Beispiel #1
1
        public object Compile(System.IO.Stream Content, List<string> references)
        {
            CodeDomProvider cc = CodeDomProvider.CreateProvider("CSharp");
            CompilerParameters cp = new CompilerParameters();
            cp.OutputAssembly = Environment.CurrentDirectory + "\\Output_csharp.dll";
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Core.dll");
            cp.ReferencedAssemblies.Add("System.Data.dll");
            cp.ReferencedAssemblies.Add("System.Xml.dll");
            cp.ReferencedAssemblies.Add("Microsoft.CSharp.dll");

            foreach (string assembly in references)
            {
                cp.ReferencedAssemblies.Add(assembly);
            }

            cp.WarningLevel = 3;

            cp.CompilerOptions = "/target:library /optimize";
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = false; //TODO check this setting

            System.IO.StreamReader sr = new System.IO.StreamReader(Content);

            CompilerResults cr = cc.CompileAssemblyFromSource(cp, sr.ReadToEnd());

            return cr;
        }
        private void LoginNormal(string username,string password,string data,ref CookieContainer cookies)
        {
            //POST login data
            Dictionary<string,string> postData = new Dictionary<string, string> ();
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create ("https://www.livecoding.tv/accounts/login/");
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705)";
            request.CookieContainer = cookies;
            request.Method = "POST";
            request.Referer = "https://www.livecoding.tv/accounts/login/";
            request.ContentType = "application/x-www-form-urlencoded";

            postData.Add ("csrfmiddlewaretoken", HtmlHelper.getAttribute(HtmlHelper.getSingleElement(data,"<input type='hidden' name='csrfmiddlewaretoken'"),"value"));
            postData.Add ("login", username);
            postData.Add ("password", password);
            byte[] postBuild = HttpHelper.CreatePostData (postData);
            request.ContentLength = postBuild.Length;
            request.GetRequestStream ().Write (postBuild, 0, postBuild.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
            using (System.IO.StreamReader sr = new System.IO.StreamReader (response.GetResponseStream ())) {
                data = sr.ReadToEnd();
            }

            if (LoginCompleted != null)
                LoginCompleted (this, cookies);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream);
            string requestFromPost = reader.ReadToEnd();

            //loop through
               // string formValue;

            string speed;
            string initialLocation;
            string finalLocation;
            string IMEI;

            if (!string.IsNullOrEmpty(Request.Form["txtSpeed"]))
            {
                //formValue = Request.Form["txtSpeed"];
                //formValue = Request.Form["txtImei"];
                speed = Request.Form["Speed"];
                initialLocation = Request.Form["initialLocation"];
                finalLocation = Request.Form["finalLocation"];
                IMEI = Request.Form["IMEI"];

                string s = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
                SqlConnection cn = new SqlConnection(s);
                cn.Open();
                SqlCommand cmd = new SqlCommand("insert into DataHistory(Speed, initialLocation, finalLocation, IMEI)values('" + speed + "','" + initialLocation + "','" + finalLocation + "','" + IMEI + "')", cn);
                cmd.ExecuteNonQuery();

            }
        }
Beispiel #4
0
        private string ReadString(string ressourcePath)
        {
            System.IO.Stream ressourceStream = null;
            System.IO.StreamReader textStreamReader = null;
            try
            {
                Assembly assembly = typeof(Addin).Assembly;
                ressourceStream = assembly.GetManifestResourceStream(assembly.GetName().Name + "." + ressourcePath);
                if (ressourceStream == null)
                    throw (new System.IO.IOException("Error accessing resource Stream."));

                textStreamReader = new System.IO.StreamReader(ressourceStream);
                if (textStreamReader == null)
                    throw (new System.IO.IOException("Error accessing resource File."));

                string text = textStreamReader.ReadToEnd();
                return text;
            }
            catch (Exception exception)
            {
                throw (exception);
            }
            finally
            {
                if (null != textStreamReader)
                    textStreamReader.Close();
                if (null != ressourceStream)
                    ressourceStream.Close();
            }
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            var file = new System.IO.StreamReader("PieCSource/Program.pie");

            string code = file.ReadToEnd();
            file.Close();

            CompilerParameters parameters = new CompilerParameters();
            parameters.ReferencedAssemblies.Add("Pie.dll");
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.GenerateInMemory = false;
            parameters.OutputAssembly = "piec.exe";
            parameters.GenerateExecutable = true;

            var provider = new PieCodeProvider();
            var results = provider.CompileAssemblyFromSource(parameters, code);

            foreach (CompilerError e in results.Errors)
            {
                Console.WriteLine(e.ErrorNumber + ", " + e.Line + ", " + e.Column + ": " + e.ErrorText);
            }

            if (results.Errors.Count == 0)
            {
                Type program = results.CompiledAssembly.GetType("Program");
                var main = program.GetMethod("Main");

                string[] strings = new string[] { "/out:test.exe", "TestCode/Program.pie", "TestCode/Hello.pie" };
                main.Invoke(null, new object[] { strings });
            }

            Console.ReadKey();
        }
Beispiel #6
0
 public static string HttpGet(string URI)
 {
     System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
     System.Net.WebResponse resp = req.GetResponse();
     System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
     return sr.ReadToEnd().Trim();
 }
Beispiel #7
0
        /// <summary>
        /// 发送Get请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public string Get(string url)
        {
            //System.Net.ServicePointManager.DefaultConnectionLimit = 512;
            //int i = System.Net.ServicePointManager.DefaultPersistentConnectionLimit;
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";
            request.Timeout = 20000;
            request.AllowAutoRedirect = false;
            request.ServicePoint.Expect100Continue = false;

            try
            {
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        return reader.ReadToEnd();
                    }
                }
                else
                    return response.StatusDescription;
            }
            catch(Exception e)
            {
                return e.Message;
            }
            finally
            {
                request = null;
            }
        }
        static void echo(string url)
        {

            var webreq = (HttpWebRequest)HttpWebRequest.Create(url + "/rest/json/echo");
            webreq.Method = "POST";
            webreq.ContentType = "application/json;charset=utf-8";
            byte[] reqecho = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject("Hello World"));
            webreq.ContentLength = reqecho.Length;
            using (var reqStream = webreq.GetRequestStream())
            {
                reqStream.Write(reqecho, 0, reqecho.Length);
            }

            var webresp = (HttpWebResponse)webreq.GetResponse();
            if (webresp.StatusCode == HttpStatusCode.OK)
            {
                using (var respReader = new System.IO.StreamReader(webresp.GetResponseStream(), Encoding.UTF8))
                {
                    var respecho = JsonConvert.DeserializeObject<string>(respReader.ReadToEnd());
                    Console.WriteLine("{0:G} Echo {1}", DateTime.Now, respecho);
                }
            }
            else
            {
                Console.WriteLine("{0:G} {1} {2}", DateTime.Now, webresp.StatusCode, webresp.StatusDescription);
            }

        }
Beispiel #9
0
        private void CheckPageForPhrase()
        {
            string html = "";
            try
            {
                System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.CreateDefault(new Uri(tbAddress.Text));
                System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse();
                System.IO.StreamReader current = new System.IO.StreamReader(resp.GetResponseStream());
                html = current.ReadToEnd();
                current.Close();
                string path = @"C:\LittleApps\HTMLPageScan\lastCheck.html";

                if (System.IO.File.Exists(path))
                {
                    System.IO.StreamReader last = System.IO.File.OpenText(path);
                    string tmpHtml = last.ReadToEnd();
                    last.Close();
                    if (html != tmpHtml)
                    {
                        SetText("\n*************" + DateTime.Now.ToShortTimeString() + "***************\nNew Item Added To Page\n");
                        WriteToDisk(path, html);
                    }
                }
                else//first time app is ever ran, otherwise the file already exists.
                {
                    WriteToDisk(path, html);
                }
                CheckHTML(html);
            }
            catch (Exception ex)
            {
                SetText(ex.Message);
            }
        }
Beispiel #10
0
        //, int CacheSeconds = 60)
        public static string GetWebResponse(string Url)
        {
            //string cachePath = Path.Combine(Settings.CachePath, "Web");
            //if (!Directory.Exists(cachePath))
            //    Directory.CreateDirectory(cachePath);
            //string cacheFile = Path.Combine(cachePath, Utils.CalculateMD5Hash(Url));

            //if (File.Exists(cacheFile) && new FileInfo(cacheFile).LastWriteTime > DateTime.Now.AddSeconds(-CacheSeconds))
            //    return File.ReadAllText(cacheFile);

            // Open a connection
            System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(Url);

            _HttpWebRequest.AllowWriteStreamBuffering = true;

            // set timeout for 20 seconds (Optional)
            _HttpWebRequest.Timeout = 20000;

            // Request response:
            using (System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse())
            {

                // Open data stream:
                using (System.IO.Stream _WebStream = _WebResponse.GetResponseStream())
                {
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(_WebStream))
                    {
                        string response = reader.ReadToEnd();
                        //File.WriteAllText(cacheFile, response);
                        return response;
                    }
                }
            }
        }
        public bool ExtractSettingsFromFile(String pathFileSettings)
        {
            try
            {
                if (System.IO.File.Exists(pathFileSettings) == true)
                {
                    System.IO.StreamReader myFile = new System.IO.StreamReader(pathFileSettings);
                    string globalContent = myFile.ReadToEnd();

                    myFile.Close();

                    if (globalContent.Contains(LineFileSeparator))
                    {
                        String[] listSettings = globalContent.Split(LineFileSeparator.ToCharArray());

                        for (int indexString = 0; indexString < listSettings.Length; indexString++)
                        {
                            if (listSettings[indexString].Contains(charToRemove.ToString()))
                            {
                                listSettings[indexString] = listSettings[indexString].Remove(listSettings[indexString].IndexOf(charToRemove), 1);
                            }
                        }
                        return ProcessSettings(listSettings);
                    }
                }

                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }
Beispiel #12
0
        private void button2_Click(object sender, EventArgs e)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create("http://vmzal04:16560/wsa/wsa1/wsdl?targetURI=urn:services-qad-com:financials:IBill:2016-05-15");

            System.Net.WebResponse resp = req.GetResponse();
            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
            string result = sr.ReadToEnd().Trim();
            XNamespace ns = XNamespace.Get("http://www.w3.org/2001/XMLSchema");

            XDocument xd = XDocument.Parse(result);
            var query = xd
     .Descendants(ns + "schema")
     .Single(element => (string)element.Attribute("elementFormDefault") == "qualified")
     .Elements(ns + "element")
     .ToDictionary(x => (string)x.Attribute("name"),
                   x => (string)x.Attribute("prodata"));


            foreach (var c in query)
            {
                System.Console.WriteLine("acct: " +
                 c.Key +
                 "\t\t\t" +
                 "contact: " +
                 c.Value);
            }
        }
        public ExecutionMirror LoadAndExecute(string fileName, ProtoCore.Core core, bool isTest = true)
        {
            string codeContent = string.Empty;

            try
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(fileName, Encoding.UTF8, true))
                {
                    codeContent = reader.ReadToEnd();
                }
            }
            catch (System.IO.IOException)
            {
                throw new FatalError("Cannot open file " + fileName);
            }

            //Start the timer
            core.StartTimer();
            core.CurrentDSFileName = ProtoCore.Utils.FileUtils.GetFullPathName(fileName);
            core.Options.RootModulePathName = core.CurrentDSFileName;

            Execute(codeContent, core);
            if (!core.Options.CompileToLib && (null != core.CurrentExecutive))
                return new ExecutionMirror(core.CurrentExecutive.CurrentDSASMExec, core);

            return null;
        }
Beispiel #14
0
        public void setLock(Event.Event  evt,int cctvid,string desc1,string desc2,int preset)
        {
            try
            {
                unlock();
                this.cctvid=cctvid;
                this.desc1=desc1;
                this.desc2=desc2;
                this.preset=preset;
                this.evt = evt;
                byte[] codebig5 =/* RemoteInterface.Util.StringToUTF8Bytes(desc2);*/         RemoteInterface.Util.StringToBig5Bytes(desc2);

                desc2 =      System.Web.HttpUtility.UrlEncode(codebig5);
                codebig5 = /* RemoteInterface.Util.StringToUTF8Bytes(desc1);   */         RemoteInterface.Util.StringToBig5Bytes(desc1);
                desc1 = System.Web.HttpUtility.UrlEncode(codebig5);
                 string uristr=string.Format(LockWindows.lockurlbase,this.wid,this.cctvid,desc1,desc2,preset);
               //  string uristr = string.Format(LockWindows.lockurlbase, 3, this.cctvid, desc1, desc2, preset);
                //只鎖定 第3號視窗

                System.Net.WebRequest web = System.Net.HttpWebRequest.Create(new Uri(uristr
                     ,UriKind.Absolute)
                 );

                System.IO.Stream stream = web.GetResponse().GetResponseStream();
                System.IO.StreamReader rd = new System.IO.StreamReader(stream);
                string res = rd.ReadToEnd();
                isLock = true;
            }
            catch (Exception ex)
            {
                isLock = false;
            }
        }
Beispiel #15
0
        private void LoginLinkedIn(string username,string password,string data,ref CookieContainer cookies)
        {
            //POST login data
            Dictionary<string,string> postData = new Dictionary<string, string> ();
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create ("https://www.linkedin.com/uas/oauth/authorize/submit");
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705)";
            request.CookieContainer = cookies;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            postData.Add ("isJsEnabled", "false");
            postData.Add ("session_key", username);
            postData.Add ("session_password", password);
            postData.Add ("agree", "true");
            postData.Add ("oauth_token", HtmlHelper.getAttribute(HtmlHelper.getSingleElement(data,"<input type=\"hidden\" name=\"oauth_token\""),"value"));
            postData.Add ("csrfToken", HtmlHelper.getAttribute(HtmlHelper.getSingleElement(data,"<input type=\"hidden\" name=\"csrfToken\""),"value"));
            postData.Add ("sourceAlias", HtmlHelper.getAttribute(HtmlHelper.getSingleElement(data,"<input type=\"hidden\" name=\"sourceAlias\""),"value"));
            //duration=0&authorize=Zugriff+erlauben&extra=&access=-3&agree=true&oauth_token=77--758ae117-ba0f-472e-b961-c05be8d12cc9&email=&appId=&csrfToken=ajax%3A3324717073940490783&sourceAlias=0_8L1usXMS_e_-SfuxXa1idxJ207ESR8hAXKfus4aDeAk&client_ts=1441384096141&client_r=%3A700951532%3A664704238%3A223863907&client_output=0&client_n=700951532%3A664704238%3A223863907&client_v=1.0.1
            postData.Add ("return_to",HtmlHelper.getAttribute(HtmlHelper.getSingleElement(data,"<input id=\"return_to\" name=\"return_to\""),"value"));

            byte[] postBuild = HttpHelper.CreatePostData (postData);
            request.ContentLength = postBuild.Length;
            request.GetRequestStream ().Write (postBuild, 0, postBuild.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
            using (System.IO.StreamReader sr = new System.IO.StreamReader (response.GetResponseStream ())) {
                data = sr.ReadToEnd();
            }

            if (LoginCompleted != null)
                LoginCompleted (this, new LoginEventArgs(data,cookies));
        }
        protected override void ExecuteCmdlet()
        {
            WebPartEntity wp = null;

            if (ParameterSetName == "FILE")
            {
                if (System.IO.File.Exists(Path))
                {
                    System.IO.StreamReader fileStream = new System.IO.StreamReader(Path);
                    string webPartString = fileStream.ReadToEnd();
                    fileStream.Close();

                    wp = new WebPartEntity();
                    wp.WebPartZone = ZoneId;
                    wp.WebPartIndex = ZoneIndex;
                    wp.WebPartXml = webPartString;
                }
            }
            else if (ParameterSetName == "XML")
            {
                wp = new WebPartEntity();
                wp.WebPartZone = ZoneId;
                wp.WebPartIndex = ZoneIndex;
                wp.WebPartXml = Xml;
            }
            if (wp != null)
            {
                this.SelectedWeb.AddWebPartToWebPartPage(PageUrl, wp);
            }
        }
Beispiel #17
0
        //
        // GET: /Proxy/
        public ActionResult Index()
        {
            string key = "<GIMMIE_KEY>";
            string secret = "<GIMMIE_SECRET>";
            string user_id = "<PLAYER_ID>";

            string queryString = Request.Url.Query;
            string[] pathArray = queryString.Split(new string[] { "gimmieapi=" }, StringSplitOptions.None);
            string path = pathArray[pathArray.Length - 1];

            string gimmieRoot = "https://api.gimmieworld.com";
            string endpoint = gimmieRoot + path;

            string access_token_secret = secret;
            string access_token = user_id;
            string url = endpoint;

            var uri = new Uri(url);
            string url2, param;
            var oAuth = new OAuthBase();
            var nonce = oAuth.GenerateNonce();
            var timeStamp = oAuth.GenerateTimeStamp();
            var signature = System.Web.HttpUtility.UrlEncode(oAuth.GenerateSignature(uri, key, secret, access_token, access_token_secret, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out url2, out param));
            var requestURL = string.Format("{0}?{1}&oauth_signature={2}", url2, param, signature);

            WebRequest req = WebRequest.Create(requestURL);
            WebResponse res = req.GetResponse();

            System.IO.Stream sm = res.GetResponseStream();
            System.IO.StreamReader s = new System.IO.StreamReader(sm);

            string output = s.ReadToEnd();

            return new ContentResult { Content = output, ContentType = "application/json" };
        }
Beispiel #18
0
 public void ReadFromResource(string filename, string carriage)
 {
     Assembly a = Assembly.GetExecutingAssembly();
     System.IO.StreamReader s = new System.IO.StreamReader(a.GetManifestResourceStream("EveMarketTool." + filename));
     string text = s.ReadToEnd();
     ReadFromString(text, carriage);
 }
 private static string LoadResource(string name)
 {
     var asm = Assembly.GetCallingAssembly();
     var stream = asm.GetManifestResourceStream(string.Format("Ember.{0}", name));
     var reader = new System.IO.StreamReader(stream);
     return reader.ReadToEnd();
 }
        public void Receive()
        {
            var form = Request.Form;

            Request.InputStream.Position = 0;
            System.IO.StreamReader str = new System.IO.StreamReader(Request.InputStream);
            string sBuf = str.ReadToEnd();

            // deserialize this from json
            var serializer = new JavaScriptSerializer();

            var updates = serializer.Deserialize<IEnumerable<Realtime>>(sBuf);

            var login = _app.WorkWith().Authentication().Login("client", "instasharp").ExecuteSync(500);

            //string typeName = "Connections";
            //var userIdsArray = updates.Select(b => b.UserId);
            //string inExpression = string.Format("{{ 'UserId' : {{ '$in' : {0} }} }}", JsonConvert.SerializeObject(userIdsArray));
            //var customFilter = JObject.Parse(inExpression);
            //var connections = _app.WorkWith().Data<Models.Connection>(typeName).Get().SetFilter(new CustomFilteringDefinition(customFilter)).ExecuteSync();

            //foreach(var connection in connections)
            //{
            //        // do something interesting
            //}
        }
        private void LoginGithub(string username,string password,string data,ref CookieContainer cookies)
        {
            //POST login data
            Dictionary<string,string> postData = new Dictionary<string, string> ();
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create ("https://github.com/session");
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705)";
            request.CookieContainer = cookies;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            postData.Add ("utf8", "\u2713");
            postData.Add ("authenticity_token", HtmlHelper.getAttribute(HtmlHelper.getSingleElement(data,"<input name=\"authenticity_token\""),"value"));
            postData.Add ("login", username);
            postData.Add ("password", password);
            postData.Add ("return_to",HtmlHelper.getAttribute(HtmlHelper.getSingleElement(data,"<input id=\"return_to\" name=\"return_to\""),"value"));

            byte[] postBuild = HttpHelper.CreatePostData (postData);
            request.ContentLength = postBuild.Length;
            request.GetRequestStream ().Write (postBuild, 0, postBuild.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
            using (System.IO.StreamReader sr = new System.IO.StreamReader (response.GetResponseStream ())) {
                data = sr.ReadToEnd();
            }

            if (LoginCompleted != null)
                LoginCompleted (this, cookies);
        }
Beispiel #22
0
 /// <summary>
 /// 发起推送请求到信鸽并获得相应
 /// </summary>
 /// <param name="url">url</param>
 /// <param name="parameters">字段</param>
 /// <returns>返回值json反序列化后的类</returns>
 private Ret CallRestful(String url, IDictionary<string, string> parameters)
 {
     if (parameters == null)
     {
         throw new ArgumentNullException("parameters");
     }
     if (string.IsNullOrEmpty(url))
     {
         throw new ArgumentNullException("url");
     }
     try
     {
         parameters.Add("access_id", accessId);
         parameters.Add("timestamp", ((int)(DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(
         new System.DateTime(1970, 1, 1))).TotalSeconds).ToString());
         parameters.Add("valid_time", valid_time.ToString());
         string md5sing = SignUtility.GetSignature(parameters, this.secretKey, url);
         parameters.Add("sign", md5sing);
         var res = HttpWebResponseUtility.CreatePostHttpResponse(url, parameters, null, null, Encoding.UTF8, null);
         var resstr = res.GetResponseStream();
         System.IO.StreamReader sr = new System.IO.StreamReader(resstr);
         var resstring = sr.ReadToEnd();
         return JsonConvert.DeserializeObject<Ret>(resstring);
     }
     catch (Exception e)
     {
         return new Ret { ret_code = -1, err_msg = e.Message };
     }
 }
Beispiel #23
0
 //Abrir
 private void abrirToolStripMenuItem_Click(object sender, EventArgs e)
 {
     load.Filter = "txt files (*.txt)|*.txt";
     if (load.ShowDialog() == System.Windows.Forms.DialogResult.OK){
         System.IO.StreamReader file = new System.IO.StreamReader(@load.FileName);
         txttexto.Text = file.ReadToEnd();}
 }
        public string fetchGowallaData(string path)
        {
            var postData = new Dictionary<string,string> () {
                { "access_token", OAuth.AccessToken }};
            var wc = new WebClient ();
            wc.Headers["Accept"] = "application/json";
            wc.Headers.Add("X-Gowalla-API-Key", OAuth.APIKey);

            var pd = PreparePostData(postData);
            try {
                foreach(var h in wc.Headers)
                {
                    Console.WriteLine(h.ToString() + ": " + wc.Headers[h.ToString()].ToString());
                }
                Console.WriteLine(baseUrl + path); //+ "?" + pd );
                //var s = wc.UploadString(baseUrl + path, "");//"?" + pd );
                var b = wc.DownloadData (baseUrl + path + "?" + pd );
                var s = Encoding.UTF8.GetString(b);

                if(!string.IsNullOrEmpty(s.ToString()))
                {
                    return s.ToString();
                }
            } catch (WebException e) {
                var x = e.Response.GetResponseStream ();
                var j = new System.IO.StreamReader (x);
                Console.WriteLine (j.ReadToEnd ());
                Console.WriteLine (e);
                // fallthrough for errors
            }
            return "";
        }
Beispiel #25
0
 /// <summary>
 /// 代理使用示例
 /// </summary>
 /// <param name="Url"></param>
 /// <param name="type"></param>
 /// <returns></returns>
 public static string GetUrltoHtml(string Url, string type = "UTF-8")
 {
     try
     {
         var request = (HttpWebRequest)WebRequest.Create(Url);
         request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
         WebProxy myProxy = new WebProxy("192.168.15.11", 8015);
         //建议连接(代理需要身份认证,才需要用户名密码)
         myProxy.Credentials = new NetworkCredential("admin", "123456");
         //设置请求使用代理信息
         request.Proxy = myProxy;
         // Get the response instance.
         System.Net.WebResponse wResp = request.GetResponse();
         System.IO.Stream respStream = wResp.GetResponseStream();
         // Dim reader As StreamReader = New StreamReader(respStream)
         using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))
         {
             return reader.ReadToEnd();
         }
     }
     catch (Exception)
     {
         //errorMsg = ex.Message;
     }
     return "";
 }
        public string AddMessagesToQueue(string qName, string oauthToken, string projectId, AddMessageReqPayload addMessageReqPayload)
        {
            string uri = string.Format("https://mq-aws-us-east-1.iron.io/1/projects/{0}/queues/{1}", projectId, qName);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            request.ContentType = "application/json";
            request.Headers.Add("Authorization", "OAuth " + oauthToken);
            request.UserAgent = "IronMQ .Net Client";
            request.Method = "POST";

            var body = JsonConvert.SerializeObject(addMessageReqPayload);

            if (body != null)
            {
                using (System.IO.StreamWriter write = new System.IO.StreamWriter(request.GetRequestStream()))
                {
                    write.Write(body);
                    write.Flush();
                }
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string resultVal = "error";
            using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream()))
            {
                resultVal = reader.ReadToEnd();
            }
            return resultVal;
        }
        public MessageCreateSuccess CreateIronMQ(string qName, string oauthToken, string projectId)
        {
            string uri = string.Format("https://mq-aws-us-east-1.iron.io/1/projects/{0}/queues/{1}", projectId, qName);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            request.ContentType = "application/json";
            request.Headers.Add("Authorization", "OAuth " + oauthToken);
            request.UserAgent = "IronMQ .Net Client";
            request.Method = "POST";

            //string body = "{\"push_type\": \"multicast\",\"subscribers\": null}";
            MsgQRequestBody body = new MsgQRequestBody();
            body.push_type = "multicast";
            body.subscribers = null;

            var bodyStr = JsonConvert.SerializeObject(body);

            if (bodyStr != null)
            {
                using (System.IO.StreamWriter write = new System.IO.StreamWriter(request.GetRequestStream()))
                {
                    write.Write(bodyStr);
                    write.Flush();
                }
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream()))
            {
                //return reader.ReadToEnd();

                return JsonConvert.DeserializeObject<MessageCreateSuccess>(reader.ReadToEnd());
            }
        }
        public void Load(string imageFilename)
        {
            this.ImageFilename = imageFilename;
            this.Filename = imageFilename.Replace(SupportedImageFormat, ".txt");
            System.IO.TextReader tr = new System.IO.StreamReader(this.Filename);
            string data = tr.ReadToEnd();
            List<EditingQuad> quads = new List<EditingQuad>();
            DataLoader.ParseData(data).ForEach(q => quads.Add(new EditingQuad(q)));

            myCanvasEditor.Clear();

            Image CalibrationImage = new Image();
            CalibrationImage.Source = new System.Windows.Media.Imaging.BitmapImage(
                new Uri(ImageFilename, UriKind.RelativeOrAbsolute));
            CalibrationImage.Width = 640;
            CalibrationImage.Height = 480;
            CalibrationImage.Stretch = Stretch.Fill;
            myCanvasEditor.Canvas.Children.Add(CalibrationImage);

            foreach (EditingQuad editingQuad in quads)
            {
                myCanvasEditor.Canvas.Children.Add(editingQuad.Polygon);
                editingQuad.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(editingQuad_PropertyChanged);
            }
            myCanvasEditor.EditableUIElements = myCanvasEditor.Canvas.Children;
            MyQuads = quads;
        }
		//private static String scriptKey = typeof(JavaScriptUtil).FullName;
 		
		private static String LibraryScript(String NomeJs)
		{
			using(System.IO.StreamReader reader = new System.IO.StreamReader(typeof(JavaScriptUtil).Assembly.GetManifestResourceStream(typeof(JavaScriptUtil),NomeJs)))
			{   
				return "<script language='javascript' type='text/javascript' >\r\n<!--\r\n" + reader.ReadToEnd() + "\r\n//-->\r\n</script>";
			}
		}
        private void LogError(HttpContext context)
        {
            try
            {
                string userName, url, data;
                userName = context.User.Identity.Name;
                CommonLogger.Info("NLog HttpException Use Name = '{0}'", userName);
                url = context.Request.Url.ToString();
                CommonLogger.Info("Url = '{0}'", url);

                HttpContext.Current.Request.InputStream.Position = 0;
                using (var reader = new System.IO.StreamReader(context.Request.InputStream))
                {
                    data = reader.ReadToEnd();
                }
                CommonLogger.Info("Data = '{0}'", data);

                foreach (var routeData in HttpContext.Current.Request.RequestContext.RouteData.Values)
                {
                    CommonLogger.Info("userName = '******' Key='{1}' Value='{2}'", userName, routeData.Key, routeData.Value);
                }
            }
            catch (Exception e)
            {
                CommonLogger.Error("An error occurs during processing unhandled exception", e);
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            string sql        = "";
            string methodName = context.Request.QueryString["method"];

            System.IO.StreamReader reader = new System.IO.StreamReader(context.Request.InputStream);
            string        value           = reader.ReadToEnd();
            DataAccessS1  dac             = new DataAccessS1();
            SqlDataReader dr;

            System.Web.Script.Serialization.JavaScriptSerializer oSerializer1;
            oSerializer1 = new System.Web.Script.Serialization.JavaScriptSerializer();
            //dynamic data;

            DataManagerS1 odem = new DataManagerS1();
            string        sJSON = "", uid = "";

            switch (methodName)
            {
            case "login":
                var    ss      = oSerializer1.Deserialize <dynamic>(value);
                string email   = ss["uid"];
                string pwd     = ss["pwd"];
                string devInfo = context.Request.QueryString["devInfo"];
                sJSON = "";
                // sql = "select (cast(ID as varchar(50))+'~'+UType+'~'+Uname) [role] from dbo.Users where email ='" + email + "' and pwd='" + pwd + "' and isdeleted=0";
                odem.Add("@email", email);
                odem.Add("@pwd", pwd);
                sJSON = Convert.ToString(odem.ExecuteScalar("LoginSP"));

                if (!string.IsNullOrEmpty(sJSON))
                {
                    //sJSON = "{\"uid\":\"" + sJSON.Split('~')[0] + "\",\"role\":\"" + sJSON.Split('~')[1].ToLower() + "\",\"name\":\"" + sJSON.Split('~')[2].ToLower() + "\"}";
                    sJSON = "{\"uid\":\"" + sJSON.Split('~')[0] + "\",\"role\":\"" + sJSON.Split('~')[1].ToLower() + "\",\"name\":\"" + sJSON.Split('~')[2].ToLower() + "\",\"email\":\"" + sJSON.Split('~')[3] + "\",\"mob\":\"" + sJSON.Split('~')[4] + "\"}";
                }
                //context.Response.ContentType = "application/text";
                break;

            case "register":
                ss   = oSerializer1.Deserialize <dynamic>(value);
                odem = new DataManagerS1();
                odem.Add("@UName", ss["name"]);
                odem.Add("@Address", ss["add"]);
                odem.Add("@Email", ss["uid"]);
                odem.Add("@Pwd", ss["pwd"]);
                odem.Add("@Mobile", ss["mob"]);
                odem.Add("@UType", "c");
                odem.Add("@CreatedBy", 0);
                try
                {
                    if (odem.ExecuteNonQuery("RegisterSP") > 0)
                    {
                        sJSON = "1";
                    }
                }
                catch
                {
                    sJSON = "";
                }
                //context.Response.ContentType = "application/text";
                break;

            case "Categories":
                dac = new DataAccessS1();
                sql = "select ID,Cname,CImg from CategoryMaster where IsDeleted=0";
                dr  = dac.ExecuteReader(sql, CommandType.Text);
                List <Category> lstCategory = new List <Category>();
                Category        objCategory;
                while (dr.Read())
                {
                    objCategory       = new Category();
                    objCategory.ID    = dr["ID"].ToString();
                    objCategory.Cname = dr["Cname"].ToString();
                    objCategory.CImg  = dr["CImg"].ToString();

                    lstCategory.Add(objCategory);
                }
                dr.Close();
                oSerializer1 =
                    new System.Web.Script.Serialization.JavaScriptSerializer();
                sJSON = oSerializer1.Serialize(lstCategory);
                break;

            case "SubCategories":
                SqlDataReader   sqlDataReader5 = new DataAccessS1().ExecuteReader("select ID,SubCatName,Simg from SubCatMaster where IsDeleted=0 and CategoryMasterID=" + context.Request.QueryString["catid"], CommandType.Text);
                List <Category> categoryList2  = new List <Category>();
                while (sqlDataReader5.Read())
                {
                    categoryList2.Add(new Category()
                    {
                        ID    = sqlDataReader5["ID"].ToString(),
                        Cname = sqlDataReader5["SubCatName"].ToString(),
                        CImg  = sqlDataReader5["Simg"].ToString()
                    });
                }
                sqlDataReader5.Close();
                sJSON = new JavaScriptSerializer().Serialize((object)categoryList2);
                break;

            case "Productsbkp":
                string catid = context.Request.QueryString["catid"];
                dac = new DataAccessS1();
                sql = "select * from Products where IsDeleted=0 and CategoryMasterID=" + catid;
                dr  = dac.ExecuteReader(sql, CommandType.Text);
                List <Product> lstProduct = new List <Product>();
                Product        objProduct;
                while (dr.Read())
                {
                    objProduct       = new Product();
                    objProduct.ID    = dr["ID"].ToString();
                    objProduct.Pname = dr["Pname"].ToString();
                    objProduct.Pimg  = dr["Pimg"].ToString();

                    objProduct.PDesc      = dr["PDesc"].ToString();
                    objProduct.PShortDesc = dr["PShortDesc"].ToString();
                    objProduct.Price      = dr["Price"].ToString();

                    lstProduct.Add(objProduct);
                }
                dr.Close();
                oSerializer1 =
                    new System.Web.Script.Serialization.JavaScriptSerializer();
                sJSON = oSerializer1.Serialize(lstProduct);
                break;

            case "Products":
                SqlDataReader  sqlDataReader3 = new DataAccessS1().ExecuteReader("select * from Products where IsDeleted=0 and SubCategoryMasterID=" + context.Request.QueryString["scatid"], CommandType.Text);
                List <Product> productList1   = new List <Product>();
                while (sqlDataReader3.Read())
                {
                    productList1.Add(new Product()
                    {
                        ID         = sqlDataReader3["ID"].ToString(),
                        Pname      = sqlDataReader3["Pname"].ToString(),
                        Pimg       = sqlDataReader3["Pimg"].ToString(),
                        PDesc      = sqlDataReader3["PDesc"].ToString(),
                        PShortDesc = sqlDataReader3["PShortDesc"].ToString(),
                        Price      = sqlDataReader3["Price"].ToString()
                    });
                }
                sqlDataReader3.Close();
                sJSON = new JavaScriptSerializer().Serialize((object)productList1);
                break;

            case "addtocart":
                uid = context.Request.QueryString["uid"];
                string pid = context.Request.QueryString["pid"];
                dac = new DataAccessS1();
                dac.addParam("@custid", uid);
                dac.addParam("@productid", pid);
                if (dac.ExecuteQuerySP("spAddToCart") > 0)
                {
                    sJSON = "1";
                }
                //string AmcID = context.Request.QueryString["AMCID"];
                //string amcdetailid = context.Request.QueryString["AMCDetailID"];
                //string Problem = context.Request.QueryString["Problem"];
                break;

            case "viewcart":
                uid        = context.Request.QueryString["uid"];
                dac        = new DataAccessS1();
                sql        = @"select C.ID,p.Pname,(p.Price*C.Qty) [Price],P.Pimg,C.Qty,P.PShortDesc,P.ID [PID] from dbo.Products P join dbo.CartDetails C on P.ID=C.ProductID 
                            where P.IsDeleted=0 and C.CustID=" + uid;
                dr         = dac.ExecuteReader(sql, CommandType.Text);
                lstProduct = new List <Product>();
                //Product objProduct;
                while (dr.Read())
                {
                    objProduct       = new Product();
                    objProduct.ID    = dr["ID"].ToString();
                    objProduct.Pname = dr["Pname"].ToString();
                    objProduct.Pimg  = dr["Pimg"].ToString();

                    objProduct.PShortDesc = dr["PShortDesc"].ToString();
                    objProduct.Price      = dr["Price"].ToString();
                    objProduct.Qty        = dr["Qty"].ToString();
                    objProduct.PID        = dr["PID"].ToString();
                    lstProduct.Add(objProduct);
                }
                dr.Close();
                oSerializer1 =
                    new System.Web.Script.Serialization.JavaScriptSerializer();
                sJSON = oSerializer1.Serialize(lstProduct);
                break;

            case "removefromcart":
                uid = context.Request.QueryString["uid"];
                string cartid = context.Request.QueryString["cartid"];
                sql = "delete from dbo.CartDetails where Id=" + cartid;
                if (dac.executeTQuery(sql) > 0)
                {
                    sJSON = "1";
                }
                break;

            case "getproducts":
                uid = context.Request.QueryString["uid"];
                pid = context.Request.QueryString["pid"];
                dac = new DataAccessS1();
                if (pid == "0")
                {
                    sql = @"select C.ID,p.Pname,(p.Price*C.Qty) [Price],P.Pimg,C.Qty,P.PShortDesc,P.ID [PID] from dbo.Products P join dbo.CartDetails C on P.ID=C.ProductID 
                            where P.IsDeleted=0 and C.CustID=" + uid;
                }
                else
                {
                    sql = "select p.ID,p.Pname, [Price],P.Pimg,1 [Qty],P.PShortDesc,P.ID [PID] from dbo.Products p where ID=" + pid;
                }
                dr         = dac.ExecuteReader(sql, CommandType.Text);
                lstProduct = new List <Product>();
                //Product objProduct;
                while (dr.Read())
                {
                    objProduct       = new Product();
                    objProduct.ID    = dr["ID"].ToString();
                    objProduct.Pname = dr["Pname"].ToString();
                    objProduct.Pimg  = dr["Pimg"].ToString();

                    objProduct.PShortDesc = dr["PShortDesc"].ToString();
                    objProduct.Price      = dr["Price"].ToString();
                    objProduct.Qty        = dr["Qty"].ToString();
                    objProduct.PID        = dr["PID"].ToString();
                    lstProduct.Add(objProduct);
                }
                dr.Close();
                oSerializer1 =
                    new System.Web.Script.Serialization.JavaScriptSerializer();
                sJSON = oSerializer1.Serialize(lstProduct);
                break;

            case "Order":
                string       str3           = context.Request.QueryString["uid"];
                string       str4           = context.Request.QueryString["pid"];
                string       str5           = context.Request.QueryString["payAmt"];
                string       str6           = context.Request.QueryString["ActualAmt"];
                string       str7           = context.Request.QueryString["AdvAmt"];
                string       str8           = context.Request.QueryString["PaymentMode"];
                string       str9           = context.Request.QueryString["AdvType_Half_Full"];
                string       str10          = context.Request.QueryString["Qty"];
                string       str11          = context.Request.QueryString["paymentID"];
                string       NameSP         = "SaveOrder";
                DataAccessS1 dataAccessS1_2 = new DataAccessS1();
                dataAccessS1_2.addParam("@uid", (object)str3);
                dataAccessS1_2.addParam("@pid", (object)str4);
                dataAccessS1_2.addParam("@ActualAmt", (object)str6);
                dataAccessS1_2.addParam("@AdvAmt", (object)str7);
                dataAccessS1_2.addParam("@PaymentMode", (object)str8);
                dataAccessS1_2.addParam("@AdvType_Half_Full", (object)str9);
                dataAccessS1_2.addParam("@Qty", (object)str10);
                dataAccessS1_2.addParam("@paymentID", (object)str11);
                dataAccessS1_2.addParam("@Address", context.Request.QueryString["address"]);
                dataAccessS1_2.addParam("@City", context.Request.QueryString["city"]);
                dataAccessS1_2.addParam("@Pin", context.Request.QueryString["pin"]);
                dataAccessS1_2.addParam("@LandMark", context.Request.QueryString["landmark"]);
                sJSON = "";
                if (dataAccessS1_2.ExecuteQuerySP(NameSP) > 0)
                {
                    sJSON = "1";
                    break;
                }
                break;

            case "vieworder":
                SqlDataReader  sqlDataReader10 = new DataAccessS1().ExecuteReader("select OD.ID,p.Pname,(OD.Price*OD.Qty) [Price],P.Pimg,OD.Qty,P.PShortDesc,P.ID [PID],OD.sts \r\n                            from dbo.Products P join dbo.OrderDetails OD on P.ID=OD.ProductID \r\n                                                join dbo.OrderMaster OM on OD.OrderMasterID=OM.ID\r\n                             where P.IsDeleted=0 and OM.CustID=" + context.Request.QueryString["uid"], CommandType.Text);
                List <Product> productList4    = new List <Product>();
                while (sqlDataReader10.Read())
                {
                    productList4.Add(new Product()
                    {
                        ID         = sqlDataReader10["ID"].ToString(),
                        Pname      = sqlDataReader10["Pname"].ToString(),
                        Pimg       = sqlDataReader10["Pimg"].ToString(),
                        PShortDesc = sqlDataReader10["PShortDesc"].ToString(),
                        Price      = sqlDataReader10["Price"].ToString(),
                        Qty        = sqlDataReader10["Qty"].ToString(),
                        PID        = sqlDataReader10["PID"].ToString(),
                        OrderSts   = sqlDataReader10["sts"].ToString()
                    });
                }
                sqlDataReader10.Close();
                sJSON = new JavaScriptSerializer().Serialize((object)productList4);
                break;

            case "NewOrderAdmin":
                sql             = @"SELECT O.[ID]
                          ,[CustID]
	                      ,u.UName
                          ,[OrderValue]
                          ,convert(varchar(10),[Date],103) [Date]
                          ,[Remarks]
                          ,[OrderNo]
                          ,[PayMode]
                          ,[AdvAmt]
                          ,[AdvType_Half_Full]
                          ,[PaymentID]
                          ,O.[Address]
                          ,[City]
                          ,[Pin]
                          ,[LandMark]
                      FROM [dbo].[OrderMaster] O join Users u on U.ID=O.CustID where O.Sts='OrderReceived'";
                dac             = new DataAccessS1
                             dr = dac.ExecuteReader(sql, CommandType.Text);
                lstProduct      = new List <Product>();
                //Product objProduct;
                while (dr.Read())
                {
                    objProduct       = new Product();
                    objProduct.ID    = dr["ID"].ToString();
                    objProduct.Pname = dr["Pname"].ToString();
                    objProduct.Pimg  = dr["Pimg"].ToString();

                    objProduct.PShortDesc = dr["PShortDesc"].ToString();
                    objProduct.Price      = dr["Price"].ToString();
                    objProduct.Qty        = dr["Qty"].ToString();
                    objProduct.PID        = dr["PID"].ToString();
                    lstProduct.Add(objProduct);
                }
                dr.Close();
                oSerializer1 =
                    new System.Web.Script.Serialization.JavaScriptSerializer();
                sJSON = oSerializer1.Serialize(lstProduct);
                break;

            case "PendingCallListSE":
                uid = context.Request.QueryString["uid"];
                string sts = context.Request.QueryString["sts"];
                sql = "GetAssignedCallSEStatuswise";
                dac = new DataAccessS1();
                dac.addParam("@SEID", uid);
                dac.addParam("@Status", sts);
                dr = dac.ExecuteReader(sql, CommandType.StoredProcedure);
                List <CallList> lstCall = new List <CallList>();
                CallList        objCallList;
                while (dr.Read())
                {
                    objCallList = new CallList();
                    objCallList.ExpectedDate   = dr["ExpectedDate"].ToString();
                    objCallList.Party          = dr["Party"].ToString();
                    objCallList.Address        = dr["Address"].ToString();
                    objCallList.Mobile1        = dr["Mobile1"].ToString();
                    objCallList.Product        = dr["Product"].ToString();
                    objCallList.DistributionID = dr["DistributionID"].ToString();
                    objCallList.Problem        = dr["Problem"].ToString();
                    objCallList.AMCDetailID    = dr["AMCDetailID"].ToString();
                    lstCall.Add(objCallList);
                }
                dr.Close();
                oSerializer1 =
                    new System.Web.Script.Serialization.JavaScriptSerializer();
                sJSON = oSerializer1.Serialize(lstCall);
                break;

            case "ProductsPartyWise":
                uid = context.Request.QueryString["uid"];
                sql = "GetProductsPartyWise";
                dac = new DataAccessS1();
                dac.addParam("@PartyID", uid);
                dr      = dac.ExecuteReader(sql, CommandType.StoredProcedure);
                lstCall = new List <CallList>();
                while (dr.Read())
                {
                    objCallList = new CallList();
                    //objCallList.Party = dr["Party"].ToString();
                    objCallList.Product     = dr["Product"].ToString();
                    objCallList.EndDate     = dr["EndDate"].ToString();
                    objCallList.ProductSlNo = dr["ProductSlNo"].ToString();
                    objCallList.AMCDetailID = dr["AMCDetailID"].ToString();
                    objCallList.AMCID       = dr["AMCID"].ToString();
                    lstCall.Add(objCallList);
                }
                dr.Close();
                oSerializer1 =
                    new System.Web.Script.Serialization.JavaScriptSerializer();
                sJSON = oSerializer1.Serialize(lstCall);
                break;

            case "partycallbooking":
                uid = context.Request.QueryString["uid"];
                string AmcID       = context.Request.QueryString["AMCID"];
                string amcdetailid = context.Request.QueryString["AMCDetailID"];
                string Problem     = context.Request.QueryString["Problem"];
                sql = string.Format(@"INSERT INTO [dbo].[CallBooking]
                                       ([AMCID]
                                       ,[AMCDetailID]
                                       ,[DueDate]
                                       ,[Problem]
                                       ,[ExpectedDate])
                                        VALUES({0},{1},'{2}','{3}','{4}')", AmcID, amcdetailid, DateTime.Now.ToString("yyyyMMdd"), Problem.Replace("'", "''"), DateTime.Now.AddDays(20).ToString("yyyyMMdd"));
                dac.executeTQueryEx(sql);
                sJSON = "1";
                break;

            case "updateCall":
                uid = context.Request.QueryString["uid"];
                sts = context.Request.QueryString["sts"];
                string distID      = context.Request.QueryString["distID"];
                string rem         = context.Request.QueryString["remarks"];
                string completed   = context.Request.QueryString["completed"];
                string OTP         = context.Request.QueryString["OTP"];
                string AMCDetailID = context.Request.QueryString["AMCDetailID"];
                if (sts == "C")
                {
                    if (dac.returnString("select OTP from AMCDetails where AMCDetailID=" + AMCDetailID) != OTP)
                    {
                        sJSON = "0";
                        break;
                    }
                }
                if (!string.IsNullOrEmpty(distID))
                {
                    sql = "updateCallBookingAndDist";
                    dac = new DataAccessS1();
                    dac.addParam("@distid", distID);
                    dac.addParam("@rem", rem);
                    dac.addParam("@uid", uid);
                    dac.addParam("@iscomplete", completed);
                    dac.addParam("@sts", sts);
                    dr = dac.ExecuteReader(sql, CommandType.StoredProcedure);

                    oSerializer1 =
                        new System.Web.Script.Serialization.JavaScriptSerializer();
                    //sJSON = oSerializer1.Serialize(lstCall);
                    sJSON = "1";
                }
                break;

            case "otpgen":
                amcdetailid = context.Request.QueryString["AMCDetailID"];
                dac         = new DataAccessS1();
                dac.addParam("@amcdetailid", amcdetailid);
                dr = dac.ExecuteReader("OTPgeneration", CommandType.StoredProcedure);
                string otp = "", no = "";
                while (dr.Read())
                {
                    otp = dr["OTP"].ToString();
                    no  = dr["Mobile1"].ToString();
                }
                dr.Close();
                Api.Classes.Mailer.SendSMS(no, "OTP for call update is " + otp);
                sJSON = "1";
                break;

            case "amcalert":
                uid = context.Request.QueryString["uid"];
                sql = @"select P.Name [Product],AD.ProductSlNo,
                            convert(varchar(10),AD.startdate,103) StartDate,convert(varchar(10),AD.EndDate,103) EndDate,AD.AMCID
                                    from [dbo].[AMCDetails] AD join Master_AMC A on A.AMCID=AD.AMCID
                                    join [dbo].[Master_Party] MP on MP.PartyID=A.PartyID
									join [dbo].[Product] P on P.ProductID=AD.ProductID where A.PartyID="                                     + uid + " and GETDATE() > DATEADD(day,-15,EndDate)";

                dac     = new DataAccessS1();
                dr      = dac.ExecuteReader(sql, CommandType.Text);
                lstCall = new List <CallList>();
                while (dr.Read())
                {
                    objCallList             = new CallList();
                    objCallList.ProductSlNo = dr["ProductSlNo"].ToString();
                    objCallList.EndDate     = dr["EndDate"].ToString();
                    objCallList.Product     = dr["Product"].ToString();
                    lstCall.Add(objCallList);
                }
                dr.Close();
                oSerializer1 =
                    new System.Web.Script.Serialization.JavaScriptSerializer();
                sJSON = oSerializer1.Serialize(lstCall);
                break;

            case "secallattended":

                break;

            case "requestamc":
                uid = context.Request.QueryString["uid"];
                string partyname = context.Request.QueryString["partyname"];
                sql = string.Format(@"INSERT INTO [dbo].[AmcRequests]
                                       ([PartyID]
                                       ,[ProductName]
                                       ,[SerialNo]
                                       ,[Model]
                                       ,[OtherInfo]
                                       )
                                        VALUES({0},'{1}','{2}','{3}','{4}')", uid, context.Request.QueryString["pname"], context.Request.QueryString["slno"],
                                    context.Request.QueryString["model"], context.Request.QueryString["other"]);
                if (dac.executeTQuery(sql) > 0)
                {
                    sJSON = "1";
                    string body = string.Format(@"Hello,< br /> New AMC request generated.Details below.<br/><strong>Party :&nbsp;</strong>{0}
                                                   <strong>Product :&nbsp;</strong>{1}<strong>Model :&nbsp;</strong>{2}<strong>Serial No :&nbsp;</strong>{3}
                                                   <strong>Remarks :&nbsp;</strong>{4}", partyname, context.Request.QueryString["pname"], context.Request.QueryString["model"]
                                                , context.Request.QueryString["slno"], context.Request.QueryString["other"]);

                    Api.Classes.Mailer.SendMail(dac.GetAppSettings("AmcRequestMailID"), "New Amc Request", body);
                }
                break;
            }
            context.Response.Write(sJSON);
            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
        }
        /// <summary>
        /// 根据Url地址Get请求返回实体
        /// xuja
        /// 2015年11月12日14:50:02
        /// </summary>
        /// <param name="url">请求的地址</param>
        /// <returns>实体</returns>
        public static T GetResponse <T>(string url)
        {
            HttpClient httpClient = new HttpClient(new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.GZip
            });
            HttpResponseMessage response = null;

            try
            {
                //using (HttpClient httpClient = new HttpClient())
                //{
                //httpClient.MaxResponseContentBufferSize = 256000;
                httpClient.DefaultRequestHeaders.Add("user-agent", userAgen);
                httpClient.CancelPendingRequests();
                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                //HttpResponseMessage response = httpClient.GetAsync(url).Result;
                Task <HttpResponseMessage> taskResponse = httpClient.GetAsync(url);
                taskResponse.Wait();
                T result = default(T);
                response = taskResponse.Result;
                //using (HttpResponseMessage response = taskResponse.Result)
                //{
                if (response.IsSuccessStatusCode)
                {
                    Task <System.IO.Stream> taskStream = response.Content.ReadAsStreamAsync();
                    taskStream.Wait();
                    System.IO.Stream       dataStream = taskStream.Result;
                    System.IO.StreamReader reader     = new System.IO.StreamReader(dataStream);
                    string s = reader.ReadToEnd();

                    result = JsonConvert.DeserializeObject <T>(s);
                }
                //}
                return(result);
                //}
            }
            catch (Exception e)
            {
                var resp = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = new StringContent(e.ToString()),
                    ReasonPhrase = "error"
                };
                //throw new HttpResponseException(resp);
                return(default(T));
            }
            finally
            {
                if (response != null)
                {
                    response.Dispose();
                }
                if (httpClient != null)
                {
                    httpClient.Dispose();
                }
            }
        }
Beispiel #33
0
        internal void loadData(string Filename)
        {
            System.IO.StreamReader reader = new System.IO.StreamReader(Filename);

            string curLine        = reader.ReadLine();
            bool   serverDataRead = false;

            name    = desc = imgFilename = string.Empty;
            density = nominalPrice = systemAvailability = systemUsage = 0;

            while (curLine != null)
            {
                if (base.loadData(reader, curLine, DataType.Resource))
                {
                    serverDataRead = true;
                }
                else if (curLine.ToUpper().StartsWith("NAME="))
                {
                    name = curLine.Substring("NAME=".Length);
                }
                else if (curLine.ToUpper() == "[DESCRIPTION]")
                {
                    desc = reader.ReadToEnd();
                }
                else if (curLine.ToUpper().StartsWith("DENSITY="))
                {
                    if (!double.TryParse(curLine.Substring("DENSITY=".Length), out density))
                    {
                        throw new InvalidResourceData();
                    }
                }
                else if (curLine.ToUpper().StartsWith("NOMPRICE="))
                {
                    if (!double.TryParse(curLine.Substring("NOMPRICE=".Length), out nominalPrice))
                    {
                        throw new InvalidResourceData();
                    }
                }
                else if (curLine.ToUpper().StartsWith("SYSTEMAVAILABILITY="))
                {
                    if (!double.TryParse(curLine.Substring("SYSTEMAVAILABILITY=".Length), out systemAvailability))
                    {
                        throw new InvalidResourceData();
                    }
                }
                else if (curLine.ToUpper().StartsWith("SYSTEMUSAGE="))
                {
                    if (!double.TryParse(curLine.Substring("SYSTEMUSAGE=".Length), out systemUsage))
                    {
                        throw new InvalidResourceData();
                    }
                }
                else if (curLine.ToUpper().StartsWith("IMGFILENAME="))
                {
                    imgFilename = curLine.Substring("IMGFILENAME=".Length);
                }

                curLine = reader.ReadLine();
            }

            if (!serverDataRead)
            {
                throw new NoServerDataException();
            }
            if (name.Length == 0 || desc.Length == 0 || imgFilename.Length == 0 || nominalPrice == 0 || density == 0 || systemAvailability == 0 || systemUsage == 0)
            {
                throw new InvalidResourceData();
            }
        }
Beispiel #34
0
        /// <summary>
        /// Load defined Lua Script File
        /// </summary>
        /// <param name="component">Component Owner</param>
        private void LoadFile(SmartComponent component)
        {
            string fileName = (string)component.Properties["LuaFile"].Value;

            string fileContent = string.Empty;
            bool   onError     = false;

            if (luaStates == null)
            {
                luaStates = new Dictionary <string, lua_State>();
            }

            if (!luaStates.ContainsKey(component.UniqueId))
            {
                luaStates[component.UniqueId] = null;
            }

            if (string.IsNullOrEmpty(fileName))
            {
                return;
            }

            try
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(fileName))
                {
                    fileContent = reader.ReadToEnd();
                }
            }
            catch (Exception ex) when(ex is System.IO.FileNotFoundException || ex is System.IO.DirectoryNotFoundException || ex is System.IO.IOException)
            {
                Logger.AddMessage("RSLuaScript: Can't open file: " + fileName + ".", LogMessageSeverity.Error);
                onError = true;
            }

            if (!string.IsNullOrEmpty(fileContent))
            {
                int       ret       = 0;
                lua_State _luaState = luaStates[component.UniqueId];
                if (!(_luaState is null))
                {
                    //Already setted: clean it
                    lua_close(_luaState);
                }
                _luaState = lua_open();
                luaL_openlibs(_luaState);

                //Set component parent
                lua_pushfstring(_luaState, component.UniqueId);
                lua_setglobal(_luaState, "SmartComponent");

                //Push SetStatus function
                lua_pushcfunction(_luaState, SetStatus);
                lua_setglobal(_luaState, "set_status");

                //Push AddLog function
                lua_pushcfunction(_luaState, AddLog);
                lua_setglobal(_luaState, "add_log");

                //Push ClearSignals function
                lua_pushcfunction(_luaState, ClearSignals);
                lua_setglobal(_luaState, "clear_signals");

                //Push AddSignal function
                lua_pushcfunction(_luaState, AddSignal);
                lua_setglobal(_luaState, "add_signal");

                //Push GetSignal function
                lua_pushcfunction(_luaState, GetSignal);
                lua_setglobal(_luaState, "get_signal");

                //Push SetSignal function
                lua_pushcfunction(_luaState, SetSignal);
                lua_setglobal(_luaState, "set_signal");

                //Push IIf function
                lua_pushcfunction(_luaState, IIf);
                lua_setglobal(_luaState, "iif");

                //Push GetLastSimulationTime function
                lua_pushcfunction(_luaState, GetLastSimulationTime);
                lua_setglobal(_luaState, "get_last_simulation_time");

                //Push AddIOConnection function
                lua_pushcfunction(_luaState, AddIOConnection);
                lua_setglobal(_luaState, "add_io_connection");

                //Update List for Lua script calls
                luaStates[component.UniqueId] = _luaState;
                UpdateComponentList(component);

                ret = luaL_loadbuffer(_luaState, fileContent, (uint)fileContent.Length, "program");
                if (ret != 0)
                {
                    Logger.AddMessage("RSLuaScript: " + component.Name + ": Error when loading open file: " + lua_tostring(_luaState, -1)?.ToString() + ".", LogMessageSeverity.Error);
                    onError = true;
                }
                else
                {
                    ret = lua_pcall(_luaState, 0, 0, 0);
                    if (ret != 0)
                    {
                        Logger.AddMessage("RSLuaScript: " + component.Name + ": Error when running main: " + lua_tostring(_luaState, -1)?.ToString() + ".", LogMessageSeverity.Error);
                        onError = true;
                    }
                    else
                    {
                        component.Properties["Status"].Value = "File loaded";
                    }
                }
            }
            if (onError)
            {
                component.Properties["LuaFile"].Value = "";
            }

            //Check connections on load (occurs the first time a signal change after reload component as no new connection event exists)
            if (component.ContainingProject is Station station)
            {
                foreach (IOConnection ioConn in station.Connections)
                {
                    if (!ioConn.AllowCycle)
                    {
                        if (ioConn.SourceObjectName == component.Name)
                        {
                            Logger.AddMessage("RSLuaScript: " + component.Name + ": Connection from " + ioConn.SourceSignal + " to "
                                              + ioConn.TargetObjectName + "." + ioConn.TargetSignal + " should allow cyclic connection.", LogMessageSeverity.Warning);
                        }
                        if (ioConn.TargetObjectName == component.Name)
                        {
                            Logger.AddMessage("RSLuaScript: " + component.Name + ": Connection from " + ioConn.SourceObjectName + "." + ioConn.SourceSignal + " to "
                                              + ioConn.TargetSignal + " should allow cyclic connection.", LogMessageSeverity.Warning);
                        }
                    }
                }
            }
        }
Beispiel #35
0
        internal static void GetToken(SocialType type, ClientInfo client, string code, Action <AccessToken> action)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(GetTokenUrl(type, client, code));

            httpWebRequest.Method = "POST";

            httpWebRequest.BeginGetResponse((p) =>
            {
                HttpWebRequest request = (HttpWebRequest)p.AsyncState;
                HttpWebResponse httpWebResponse;
                try
                {
                    httpWebResponse = (HttpWebResponse)request.EndGetResponse(p);
                }
                catch (WebException ex)
                {
                    return;
                }
                if (httpWebResponse != null)
                {
                    using (var stream = httpWebResponse.GetResponseStream())
                    {
                        AccessToken token = new AccessToken();
                        if (type == SocialType.Tencent)
                        {
                            using (var reader = new System.IO.StreamReader(stream))
                            {
                                string text = reader.ReadToEnd();
                                if (!string.IsNullOrEmpty(text))
                                {
                                    //access_token=ec70e646177f025591e4282946c19b67&expires_in=604800&name=xshf12345
                                    var acc = text.Split('&');
                                    foreach (var item in acc)
                                    {
                                        var single = item.Split('=');
                                        if (single[0] == "access_token")
                                        {
                                            token.Token = single[1];
                                        }
                                        else if (single[0] == "expires_in")
                                        {
                                            token.ExpiresTime = DateTime.Now.AddSeconds(Convert.ToInt32(single[1]));
                                        }
                                        else if (single[0] == "name")
                                        {
                                            token.UserInfo = single[1];
                                        }
                                    }
                                    token.OpenId = client.Tag;
                                }
                            }
                        }
                        else if (type == SocialType.Weibo)
                        {
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Weibo.WeiboAccessToken));
                            var item          = ser.ReadObject(stream) as Weibo.WeiboAccessToken;
                            item.ExpiresTime  = DateTime.Now.AddSeconds(Convert.ToDouble(item.expires_in));
                            token.Token       = item.access_token;
                            token.ExpiresTime = item.ExpiresTime;
                            token.UserInfo    = item.uid;
                        }
                        else if (type == SocialType.Renren)
                        {
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Renren.RenrenAccessToken));
                            var item          = ser.ReadObject(stream) as Renren.RenrenAccessToken;
                            item.ExpiresTime  = DateTime.Now.AddSeconds(Convert.ToDouble(item.expires_in));
                            token.Token       = item.access_token;
                            token.ExpiresTime = item.ExpiresTime;
                            token.UserInfo    = item.user.name;
                        }
                        string filePath = string.Format(SocialAPI.ACCESS_TOKEN_PREFIX, type.ToString());
                        JsonHelper.SerializeData <AccessToken>(filePath, token);
                        action(token);
                    }
                }
            }, httpWebRequest);
        }
Beispiel #36
0
        // Invoked after the user has authorized us
        //
        // TODO: this should return the stream error for invalid passwords instead of
        // just true/false.
        public bool AcquireAccessToken()
        {
            var headers = new Dictionary <string, string>()
            {
                { "oauth_consumer_key", provider.ConsumerKey },
                { "oauth_nonce", MakeNonce() },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_timestamp", MakeTimestamp() },
                { "oauth_version", "1.0" }
            };
            var content = "";

            if (xAuthUsername == null)
            {
                headers.Add("oauth_token", OAuthUtils.PercentEncode(AuthorizationToken));
                headers.Add("oauth_verifier", OAuthUtils.PercentEncode(AuthorizationVerifier));
            }
            else
            {
                headers.Add("x_auth_username", OAuthUtils.PercentEncode(xAuthUsername));
                headers.Add("x_auth_password", OAuthUtils.PercentEncode(xAuthPassword));
                headers.Add("x_auth_mode", "client_auth");
                content = String.Format("x_auth_mode=client_auth&x_auth_password={0}&x_auth_username={1}", OAuthUtils.PercentEncode(xAuthPassword), OAuthUtils.PercentEncode(xAuthUsername));
            }

            string signature           = MakeSignature("POST", provider.AccessTokenUrl, headers);
            string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, RequestTokenSecret);
            string oauth_signature     = MakeOAuthSignature(compositeSigningKey, signature);

            var wc = new WebClient();

            headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature));
            if (xAuthUsername != null)
            {
                headers.Remove("x_auth_username");
                headers.Remove("x_auth_password");
                headers.Remove("x_auth_mode");
            }
            wc.Headers[HttpRequestHeader.Authorization] = HeadersToOAuth(headers);

            try
            {
                var result = HttpUtility.ParseQueryString(wc.UploadString(new Uri(provider.AccessTokenUrl), content));

                if (result["oauth_token"] != null)
                {
                    AccessToken       = result["oauth_token"];
                    AccessTokenSecret = result["oauth_token_secret"];
                    AuthInfo          = result.ToDictionary();

                    return(true);
                }
            }
            catch (WebException e)
            {
                var x = e.Response.GetResponseStream();
                var j = new System.IO.StreamReader(x);
                Console.WriteLine(j.ReadToEnd());
                Console.WriteLine(e);
                // fallthrough for errors
            }
            return(false);
        }
Beispiel #37
0
        private void ReadFile_Click(object sender, EventArgs e)
        {
            if (ReadFileName.Text.Length <= 0)
            {
                MessageBox.Show("先輩!何でファイル名書いてないんすか!\nやめてくださいよ本当に!",
                                "ああああああ!!テメェェェ!!何してんだよァァァ!!",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Hand);

                return;
            }

            enemyMSList.ems.Clear();

            System.IO.StreamReader sr = null;
            try
            {
                sr = new System.IO.StreamReader("data/" + ReadFileName.Text + ".txt");

                string[] txt = sr.ReadToEnd().Split(' ');
                int      tmp = 0;

                TexturePath.Text     = txt[tmp++];
                TextureName.Text     = txt[tmp++];
                MaxLife.Value        = decimal.Parse(txt[tmp++]);
                HitDamage.Value      = decimal.Parse(txt[tmp++]);
                MoveSpeed.Value      = decimal.Parse(txt[tmp++]);
                JumpPower.Value      = decimal.Parse(txt[tmp++]);
                IsUseGrabity.Checked = int.Parse(txt[tmp++]) == 1;

                BaseW.Value = decimal.Parse(txt[tmp++]);
                BaseH.Value = decimal.Parse(txt[tmp++]);
                BaseD.Value = decimal.Parse(txt[tmp++]);

                DamageCameraPosX.Value = decimal.Parse(txt[tmp++]);
                DamageCameraPosY.Value = decimal.Parse(txt[tmp++]);
                DamageCameraPosZ.Value = decimal.Parse(txt[tmp++]);
                DamageCameraW.Value    = decimal.Parse(txt[tmp++]);
                DamageCameraH.Value    = decimal.Parse(txt[tmp++]);
                DamageCameraD.Value    = decimal.Parse(txt[tmp++]);
                VisibillityPosX.Value  = decimal.Parse(txt[tmp++]);
                VisibillityPosY.Value  = decimal.Parse(txt[tmp++]);
                VisibillityPosZ.Value  = decimal.Parse(txt[tmp++]);
                VisibillityW.Value     = decimal.Parse(txt[tmp++]);
                VisibillityH.Value     = decimal.Parse(txt[tmp++]);
                VisibillityD.Value     = decimal.Parse(txt[tmp++]);
                AttackTransPosX.Value  = decimal.Parse(txt[tmp++]);
                AttackTransPosY.Value  = decimal.Parse(txt[tmp++]);
                AttackTransPosZ.Value  = decimal.Parse(txt[tmp++]);
                AttackTransW.Value     = decimal.Parse(txt[tmp++]);
                AttackTransH.Value     = decimal.Parse(txt[tmp++]);
                AttackTransD.Value     = decimal.Parse(txt[tmp++]);

                MovePatternNum.Value        = decimal.Parse(txt[tmp++]);
                enemyMSList.totalPatternNum = (int)MovePatternNum.Value;
                for (int i = 0; i < enemyMSList.totalPatternNum; ++i)
                {
                    enemyMSList.ems.Add(new EnemyMoveSetList.EnemyMoveSet());

                    enemyMSList.ems[i].emp.totalMoveNum = int.Parse(txt[tmp++]);

                    for (int j = 0; j < enemyMSList.ems[i].emp.totalMoveNum; ++j)
                    {
                        EnemyMovePattern.EnemyMove setem = new EnemyMovePattern.EnemyMove();
                        setem.moveId       = int.Parse(txt[tmp++]);
                        setem.behaviorId   = int.Parse(txt[tmp++]);
                        setem.durationTime = int.Parse(txt[tmp++]);
                        setem.animSrc.Set(int.Parse(txt[tmp++]), int.Parse(txt[tmp++]), int.Parse(txt[tmp++]), int.Parse(txt[tmp++]));
                        setem.basisRenderPosX = float.Parse(txt[tmp++]);
                        setem.basisRenderPosY = float.Parse(txt[tmp++]);
                        setem.animNum         = int.Parse(txt[tmp++]);
                        setem.waitTime        = int.Parse(txt[tmp++]);
                        setem.isRoop          = int.Parse(txt[tmp++]) == 1 ? 1 : 0;

                        enemyMSList.ems[i].emp.em.Add(setem);
                    }

                    for (int k = 0; k < enemyMSList.totalPatternNum; ++k)
                    {
                        enemyMSList.ems[i].transitionId.Add(int.Parse(txt[tmp++]));
                    }
                }

                MovePatternNum.Minimum = enemyMSList.totalPatternNum;
                OutputFileName.Text    = ReadFileName.Text;
                readFile = true;

                MessageBox.Show("読み込みが完了しました",
                                "完了",
                                MessageBoxButtons.OK);
            }
            catch
            {
                MessageBox.Show("指定したファイルが無いか、\n正常なファイルでない可能性が微粒子レベルで存在している…?",
                                "データ壊れちゃ~↑う",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Hand);

                return;
            }

            return;
        }
 public static OAuth2Message CreateFromEncodedResponse(System.IO.StreamReader reader)
 {
     return(OAuth2MessageFactory.CreateFromEncodedResponse(reader.ReadToEnd()));
 }
Beispiel #39
0
        /// <summary>
        /// Rollback all transaction root logs.
        /// NOTE: invoke this upon app restart
        /// </summary>
        public static bool RollbackAll(string serverPath)
        {
            string logFolder = string.Format("{0}\\TransactionLogs", serverPath);

            if (System.IO.Directory.Exists(logFolder))
            {
                //** 1.) open each transaction log file in TransactionLog folder and restore the last line activity...
                string[] logFiles = System.IO.Directory.GetFiles(logFolder, string.Format("{0}*.txt", TransLiteral));
                foreach (string logFile in logFiles)
                {
                    //** open the transaction log file and process contents
                    System.IO.StreamReader reader;
                    try
                    {
                        reader = new System.IO.StreamReader(logFile);
                    }
                    catch
                    {
                        return(false);
                    }
                    using (reader)
                    {
                        reader.BaseStream.Seek(0, System.IO.SeekOrigin.End);
                        if (reader.BaseStream.Position == 0)
                        {
                            reader.Close();
                            continue;
                        }
                        long seekCount = -256;
                        if (reader.BaseStream.Position < 256)
                        {
                            seekCount = reader.BaseStream.Position * -1;
                        }
                        reader.BaseStream.Seek(seekCount, System.IO.SeekOrigin.End);
                        string s = reader.ReadToEnd();
                        s = s.TrimEnd();
                        const string registerSaveLiteral = "RegisterSave ";
                        if (string.IsNullOrEmpty(s) || !s.StartsWith(registerSaveLiteral))
                        {
                            // do nothing...
                        }
                        else
                        {
                            //** roll back...
                            string   values = s.Substring(registerSaveLiteral.Length - 1);
                            string[] parts  = values.Split(new string[] { ", " }, StringSplitOptions.None);
                            if (parts != null && parts.Length == 3)
                            {
                                string targetFilename = parts[0].Trim();
                                int    targetBlockAddress;

                                //** TODO: create a restart log file where these exceptions will be logged

                                if (!int.TryParse(parts[1], out targetBlockAddress))
                                {
                                    throw new ApplicationException(
                                              string.Format("Invalid Block Address{0} found in log file {1}", parts[1],
                                                            targetFilename));
                                }
                                int targetSegmentSize;
                                if (!int.TryParse(parts[2], out targetSegmentSize))
                                {
                                    throw new ApplicationException(
                                              string.Format("Invalid _region Size{0} found in log file {1}", parts[2],
                                                            targetFilename));
                                }

                                string sourceFilename = string.Format("{0}.log",
                                                                      logFile.Substring(0, logFile.Length - 4));
                                if (!System.IO.File.Exists(sourceFilename))
                                {
                                    throw new ApplicationException(
                                              string.Format("Backup filename{0} not found.", sourceFilename));
                                }

                                int        targetBufferSize;
                                FileStream targetFileStream =
                                    File.UnbufferedOpen(ObjectServer.NormalizePath(serverPath, targetFilename),
                                                        System.IO.FileAccess.ReadWrite,
                                                        targetSegmentSize, out targetBufferSize);

                                if (targetFileStream == null)
                                {
                                    throw new ApplicationException(string.Format("Can't open Target File {0}.",
                                                                                 targetFilename));
                                }

                                int        sourceBufferSize;
                                FileStream sourceFileStream =
                                    File.UnbufferedOpen(
                                        ObjectServer.NormalizePath(serverPath, sourceFilename),
                                        System.IO.FileAccess.ReadWrite,
                                        targetSegmentSize, out sourceBufferSize);
                                var sourceBuffer = new byte[sourceBufferSize];

                                targetFileStream.Seek(targetBlockAddress, System.IO.SeekOrigin.Begin);

                                //** copy asynchronously from source to target log file
                                IAsyncResult iar = sourceFileStream.BeginRead(sourceBuffer, 0,
                                                                              targetSegmentSize, null, null);
                                if (!iar.IsCompleted)
                                {
                                    iar.AsyncWaitHandle.WaitOne();
                                }
                                sourceFileStream.EndRead(iar);
                                targetFileStream.Seek(0, System.IO.SeekOrigin.Begin);
                                iar = targetFileStream.BeginWrite(sourceBuffer, 0,
                                                                  targetSegmentSize, null, null);
                                if (!iar.IsCompleted)
                                {
                                    iar.AsyncWaitHandle.WaitOne();
                                }
                                targetFileStream.EndWrite(iar);
                                targetFileStream.Flush();

                                targetFileStream.Dispose();
                                sourceFileStream.Dispose();
                            }
                        }
                    }
                }
                foreach (string logFile in logFiles)
                {
                    ProcessLines(logFile, null, null);
                    Sop.Utility.Utility.FileDelete(logFile);
                }

                //** remove TransactionLog folder
                //System.IO.Directory.Delete(LogFolder, true);
                return(true);
            }
            return(false);
        }
Beispiel #40
0
        private void Login(System.Net.IWebProxy proxy)
        {
            if (cookie == null)
            {
                //获取SessionId和post_key
                System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://accounts.pixiv.net/login?lang=zh&source=pc&view_type=page&ref=wwwtop_accounts_index");
                var rsp             = (System.Net.HttpWebResponse)req.GetResponse();
                var cookieContainer = new System.Net.CookieContainer();
                cookieContainer.SetCookies(rsp.ResponseUri, rsp.Headers["Set-Cookie"]);

                //这里是失败的尝试……跳过就好

                /*
                 * //cookieContainer.Add(phpsessidCookie);
                 * //cookieContainer.Add(p_ab_idCookie);
                 * cookie = rsp.Headers.Get("Set-Cookie");
                 * if (cookie == null)
                 * {
                 *  throw new Exception("获取初始PHPSESSID失败");
                 * }
                 * //Set-Cookie: PHPSESSID=3af0737dc5d8a27f5504a7b8fe427286; expires=Tue, 15-May-2012 10:05:39 GMT; path=/; domain=.pixiv.net
                 * int sessionIndex = cookie.LastIndexOf("PHPSESSID");
                 * string phpsessid = cookie.Substring(sessionIndex + 10, cookie.IndexOf(';', sessionIndex + 10) - sessionIndex - 9);
                 * int p_ab_idIndex = cookie.LastIndexOf("p_ab_id");
                 * string p_ab_id = cookie.Substring(p_ab_idIndex + 8, cookie.IndexOf(';', p_ab_idIndex + 8) - p_ab_idIndex - 8);
                 * rsp.Close();
                 * var phpsessidCookie = new System.Net.Cookie("p_ab_id", p_ab_id);
                 * var p_ab_idCookie = new System.Net.Cookie("PHPSESSID", phpsessid);
                 */

                var loginPageStream = rsp.GetResponseStream();
                System.IO.StreamReader streamReader = new System.IO.StreamReader(loginPageStream);
                string loginPageString = streamReader.ReadToEnd();
                streamReader.Dispose();
                loginPageStream.Dispose();
                rsp.Close();

                HtmlDocument loginPage = new HtmlDocument();
                loginPage.LoadHtml(loginPageString);
                HtmlNode postKeyNode = loginPage.DocumentNode.SelectSingleNode("//input[@name='post_key']");
                string   postKey     = postKeyNode.Attributes.Where(p => p.Name == "value").Select(p => p.Value).ToList()[0];


                //模拟登陆
                req           = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://accounts.pixiv.net/api/login?lang=zh");
                req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
                req.Proxy     = proxy;
                req.Timeout   = 8000;
                req.Method    = "POST";
                //prevent 302
                req.AllowAutoRedirect = false;
                //user & pass
                int    index = rand.Next(0, user.Length);
                string data  = "captcha=&g_recaptcha_response=&pixiv_id=" + user[index] + "&password="******"&source=pc" + "&post_key=" + postKey + "&ref=wwwtop_accounts_index" + "&return_to=http%3A%2F%2Fwww.pixiv.net%2F";
                byte[] buf   = Encoding.UTF8.GetBytes(data);
                req.ContentLength   = buf.Length;
                req.ContentType     = "application/x-www-form-urlencoded; charset=UTF-8";
                req.KeepAlive       = true;
                req.Referer         = "https://accounts.pixiv.net/login?lang=zh&source=pc&view_type=page&ref=wwwtop_accounts_index";
                req.Accept          = "application/json, text/javascript, */*; q=0.01";
                req.CookieContainer = cookieContainer;


                System.IO.Stream str = req.GetRequestStream();
                str.Write(buf, 0, buf.Length);
                str.Close();
                var getRsp = req.GetResponse();

                //HTTP 302然后返回实际地址
                cookie = getRsp.Headers.Get("Set-Cookie");
                if (/*rsp.Headers.Get("Location") == null ||*/ cookie == null)
                {
                    throw new Exception("自动登录失败");
                }
                //Set-Cookie: PHPSESSID=3af0737dc5d8a27f5504a7b8fe427286; expires=Tue, 15-May-2012 10:05:39 GMT; path=/; domain=.pixiv.net
                int sessionIndex      = cookie.LastIndexOf("PHPSESSID");
                int device_tokenIndex = cookie.LastIndexOf("device_token");
                cookie = cookie.Substring(sessionIndex, cookie.IndexOf(';', sessionIndex) - sessionIndex) + "; " + cookie.Substring(device_tokenIndex, cookie.IndexOf(';', device_tokenIndex) - device_tokenIndex);
                rsp.Close();
            }
        }
Beispiel #41
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["type"] != null)
            {
                if (Request.QueryString["type"] != "")
                {
                    string URL = "";
                    double amt = (double.Parse(Request.QueryString["amt"].ToString()));
                    transAmount   = amt.ToString();
                    transid       = Request.QueryString["transid"].ToString();
                    transshowname = Request.QueryString["show"].ToString();
                    String ErrorUrl    = IpAddress + "Payment/HDFC/Error.aspx";
                    String ResponseUrl = IpAddress + "Payment/HDFC/ReturnReceipt.aspx";
                    string qrystr      = "id=" + HDFCTransPortalID + "&password="******"&action=1&langid=USA&currencycode=356&amt=" + transAmount
                                         + "&responseURL=" + Server.UrlEncode(ResponseUrl) + "&errorURL=" + Server.UrlEncode(ErrorUrl)
                                         + "&trackid=" + transid
                                         + "&udf1=TicketBooking" + "&udf2=" + transshowname
                                         + "&udf3=" + transshowname + "&udf4=" + transshowname + "&udf5=" + transshowname;
                    System.IO.StreamWriter    requestWriter = null;
                    System.Net.HttpWebRequest objRequest    = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(HDFCTransUrl);    //create a SSL connection object server-to-server
                    objRequest.Method          = "POST";
                    objRequest.ContentLength   = qrystr.Length;
                    objRequest.ContentType     = "application/x-www-form-urlencoded";
                    objRequest.CookieContainer = new System.Net.CookieContainer();
                    try
                    {
                        requestWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());      // here the request is sent to payment gateway
                        requestWriter.Write(qrystr);
                    }
                    catch (Exception ex)
                    {
                    }

                    if (requestWriter != null)
                    {
                        requestWriter.Close();
                    }
                    System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();

                    using (System.IO.StreamReader sr =
                               new System.IO.StreamReader(objResponse.GetResponseStream()))
                    {
                        String NSDLval = sr.ReadToEnd();
                        if (NSDLval.Contains("Invalid User Defined Field"))
                        {
                            return;
                        }
                        if (NSDLval.IndexOf("http") == -1)
                        {
                            return;
                        }
                        string strPmtId  = NSDLval.Substring(0, NSDLval.IndexOf(":http"));      // Merchant MUST map (update) the Payment ID received with the merchant Track Id in his database at this place.
                        string strPmtUrl = NSDLval.Substring(NSDLval.IndexOf("http"));
                        if (strPmtId != String.Empty && strPmtUrl != String.Empty)
                        {
                            URL = strPmtUrl.ToString() + "?PaymentID=" + strPmtId;
                        }

                        sr.Close();
                        Response.Redirect(URL, false);
                    }
                }
            }
        }
        public async Task <T> Download <T>(string inUrl, int retryTimesOnException = 1, int timeout_Header_InSconds = 3, int timeout_Content_InSconds = 10, Action <Exception> exHandler = null, System.Threading.CancellationToken?cToken = null, bool cacheEnabled = false, Action <List <string> > logHandler = null)
        {
            object r = null;
            int    retryTime_Counter;

            retryTime_Counter = 1;
            List <string> logs = null;

            if (logHandler != null)
            {
                logs = new List <string>();
            }
            while (retryTime_Counter <= retryTimesOnException)
            {
                try
                {
                    if (cToken != null && cToken.Value.IsCancellationRequested)
                    {
                        break;
                    }
                    if (logs != null)
                    {
                        logs.Add($"Try - Start: {retryTime_Counter}");
                    }
                    Download_Done   = 0;
                    Download_Length = null;
                    try
                    {
                        System.Net.HttpWebRequest req_Header = System.Net.WebRequest.Create(inUrl) as System.Net.HttpWebRequest;
                        req_Header.Method = "HEAD";
                        var req_Header_GetResponseAsync_Task = req_Header.GetResponseAsync();
                        if (await Task.WhenAny(req_Header_GetResponseAsync_Task, Task.Delay(TimeSpan.FromSeconds(timeout_Header_InSconds))) == req_Header_GetResponseAsync_Task)
                        {
                            using (System.Net.WebResponse resp_Header = req_Header_GetResponseAsync_Task.Result)
                            {
                                int resp_Header_ContentLength;
                                if (resp_Header.Headers.AllKeys.Count(a1 => a1 == "Content-Length") > 0)
                                {
                                    if (int.TryParse(resp_Header.Headers["Content-Length"], out resp_Header_ContentLength))
                                    {
                                        Download_Length = resp_Header_ContentLength;
                                        if (logs != null)
                                        {
                                            logs.Add($"Download_Length - Try 1: {Download_Length}");
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            throw new TimeoutException($"Time out (HEADER) on URL: {inUrl}");
                        }
                    }
                    catch (Exception ex1)
                    {
                        if (logs != null)
                        {
                            logs.Add($"DownloadLength - Try 1 Ex: {ex1.ToString()}");
                        }
                    }
                    //
                    if (cToken != null && cToken.Value.IsCancellationRequested)
                    {
                        break;
                    }
                    //
                    System.Net.HttpWebRequest hWReq = System.Net.WebRequest.Create(inUrl) as System.Net.HttpWebRequest;
                    hWReq.Method = "GET";
                    hWReq.Accept = null;
                    //if (!cacheEnabled)
                    //{
                    //    hWReq.Headers["Cache-Control"] = "no-cache";
                    //    hWReq.Headers["Pragma"] = "no-cache";
                    //}
                    //
                    System.Net.WebResponse hWResp      = null;
                    System.Net.WebRequest  hwReq_Typed = hWReq as System.Net.WebRequest;
                    var hWResp_GetResponseAsync_Task   = hwReq_Typed.GetResponseAsync();
                    if (await Task.WhenAny(hWResp_GetResponseAsync_Task, Task.Delay(TimeSpan.FromSeconds(timeout_Content_InSconds))) == hWResp_GetResponseAsync_Task)
                    {
                        if (cToken != null && cToken.Value.IsCancellationRequested)
                        {
                            break;
                        }
                        //
                        hWResp = hWResp_GetResponseAsync_Task.Result;
                        // Check for content length in GET header (if no success using HEAD method)
                        if (Download_Length == null)
                        {
                            int resp_Header_ContentLength;
                            if (hWResp.Headers.AllKeys.Count(a1 => a1 == "Content-Length") > 0)
                            {
                                if (int.TryParse(hWResp.Headers["Content-Length"], out resp_Header_ContentLength))
                                {
                                    Download_Length = resp_Header_ContentLength;
                                    if (logs != null)
                                    {
                                        logs.Add($"Download_Length - Try 2: {Download_Length}");
                                    }
                                }
                            }
                        }
                        // Read the response into a Stream object.
                        byte[] data_Native;
                        using (System.IO.MemoryStream ms1 = new System.IO.MemoryStream())
                        {
                            using (System.IO.Stream responseStream = hWResp.GetResponseStream())
                            {
                                int    bufferSize = 8192;
                                byte[] buffer     = new byte[bufferSize];
                                int    bufferUsed;
                                do
                                {
                                    if (cToken != null && cToken.Value.IsCancellationRequested)
                                    {
                                        break;
                                    }
                                    //
                                    Task <int> responseStream_ReadAsync_Task;
                                    if (cToken != null)
                                    {
                                        responseStream_ReadAsync_Task = responseStream.ReadAsync(buffer, 0, bufferSize, cToken.Value);
                                    }
                                    else
                                    {
                                        responseStream_ReadAsync_Task = responseStream.ReadAsync(buffer, 0, bufferSize);
                                    }
                                    //
                                    if (await Task.WhenAny(responseStream_ReadAsync_Task, Task.Delay(TimeSpan.FromSeconds(timeout_Content_InSconds))) == responseStream_ReadAsync_Task)
                                    {
                                        bufferUsed = responseStream_ReadAsync_Task.Result;
                                        if (bufferUsed > 0)
                                        {
                                            ms1.Write(buffer, 0, bufferUsed);
                                            Download_Done += bufferUsed;
                                            if (Download_ProgressChanged != null)
                                            {
                                                Download_ProgressChanged(this, EventArgs.Empty);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        throw new TimeoutException($"Time out (GET - Read) on URL: {inUrl}");
                                    }
                                } while (bufferUsed > 0);
                            }
                            //
                            if (cToken != null && cToken.Value.IsCancellationRequested)
                            {
                                break;
                            }
                            //
                            data_Native  = ms1.ToArray();
                            ms1.Position = 0;
                            //
                            if (typeof(T) == typeof(string))
                            {
                                string data;
                                using (var reader = new System.IO.StreamReader(ms1))
                                {
                                    data = reader.ReadToEnd();
                                }
                                r = data;
                            }
                            else if (typeof(T) == typeof(byte[]))
                            {
                                r = data_Native;
                            }
                            else if (typeof(T) == typeof(System.IO.MemoryStream))
                            {
                                System.IO.MemoryStream ms2 = new System.IO.MemoryStream(data_Native);
                                r = ms2;
                            }
                        }
                    }
                    else
                    {
                        throw new TimeoutException($"Time out (GET) on URL: {inUrl}");
                    }
                }
                catch (Exception ex)
                {
                    if (logs != null)
                    {
                        logs.Add($"Try {retryTime_Counter} Ex: {ex.ToString()}");
                    }
                    //
                    r = null;
                    if (exHandler != null)
                    {
                        exHandler(ex);
                    }
                    //
                    var we = ex.InnerException as System.Net.WebException;
                    if (we != null)
                    {
                        //var resp = we.Response as System.Net.HttpWebResponse;
                        //if (resp != null)
                        //{
                        //    var code = resp.StatusCode;
                        //}
                        Debug.WriteLine("RespCallback Exception raised! Message:{0}" + we.Message);
                        Debug.WriteLine("Status:{0}", we.Status);
                    }
                    else
                    {
                        Debug.WriteLine("Unknown Exception: {0}", ex.ToString());
                    }
                }
                //
                if (cToken != null && cToken.Value.IsCancellationRequested)
                {
                    break;
                }
                //
                if (r != null)
                {
                    break;
                }
                retryTime_Counter++;
            }
            //
            if (cToken != null)
            {
                cToken.Value.ThrowIfCancellationRequested();
            }
            //
            if (logHandler != null)
            {
                logHandler(logs);
            }
            //
            return((T)r);
        }
Beispiel #43
0
        internal void loadData(string Filename)
        {
            System.IO.StreamReader reader = new System.IO.StreamReader(Filename);

            string curLine                 = reader.ReadLine();
            bool   serverDataRead          = false;
            List <ModuleAbility> abilities = new List <ModuleAbility>();

            name        = desc = string.Empty;
            nominalCost = 0;

            while (curLine != null)
            {
                if (base.loadData(reader, curLine, DataType.Ability))
                {
                    serverDataRead = true;
                }
                else if (curLine.ToUpper().StartsWith("NAME="))
                {
                    name = curLine.Substring("NAME=".Length);
                }
                else if (curLine.ToUpper().StartsWith("NOMINALCOST="))
                {
                    nominalCost = double.Parse(curLine.Substring("NOMINALCOST=".Length));
                }
                else if (curLine.ToUpper().StartsWith("ABILITY"))
                {
                    int abilityIndex = int.Parse(curLine.Substring("ABILITY".Length, 3));

                    while (abilities.Count <= abilityIndex)
                    {
                        abilities.Add(new ModuleAbility());
                    }

                    if (curLine.ToUpper().StartsWith("ABILITY" + abilityIndex.ToString("000") + "ID="))
                    {
                        abilities[abilityIndex].ability = int.Parse(curLine.Substring(("ABILITY" + abilityIndex.ToString("000") + "ID=").Length));
                    }
                    if (curLine.ToUpper().StartsWith("ABILITY" + abilityIndex.ToString("000") + "FIELD"))
                    {
                        int fieldIndex = int.Parse(curLine.Substring(("ABILITY" + abilityIndex.ToString("000") + "FIELD").Length, 3));
                    }
                }
                else if (curLine.ToUpper() == "[DESCRIPTION]")
                {
                    desc = reader.ReadToEnd();
                }

                curLine = reader.ReadLine();
            }

            if (!serverDataRead)
            {
                throw new NoServerDataException();
            }
            if (name.Length == 0 || desc.Length == 0 || nominalCost <= 0)
            {
                throw new InvalidModuleData();
            }

            fieldNames = names.ToArray();
        }
Beispiel #44
0
        private void EncodeOrDecode(bool encode)
        {
            bool existsError = false;

            if (CBoxInput.Text == TXT_FILE && !inputFileSelected)
            {
                epInput.SetError(BtnOpenFile, "No input file is selected.");
                existsError = true;
            }
            if (CBoxOutput.Text == TXT_FILE && !outputFileSelected)
            {
                epOutput.SetError(BtnSaveFile, "No output file is selected.");
                existsError = true;
            }

            if (existsError)
            {
                return;
            }

            ICodeMethod method;
            string      input;

            switch (CBoxInput.Text)
            {
            case TXT_FIELD:
                input = TxtInputArea.Text;
                break;

            case TXT_FILE:
                System.IO.StreamReader file = new System.IO.StreamReader(openFileDialog.FileName);
                input = file.ReadToEnd();
                file.Close();
                break;

            default:
                throw new Exception("Invalid selection for input.");
            }
            switch (CBoxMethod.Text)
            {
            case METHOD_SUBSTITUTION:
                method = new SubstitutionCypher(input, alphabet);
                break;

            default:
                throw new NotImplementedException();
            }

            string output;

            if (encode)
            {
                output = method.Encode(TxtKey.Text);
            }
            else
            {
                output = method.Decode(TxtKey.Text);
            }

            switch (CBoxOutput.Text)
            {
            case TXT_FIELD:
                TxtOutputArea.Text = output;
                break;

            case TXT_FILE:
                System.IO.StreamWriter file = new System.IO.StreamWriter(saveFileDialog.FileName);
                file.Write(output);
                file.Close();
                break;
            }

            LblDone.Visible = true;

            //Stop showing "done" after a while.
            const int DONE_DISPLAY_TIME_MILISECONDS = 1500;

            Task.Delay(DONE_DISPLAY_TIME_MILISECONDS).GetAwaiter().OnCompleted(() => {
                if (LblDone != null)
                {
                    LblDone.Visible = false;
                }
            });
        }
Beispiel #45
0
        public string Call(string method, string jsonPayload)
        {
            var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(Endpoint + method);

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; //Added to support all TLS types required by remote server

            request.Method        = "POST";
            request.ContentLength = 0;
            request.ContentType   = "application/json; charset=utf-8";
            request.Headers.Add("X-CENTRIFY-NATIVE-CLIENT", "1");
            request.Timeout = 120000;

            if (BearerToken != null)
            {
                request.Headers.Add("Authorization", "Bearer " + BearerToken);
            }

            // Carry cookies from call to call
            if (Cookies == null)
            {
                Cookies = new CookieContainer();
                Cookies.PerDomainCapacity = 300;
            }

            request.CookieContainer = Cookies;

            // Add content if provided
            if (!string.IsNullOrEmpty(jsonPayload))
            {
                var bytes = System.Text.Encoding.UTF8.GetBytes(jsonPayload);
                request.ContentLength = bytes.Length;

                using (var writeStream = request.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }

            using (var response = (System.Net.HttpWebResponse)request.GetResponse())
            {
                string responseValue = null;

                // If call did not return 200, throw exception
                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    throw new ApplicationException(string.Format("Request failed. Received HTTP {0}", response.StatusCode));
                }

                // If response is non-empty, read it all out as a string
                if (response.ContentLength > 0)
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        {
                            using (var reader = new System.IO.StreamReader(responseStream))
                            {
                                responseValue = reader.ReadToEnd();
                            }
                        }
                    }
                }

                return(responseValue);
            }
        }
Beispiel #46
0
        /// <summary>
        /// Prepara un servidor para ser utilizado por Lázaro. Crea estructuras y realiza una carga inicial de datos.
        /// </summary>
        public Lfx.Types.OperationResult Prepare(Lfx.Types.OperationProgress progreso)
        {
            bool MiProgreso = false;

            if (progreso == null)
            {
                progreso       = new Types.OperationProgress("Preparando el almacén de datos", "Se están creando las tablas de datos y se va realizar una carga inicial de datos. Esta operación puede demorar varios minutos.");
                progreso.Modal = true;
                progreso.Begin();
                MiProgreso = true;
            }

            // Creación de tablas
            progreso.ChangeStatus("Creando estructuras");
            this.CheckAndUpdateDataBaseStructure(this.MasterConnection, true, progreso);

            this.MasterConnection.EnableConstraints(false);

            string Sql = "";

            using (System.IO.Stream RecursoSql = ObtenerRecurso(@"Data.Struct.dbdata.sql")) {
                using (System.IO.StreamReader Lector = new System.IO.StreamReader(RecursoSql, System.Text.Encoding.UTF8)) {
                    // Carga inicial de datos
                    Sql = this.MasterConnection.CustomizeSql(Lector.ReadToEnd());
                    Lector.Close();
                    RecursoSql.Close();
                }
            }

            // Si hay archivos adicionales de datos para la carga inicial, los incluyo
            // Estos suelen tener datos personalizados de esta instalación en partícular
            if (System.IO.File.Exists(Lfx.Environment.Folders.ApplicationFolder + "default.alf"))
            {
                using (System.IO.StreamReader Lector = new System.IO.StreamReader(Lfx.Environment.Folders.ApplicationFolder + "default.alf", System.Text.Encoding.UTF8)) {
                    Sql += Lfx.Types.ControlChars.CrLf;
                    Sql += this.MasterConnection.CustomizeSql(Lector.ReadToEnd());
                    Lector.Close();
                }
            }

            progreso.ChangeStatus("Carga inicial de datos");
            progreso.Max = Sql.Length;
            //this.MasterConnection.ExecuteSql(Sql);

            do
            {
                string Comando = Lfx.Data.Connection.GetNextCommand(ref Sql);
                try {
                    this.MasterConnection.ExecuteSql(Comando);
                } catch {
                    // Hubo errores, pero continúo
                }
                progreso.ChangeStatus(progreso.Max - Sql.Length);
            }while (Sql.Length > 0);

            progreso.ChangeStatus("Carga de TagList");
            // Cargar TagList y volver a verificar la estructura
            Lfx.Workspace.Master.Structure.TagList.Clear();
            Lfx.Workspace.Master.Structure.LoadBuiltIn();

            this.CheckAndUpdateDataBaseStructure(this.MasterConnection, false, progreso);

            this.MasterConnection.EnableConstraints(true);
            this.CurrentConfig.WriteGlobalSetting("Sistema.DB.Version", Lfx.Workspace.VersionUltima);

            if (MiProgreso)
            {
                progreso.End();
            }
            return(new Lfx.Types.SuccessOperationResult());
        }
Beispiel #47
0
        public WeightsMatrix readConfiguration(string path)
        {
            WeightsMatrix wm;
            string        data = "";

            try
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(path);
                data = reader.ReadToEnd();
                reader.Close();

                float[] weightsRow = new float[1];

                ArrayList netConfigMatrix = new ArrayList();

                string strctr = data.Substring(1, data.IndexOf("]", 0) - 1);
                data = data.Substring(strctr.Length + 2);
                ArrayList structure  = new ArrayList();
                int       spaceindex = 0;
                string    s          = "";
                while (true)
                {
                    spaceindex = strctr.IndexOf(" ", 0);
                    if (spaceindex == -1)
                    {
                        structure.Add(Convert.ToInt16(strctr));
                        break;
                    }
                    s = strctr.Substring(0, spaceindex);
                    structure.Add(Convert.ToInt16(s));
                    strctr = strctr.Substring(spaceindex, strctr.Length - spaceindex);
                    strctr = strctr.Trim();
                }
                netConfigMatrix.Add(structure);

                string iw = data.Substring(1, data.IndexOf("]", 0) - 1);
                data         = data.Substring(iw.Length + 2);
                double[,] IW = new double[Int32.Parse(structure[1].ToString()), Int32.Parse(structure[0].ToString())];
                spaceindex   = 0;
                int semicolonindex = 0;
                int rowCount       = 0;
                int columnCount    = 0;
                s = "";
                int inputNeruronCount = int.Parse(structure[structure.Count - 2].ToString());
                int inputNeruronIndex = 0;

                while (inputNeruronIndex < inputNeruronCount)
                {
                    semicolonindex = iw.IndexOf(";");
                    string w = "";
                    if (semicolonindex == -1)
                    {
                        w = iw.Substring(0).Trim();
                    }
                    else
                    {
                        w  = iw.Substring(0, semicolonindex).Trim();
                        iw = iw.Substring(semicolonindex + 1);
                    }
                    for (int colCount = 0; columnCount < IW.GetLength(1); colCount++)
                    {
                        spaceindex = w.IndexOf(" ", 0);
                        if (spaceindex == -1)
                        {
                            IW[rowCount, colCount] = double.Parse(w);
                            break;
                        }
                        s = w.Substring(0, spaceindex);
                        IW[rowCount, colCount] = double.Parse(s);
                        w = w.Substring(spaceindex, w.Length - spaceindex).Trim();
                    }
                    rowCount++;
                    inputNeruronIndex++;
                }

                string lw = data.Substring(1, data.IndexOf("]", 0) - 1);
                int[,] LW      = new int[Int32.Parse(structure[2].ToString()), Int32.Parse(structure[1].ToString())];
                spaceindex     = 0;
                semicolonindex = 0;
                rowCount       = 0;
                columnCount    = 0;
                s = "";
                int outputNeruronCount = int.Parse(structure[structure.Count - 1].ToString());
                int outputNeruronIndex = 0;
                while (outputNeruronIndex < outputNeruronCount)
                {
                    semicolonindex = lw.IndexOf(";");
                    string w = "";
                    if (semicolonindex == -1)
                    {
                        w = lw.Substring(0).Trim();
                    }
                    else
                    {
                        w  = lw.Substring(0, semicolonindex).Trim();
                        lw = lw.Substring(semicolonindex + 1);
                    }
                    for (int colCount = 0; columnCount < LW.GetLength(1); colCount++)
                    {
                        spaceindex = w.IndexOf(" ", 0);
                        if (spaceindex == -1)
                        {
                            LW[rowCount, colCount] = Int32.Parse(w);
                            break;
                        }
                        s = w.Substring(0, spaceindex);
                        LW[rowCount, colCount] = Int32.Parse(s);
                        w = w.Substring(spaceindex, w.Length - spaceindex).Trim();
                    }
                    rowCount++;
                    outputNeruronIndex++;
                }
                wm = new WeightsMatrix(IW, LW);
                return(wm);
            }
            catch (Exception ioerror)
            {
                throw ioerror;
            }
        }
Beispiel #48
0
        protected void Button2_Click(object sender, EventArgs e)
        {
            String username     = TextBox3.Text.ToString();
            String pass_entered = TextBox1.Text.ToString();

            if (username == "")
            {
                Label1.Text = "Please enter username";
            }
            else
            {
                if (pass_entered == "")
                {
                    Label1.Text = "Please enter password";
                }
                else
                {
                    string      url      = s.url + "user_login/" + username;
                    WebRequest  request  = WebRequest.Create(url);
                    WebResponse response = request.GetResponse();

                    using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
                    {
                        XDocument xmlDoc = new XDocument();
                        try
                        {
                            xmlDoc = XDocument.Parse(sr.ReadToEnd());
                            string status  = xmlDoc.Root.Value.ToString();
                            string status1 = status;

                            if (status1.Equals("User not verified"))
                            {
                                Label1.Visible = true;
                                Label1.Text    = status1;
                            }
                            else if (status1.Equals("Invalid user"))
                            {
                                Label1.Visible = true;
                                Label1.Text    = status1;
                            }
                            else
                            {
                                string[] a = status1.Split('$');
                                // password check
                                string password = a[0];

                                if (password.Equals(pass_entered))
                                {
                                    FlagCheck.flag  = "user";
                                    FlagCheck.name  = a[1];
                                    Session["x"]    = a[2];
                                    Session.Timeout = 1000;
                                    if (flag == 1)
                                    {
                                        if (Request.QueryString["id"].ToString() == "settings")
                                        {
                                            Response.Redirect("User_Settings.aspx");
                                        }
                                        else
                                        {
                                            Response.Redirect("InstituteHome.aspx?id=" + Request.QueryString["id"].ToString());
                                        }
                                    }
                                    else
                                    {
                                        Response.Redirect("Search.aspx?Name=" + a[1]);
                                    }
                                }
                                else
                                {
                                    Label1.Visible = true;
                                    Label1.Text    = "Incorrect Password";
                                }
                            }
                        }
                        catch (Exception)
                        {
                            // handle if necessary
                        }
                    }
                }
            }
        }
Beispiel #49
0
        public float[,] readInputs(string path, int inputLayerNeuronCount)
        {
            try
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(path);
                data = reader.ReadToEnd();
                reader.Close();
                //    System.IO.File.Delete(path);
            }
            catch (Exception ioerror)
            {
                Console.Out.WriteLine(ioerror.ToString());
            } // cath ends
            int       inputsSize = 0;
            int       rowSize;
            string    inputRow;
            int       semiColonIndex = 0;
            ArrayList rows           = new ArrayList();

            while (true)
            {
                rowSize = data.IndexOf(";", semiColonIndex);
                if (rowSize == -1)
                {
                    inputs = new float[inputsSize, inputLayerNeuronCount];
                    break;
                }
                inputRow = data.Substring(semiColonIndex, rowSize - semiColonIndex);
                rows.Add(inputRow);
                semiColonIndex = rowSize + 1;
                inputsSize++;
            } // while ends


            object[] obj = rows.ToArray();
            for (int rowCount = 0; rowCount < rows.Count; rowCount++)
            {
                inputRow = (string)obj[rowCount];
                int     commaIndex = 0;
                int     valSize;
                int     count = 0;
                string  inputVal;
                float[] iVal = new float[inputLayerNeuronCount];
                while (true)
                {
                    valSize = inputRow.IndexOf(",", commaIndex);
                    if (valSize == -1)
                    {
                        inputVal      = inputRow.Substring(commaIndex, (inputRow.Length) - commaIndex);
                        iVal[count++] = System.Single.Parse(inputVal);
                        for (int i = 0; i < iVal.Length; i++)
                        {
                            inputs[rowCount, i] = iVal[i];
                        }

                        break;
                    }
                    inputVal      = inputRow.Substring(commaIndex, valSize - commaIndex);
                    iVal[count++] = System.Single.Parse(inputVal);
                    commaIndex    = valSize + 1;
                } // while ends
            }     // for ends
            return(inputs);
        }         // readInputs end
        public void TestUploadFile()
        {
            // hack to ignore bad certificates
            ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateRemoteCertificate);

            var service = new VimService();

            service.Url             = "https://vsphere-eng/sdk/vimService";
            service.CookieContainer = new CookieContainer();

            ServiceContent         _sic    = null;
            ManagedObjectReference _svcRef = new ManagedObjectReference();

            _svcRef.type  = "ServiceInstance";
            _svcRef.Value = "ServiceInstance";

            _sic = service.RetrieveServiceContent(_svcRef);

            if (_sic.sessionManager != null)
            {
                service.Login(_sic.sessionManager, "ENGDOM\\pyramiswebbuilder", "Gilbert93", null);
            }

            Cookie cookie = service.CookieContainer.GetCookies(
                new Uri(service.Url))[0];
            String cookieString = cookie.ToString();

            DataStores datastore = DataStores.datastore4;

            System.IO.FileInfo fi = new System.IO.FileInfo(@"c:\temp.pdf");

            //MyWebClient wc = new MyWebClient();
            //wc.Credentials = new NetworkCredential("root", "Gilbert93");

            // wc.UploadString("https://10.4.2.78/folder/test.txt?dcPath=ha-datacenter&dsName=" + datastore.ToString(), "PUT", "Testing");

            //wc.UploadFile("https://10.4.2.78/folder/" + fi.Name + "?dcPath=ha-datacenter&dsName=" + datastore.ToString(), fi.FullName);

            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://vsphere-eng/folder/" + fi.Name + "?dcPath=DataCenter&dsName=" + datastore.ToString());

            request.Headers.Add(HttpRequestHeader.Cookie, cookieString);

            request.PreAuthenticate = true;
            request.UserAgent       = "Upload Test";
            request.Method          = "POST";

            request.Credentials = new NetworkCredential("ENGDOM\\pyramiswebbuilder", "Gilbert93");

            request.ContentType   = "application/octet-stream";
            request.Accept        = "100-continue";
            request.ContentLength = fi.Length;


            System.IO.Stream s = request.GetRequestStream();

            using (System.IO.FileStream fileStream = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                // used on each read operation
                byte[] buffer = new byte[1024];
                int    len    = 0;
                while ((len = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    s.Write(buffer, 0, len);
                }
            }

            s.Close();

            // execute the request
            WebResponse response = request.GetResponse();

            string result = String.Empty;

            using (System.IO.TextReader tr = new System.IO.StreamReader(response.GetResponseStream()))
            {
                result = tr.ReadToEnd();
            }

            Console.WriteLine(result);


            //service.Logout(_svcRef);
        }
Beispiel #51
0
                    private ItemState InitiateRequests(HttpListenerRequest request)
                    {
                        // TODO: Check credentials
                        string body;

                        using (var reader = new System.IO.StreamReader(request.InputStream, request.ContentEncoding))
                            body = reader.ReadToEnd();
                        var requestData = JsonConvert.DeserializeObject <Dictionary <string, string> >(body);

                        string storageIdentifier;

                        if ((requestData == null) || !requestData.TryGetValue("storage", out storageIdentifier))
                        {
                            storageIdentifier = null;
                        }

                        string cameraIdentifier;

                        if ((requestData == null) || !requestData.TryGetValue("camera", out cameraIdentifier))
                        {
                            cameraIdentifier = null;
                        }

                        DateTime?start;
                        string   startStr;

                        if ((requestData != null) && requestData.TryGetValue("start", out startStr))
                        {
                            start = DateTime.Parse(startStr);
                        }
                        else
                        {
                            start = null;
                        }

                        DateTime?end;
                        string   endStr;

                        if ((requestData != null) && requestData.TryGetValue("end", out endStr))
                        {
                            end = DateTime.Parse(endStr);
                        }
                        else
                        {
                            end = null;
                        }

                        Configuration.Storage.Container[] searchContainers = Configuration.Database.Instance.Storage.AllContainers;
                        if (storageIdentifier != null)
                        {
                            Configuration.Storage.Container found = null;
                            foreach (var container in searchContainers)
                            {
                                if (container.Identifier.Equals(storageIdentifier))
                                {
                                    found = container;
                                    break;
                                }
                            }
                            if (found == null)
                            {
                                searchContainers = new Configuration.Storage.Container[0];
                            }
                            else
                            {
                                searchContainers = new Configuration.Storage.Container[] { found }
                            };
                        }

                        ItemState result = new ItemState();

                        foreach (var container in searchContainers)
                        {
                            var storage = storageManager.GetStorage(container.Identifier);
                            if (storage != null)
                            {
                                storage.SearchTimes(cameraIdentifier, start, end, this);
                                result.expecting++;
                            }
                        }
                        return(result);
                    }
Beispiel #52
0
        public ArrayList readConfiguration(string path)
        {
            string data = "";

            try
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(path);
                data = reader.ReadToEnd();
                reader.Close();



                float[] weightsRow = new float[1];

                ArrayList netConfigMatrix = new ArrayList();

                string    strctr     = data.Substring(0, data.IndexOf(";", 0));
                ArrayList structure  = new ArrayList();
                int       commaindex = 0;
                string    s          = "";
                short[,] lf = new short[1, 2];
                while (true)
                {
                    commaindex = strctr.IndexOf(",", 0);
                    s          = strctr.Substring(0, commaindex);
                    lf[0, 0]   = Convert.ToInt16(s);
                    int nextCommaIndex;
                    nextCommaIndex = strctr.IndexOf(",", commaindex + 1);
                    s        = strctr.Substring(commaindex + 1, 1);
                    lf[0, 1] = Convert.ToInt16(s);
                    structure.Add(lf);
                    lf     = new short[1, 2];
                    strctr = strctr.Substring(nextCommaIndex + 1, strctr.Length - (nextCommaIndex + 1));
                    if (nextCommaIndex == -1)
                    {
                        break;
                    }
                }
                //s = strctr.Substring(0);
                //structure.Add(Convert.ToInt16(s));
                netConfigMatrix.Add(structure);
                data = data.Substring(data.IndexOf(";") + 1);
                // get weights
                strctr = data.Substring(0, data.IndexOf(";", 0));
                ArrayList sss = new ArrayList();
                commaindex = 0;
                s          = "";
                while (strctr.IndexOf(",", 0) != -1)
                {
                    commaindex = strctr.IndexOf(",", 0);
                    s          = strctr.Substring(0, commaindex);
                    sss.Add(Convert.ToDouble(s));
                    strctr = strctr.Substring(commaindex + 1, strctr.Length - (commaindex + 1));
                }
                s = strctr.Substring(0);
                sss.Add(Convert.ToDouble(s));
                netConfigMatrix.Add(sss);
                data = data.Substring(data.IndexOf(";") + 1);

                // get biases
                strctr = data.Substring(0, data.IndexOf(";", 0));
                ArrayList biases = new ArrayList();
                commaindex = 0;
                s          = "";
                while (strctr.IndexOf(",", 0) != -1)
                {
                    commaindex = strctr.IndexOf(",", 0);
                    s          = strctr.Substring(0, commaindex);
                    biases.Add(Convert.ToDouble(s));
                    strctr = strctr.Substring(commaindex + 1, strctr.Length - (commaindex + 1));
                }
                s = strctr.Substring(0);
                biases.Add(Convert.ToDouble(s));
                netConfigMatrix.Add(biases);

                data = data.Substring(data.IndexOf(";") + 1);
                // get preprocessing components
                strctr = data.Substring(0, data.IndexOf(";", 0));
                ArrayList normComps = new ArrayList();
                commaindex = 0;
                s          = "";
                while (strctr.IndexOf(",", 0) != -1)
                {
                    commaindex = strctr.IndexOf(",", 0);
                    s          = strctr.Substring(0, commaindex);
                    normComps.Add(Convert.ToDouble(s));
                    strctr = strctr.Substring(commaindex + 1, strctr.Length - (commaindex + 1));
                }
                s = strctr.Substring(0);
                normComps.Add(Convert.ToDouble(s));
                netConfigMatrix.Add(normComps);

                data = data.Substring(data.IndexOf(";") + 1);
                // get preprocessing components
                strctr = data.Substring(0, data.IndexOf(";", 0));
                ArrayList denormComps = new ArrayList();
                commaindex = 0;
                s          = "";
                while (strctr.IndexOf(",", 0) != -1)
                {
                    commaindex = strctr.IndexOf(",", 0);
                    s          = strctr.Substring(0, commaindex);
                    denormComps.Add(Convert.ToDouble(s));
                    strctr = strctr.Substring(commaindex + 1, strctr.Length - (commaindex + 1));
                }
                s = strctr.Substring(0);
                denormComps.Add(Convert.ToDouble(s));
                netConfigMatrix.Add(denormComps);

                return(netConfigMatrix);
            }catch (Exception ioerror)
            {
                return(null);
            }
        }
Beispiel #53
0
        private void frmSampleGrid1_Load(object sender, System.EventArgs e)
        {
            string[] l_CountryList = new string[] { "Italy", "France", "Spain", "UK", "Argentina", "Mexico", "Switzerland", "Brazil", "Germany", "Portugal", "Sweden", "Austria" };

            grid1.RowsCount     = 1;
            grid1.ColumnsCount  = 10;
            grid1.FixedRows     = 1;
            grid1.FixedColumns  = 1;
            grid1.SelectionMode = SourceGrid.GridSelectionMode.Row;
            grid1.AutoStretchColumnsToFitWidth = true;
            grid1.Columns[0].AutoSizeMode      = SourceGrid.AutoSizeMode.None;
            grid1.Columns[0].Width             = 25;

            grid1.Controller.AddController(new KeyDeleteController());

            //TODO
            ////Enable Drag and Drop
            //grid1.GridController.AddController(SourceGrid.Controllers.SelectionDrag.Cut);
            //grid1.GridController.AddController(SourceGrid.Controllers.SelectionDrop.Default);


            #region Create Grid Style, Views and Controllers
            //Views
            mView_Price = new SourceGrid.Cells.Views.Cell();
            mView_Price.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;


            mController_Link           = new SourceGrid.Cells.Controllers.Button();
            mController_Link.Executed += new EventHandler(mController_Link_Click);
            #endregion

            #region Create Header Row and Editor
            SourceGrid.Cells.Header l_00Header = new SourceGrid.Cells.Header(null);
            grid1[0, 0] = l_00Header;

            mEditor_Id = SourceGrid.Cells.Editors.Factory.Create(typeof(int));
            mEditor_Id.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.AnyKey | SourceGrid.EditableMode.SingleClick;
            grid1[0, 1]             = new SourceGrid.Cells.ColumnHeader("ID (int)");

            mEditor_Name = SourceGrid.Cells.Editors.Factory.Create(typeof(string));
            mEditor_Name.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.AnyKey | SourceGrid.EditableMode.SingleClick;
            grid1[0, 2] = new SourceGrid.Cells.ColumnHeader("NAME (string)");

            mEditor_Address = SourceGrid.Cells.Editors.Factory.Create(typeof(string));
            mEditor_Address.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.AnyKey | SourceGrid.EditableMode.SingleClick;
            grid1[0, 3] = new SourceGrid.Cells.ColumnHeader("ADDRESS (string)");

            mEditor_City = SourceGrid.Cells.Editors.Factory.Create(typeof(string));
            mEditor_City.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.AnyKey | SourceGrid.EditableMode.SingleClick;
            grid1[0, 4] = new SourceGrid.Cells.ColumnHeader("CITY (string)");

            mEditor_BirthDay = SourceGrid.Cells.Editors.Factory.Create(typeof(DateTime));
            mEditor_BirthDay.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.AnyKey | SourceGrid.EditableMode.SingleClick;
            grid1[0, 5] = new SourceGrid.Cells.ColumnHeader("BIRTHDATE (DateTime)");

            mEditor_Country = new SourceGrid.Cells.Editors.ComboBox(typeof(string), l_CountryList, false);
            mEditor_Country.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.AnyKey | SourceGrid.EditableMode.SingleClick;
            grid1[0, 6] = new SourceGrid.Cells.ColumnHeader("COUNTRY (string + combobox)");

            mEditor_Price = new SourceGrid.Cells.Editors.TextBoxCurrency(typeof(double));
            mEditor_Price.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.AnyKey | SourceGrid.EditableMode.SingleClick;
            grid1[0, 7] = new SourceGrid.Cells.ColumnHeader("$ PRICE (double)");

            grid1[0, 8] = new SourceGrid.Cells.ColumnHeader("Selected");

            grid1[0, 9] = new SourceGrid.Cells.ColumnHeader("WebSite");
            #endregion

            //Read Data From xml
            System.IO.StreamReader reader = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("WindowsFormsSample.GridSamples.SampleData.xml"));
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.LoadXml(reader.ReadToEnd());
            reader.Close();
            System.Xml.XmlNodeList rows = xmlDoc.SelectNodes("//row");
            grid1.RowsCount = rows.Count + 1;
            int rowsCount = 1;
            foreach (System.Xml.XmlNode l_Node in rows)
            {
                #region Pupulate RowsCount
                grid1[rowsCount, 0] = new SourceGrid.Cells.RowHeader(null);

                grid1[rowsCount, 1] = new SourceGrid.Cells.Cell(rowsCount, mEditor_Id);

                grid1[rowsCount, 2] = new SourceGrid.Cells.Cell(l_Node.Attributes["ContactName"].InnerText, mEditor_Name);

                grid1[rowsCount, 3] = new SourceGrid.Cells.Cell(l_Node.Attributes["Address"].InnerText, mEditor_Address);

                grid1[rowsCount, 4] = new SourceGrid.Cells.Cell(l_Node.Attributes["City"].InnerText, mEditor_City);

                grid1[rowsCount, 5] = new SourceGrid.Cells.Cell(DateTime.Today, mEditor_BirthDay);

                grid1[rowsCount, 6] = new SourceGrid.Cells.Cell(l_Node.Attributes["Country"].InnerText, mEditor_Country);

                grid1[rowsCount, 7]      = new SourceGrid.Cells.Cell(25.0, mEditor_Price);
                grid1[rowsCount, 7].View = mView_Price;

                grid1[rowsCount, 8] = new SourceGrid.Cells.CheckBox(null, false);

                grid1[rowsCount, 9] = new SourceGrid.Cells.Link(l_Node.Attributes["website"].InnerText);
                grid1[rowsCount, 9].AddController(mController_Link);
                #endregion

                rowsCount++;
            }

            grid1.AutoSizeCells();
        }
Beispiel #54
0
        public void Run()
        {
            if (!IsConnectedToInternet())
            {
                System.Console.WriteLine("Not connected to a network");
                return;
            }

            bool useLocalIP = true;

            if (!TryConnectLocalIP())
            {
                useLocalIP = false;
                System.Console.WriteLine("Could not connect through local IP address");
            }

            System.Console.WriteLine("Connect using {0}", baseUrl.TrimEnd('/'));

            using (var listener = new System.Net.HttpListener())
            {
                listener.Prefixes.Add(baseUrl);
                if (useLocalIP)
                {
                    listener.Prefixes.Add(ExternalUrl);
                }

                listener.Start();
                while (true)
                {
                    System.Net.HttpListenerContext ctx     = listener.GetContext();
                    System.Net.HttpListenerRequest request = ctx.Request;
                    System.Console.WriteLine(request.Url);

                    System.Net.HttpListenerResponse response = ctx.Response;

                    string urlString = request.Url.ToString();
                    string rawUrl    = request.RawUrl.ToString();

                    string responseText = null;

                    byte[] reponseBuffer = null;
                    if (rawUrl == root)
                    {
                        responseText         = defaultPage;
                        responseText         = responseText.Replace(baseUrl, urlString + "/");
                        response.ContentType = "text/HTML";
                    }
                    else if (rawUrl.StartsWith(WebService.resourcePrefix))
                    {
                        string resourceName = rawUrl.Remove(0, WebService.resourcePrefix.Length);

                        if (rawUrl.EndsWith(".jpg"))
                        {
                            reponseBuffer        = HtmlRenderer.GetEmbeddedContentAsBinary(resourceName);
                            response.ContentType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
                        }
                        else
                        {
                            responseText         = HtmlRenderer.GetEmbeddedContent(resourceName);
                            response.ContentType = "text/css";
                        }
                    }
                    else if (rawUrl.StartsWith(root + "/"))
                    {
                        var streamReader = new System.IO.StreamReader(request.InputStream, request.ContentEncoding);
                        var jsonRequest  = streamReader.ReadToEnd();

                        string requestedPage      = rawUrl.Remove(0, (root + "/").Length);
                        object unserializedObject = null;

                        Type serviceType;
                        if (mapNameToServiceType.TryGetValue(requestedPage, out serviceType))
                        {
                            unserializedObject = js.Deserialize(jsonRequest, serviceType);
                            if (unserializedObject == null)
                            {
                                unserializedObject = Activator.CreateInstance(serviceType);
                            }
                        }

                        if (unserializedObject is IRequestWithHtmlResponse)
                        {
                            responseText = ((IRequestWithHtmlResponse)unserializedObject).GetResponse(this);
                        }
                        else if (unserializedObject is IRequestWithJsonResponse)
                        {
                            object o          = ((IRequestWithJsonResponse)unserializedObject).GetResponse(this);
                            var    serialized = js.Serialize(o);
                            responseText = serialized;
                        }
                        response.ContentType = "text/html";
                    }

                    if (response.ContentType != null && response.ContentType.StartsWith("text") && responseText != null)
                    {
                        response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
                        reponseBuffer            = System.Text.Encoding.UTF8.GetBytes(responseText);
                    }

                    if (reponseBuffer != null)
                    {
                        //These headers to allow all browsers to get the response
                        response.Headers.Add("Access-Control-Allow-Credentials", "true");
                        response.Headers.Add("Access-Control-Allow-Origin", "*");
                        response.Headers.Add("Access-Control-Origin", "*");

                        //response.StatusCode = 200;
                        //response.StatusDescription = "OK";
                        // Get a response stream and write the response to it.
                        response.ContentLength64 = reponseBuffer.Length;
                        System.IO.Stream output = response.OutputStream;
                        output.Write(reponseBuffer, 0, reponseBuffer.Length);
                        output.Close();
                    }
                    response.Close();
                }
            }
        }
Beispiel #55
0
        //static void Main(string[] args) {
        //    Application<CNSControl>._Main(args, false, null, () => new ViscousShockProfile());
        //}

        protected override void SetInitial()
        {
            //base.SetInitial();
            WorkingSet.ProjectInitialValues(SpeciesMap, base.Control.InitialValues_Evaluators);
            string viscosityLaw = Control.ViscosityLaw.ToString();

            if (true)
            {
                DGField mpiRank = new SinglePhaseField(new Basis(GridData, 0), "rank");
                m_IOFields.Add(mpiRank);

                for (int j = 0; j < GridData.Cells.NoOfLocalUpdatedCells; j++)
                {
                    mpiRank.SetMeanValue(j, DatabaseDriver.MyRank);
                }
            }

            // exakte Lösung für 1D-Testfall
            int p = Control.MomentumDegree;
            CellQuadratureScheme scheme = new CellQuadratureScheme(true);
            int  order            = WorkingSet.Momentum[0].Basis.Degree * 2 + 2;
            int  noOfNodesPerCell = scheme.Compile(GridData, order).First().Rule.NoOfNodes;
            int  offset           = Grid.CellPartitioning.i0 * noOfNodesPerCell;
            long K = Grid.NumberOfCells;

            string pathToData;
            string initial;

            if (Grid.Description.Contains("Unsteady"))
            {
                pathToData = @"P:\ViscousTerms\NS_exact\data\M4_" + viscosityLaw + "_unsteady\\";
                initial    = "1";
            }
            else
            {
                pathToData = @"P:\ViscousTerms\NS_exact\data\M4_" + viscosityLaw + "_steady\\";
                initial    = "0";
            }

            ScalarFunction func = new ScalarFunction(
                (MultidimensionalArray arrIn, MultidimensionalArray arrOut) => {
                string filename = "m" + initial + "_" + K.ToString() + "_" + Control.MomentumDegree.ToString() + ".txt";
                double[] output;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(pathToData + filename)) {
                    output = sr.ReadToEnd().
                             Split(',').
                             Select((str) => double.Parse(str, System.Globalization.CultureInfo.InvariantCulture.NumberFormat)).
                             Skip(offset).
                             Take(Grid.CellPartitioning.LocalLength * noOfNodesPerCell).
                             ToArray();
                };
                output.CopyTo(arrOut.Storage, 0);
            }
                );

            WorkingSet.Momentum[0].ProjectField(1.0, func, scheme);

            p                = Control.EnergyDegree;
            scheme           = new CellQuadratureScheme(true);
            order            = WorkingSet.Energy.Basis.Degree * 2 + 2;
            noOfNodesPerCell = scheme.Compile(GridData, order).First().Rule.NoOfNodes;
            offset           = Grid.CellPartitioning.i0 * noOfNodesPerCell;

            func = new ScalarFunction(
                (MultidimensionalArray arrIn, MultidimensionalArray arrOut) => {
                string filename = "rhoE" + initial + "_" + K.ToString() + "_" + p.ToString() + ".txt";
                double[] output;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(pathToData + filename)) {
                    output = sr.ReadToEnd().
                             Split(',').
                             Select((str) => double.Parse(str, System.Globalization.CultureInfo.InvariantCulture.NumberFormat)).
                             Skip(offset).
                             Take(Grid.CellPartitioning.LocalLength * noOfNodesPerCell).
                             ToArray();
                };
                output.CopyTo(arrOut.Storage, 0);
            }
                );
            WorkingSet.Energy.ProjectField(func);


            p                = Control.DensityDegree;
            scheme           = new CellQuadratureScheme(true);
            order            = WorkingSet.Density.Basis.Degree * 2 + 2;
            noOfNodesPerCell = scheme.Compile(GridData, order).First().Rule.NoOfNodes;
            offset           = Grid.CellPartitioning.i0 * noOfNodesPerCell;

            func = new ScalarFunction(
                (MultidimensionalArray arrIn, MultidimensionalArray arrOut) => {
                string filename = "rho" + initial + "_" + K.ToString() + "_" + p.ToString() + ".txt";
                double[] output;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(pathToData + filename)) {
                    output = sr.ReadToEnd().
                             Split(',').
                             Select((str) => double.Parse(str, System.Globalization.CultureInfo.InvariantCulture.NumberFormat)).
                             Skip(offset).
                             Take(Grid.CellPartitioning.LocalLength * noOfNodesPerCell).
                             ToArray();
                };
                output.CopyTo(arrOut.Storage, 0);
            }
                );

            WorkingSet.Density.ProjectField(func);
            WorkingSet.UpdateDerivedVariables(this, CellMask.GetFullMask(GridData));

            //string guidString = "00000000-0000-0000-0000-000000000000";

            //switch (K) {
            //    case 32:
            //        guidString = "6725b9fc-d072-44cd-ae72-196e8a692735";
            //        break;
            //    case 64:
            //        guidString = "cb714aec-4b4a-4dae-9e70-32861daa195f";
            //        break;
            //    case 128:
            //        guidString = "678dc736-bbf6-4a1e-86eb-4f80b2354748";
            //        break;
            //}


            //Guid tsGuid = new Guid(guidString);
            //var db = this.GetDatabase();
            //string fieldName = "rho";
            //ITimestepInfo tsi = db.Controller.DBDriver.LoadTimestepInfo(tsGuid, null, db);
            //previousRho = (SinglePhaseField)db.Controller.DBDriver.LoadFields(tsi, GridData, new[] { fieldName }).Single().CloneAs();
            //diffRho = WorkingSet.Density.CloneAs();
            //diffRho.Clear();


            //fieldName = "rhoE";
            //previousRhoE = (SinglePhaseField)db.Controller.DBDriver.LoadFields(tsi, GridData, new[] { fieldName }).Single().CloneAs();
            //diffRhoE = WorkingSet.Energy.CloneAs();
            //diffRhoE.Clear();

            //fieldName = "m0";
            //previousM0 = (SinglePhaseField)db.Controller.DBDriver.LoadFields(tsi, GridData, new[] { fieldName }).Single().CloneAs();
            //diffM0 = WorkingSet.Momentum[0].CloneAs();
            //diffM0.Clear();

            //diffRho.Identification = "diffRho";
            //diffM0.Identification = "diffM0";
            //diffRhoE.Identification = "diffRhoE";
            //previousRho.Identification = "Rho_analy";
            //previousM0.Identification = "M0_analy";
            //previousRhoE.Identification = "RhoE_analy";
            //m_IOFields.Add(diffM0);
            //m_IOFields.Add(diffRho);
            //m_IOFields.Add(diffRhoE);
            //m_IOFields.Add(previousM0);
            //m_IOFields.Add(previousRho);
            //m_IOFields.Add(previousRhoE);
        }
            public ItemInfo GetItemInfo(int _ItemID, WowVersionEnum _WowVersion)
            {
                try
                {
                    var itemInfoCache = GetItemInfoCache(_WowVersion, true);
                    if (itemInfoCache == null)
                    {
                        return(null);
                    }
                    ItemInfo itemInfo = null;
                    //m_ItemInfoLock.AcquireReaderLock(1000);
                    Monitor.Enter(m_ItemInfoLock);
                    if (itemInfoCache.ContainsKey(_ItemID) == true)
                    {
                        itemInfo = itemInfoCache[_ItemID];
                        Monitor.Exit(m_ItemInfoLock);
                    }
                    else
                    {
                        Monitor.Exit(m_ItemInfoLock);
                        foreach (string itemDatabaseAddress in m_CurrentItemDatabaseOrder)
                        {
                            try
                            {
                                //System.Net.WebClient webClient = new System.Net.WebClient();
                                //var cook = new System.Collections.Specialized.NameValueCollection();
                                //cook.Add("dbVersion", "0");
                                System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
                                //cookieContainer.Add(new Uri(itemDatabaseAddress), new System.Net.Cookie("PHPSESSID", "d617cebcf593d37bde6c9c8caa01ef18"));
                                var webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(itemDatabaseAddress + "ajax.php?item=" + _ItemID);
                                webRequest.Timeout          = 5000;
                                webRequest.ReadWriteTimeout = 5000;
                                if (itemDatabaseAddress.Contains("database.wow-one.com"))
                                {
                                    if (_WowVersion == WowVersionEnum.Vanilla)
                                    {
                                        cookieContainer = DatabaseWowOneCookies_Get();//Hämta rätt cookies när det är vanilla
                                        //cookieContainer.SetCookies(new Uri("http://database.wow-one.com"), "dbVersion=0");
                                    }
                                }
                                else
                                {
                                    if (_WowVersion == WowVersionEnum.TBC)
                                    {
                                        continue;//Bara stöd för database.wow-one.com när det är TBC
                                    }
                                }
                                webRequest.CookieContainer = cookieContainer;
                                using (var webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse())
                                {
                                    using (System.IO.StreamReader reader = new System.IO.StreamReader(webResponse.GetResponseStream()))
                                    {
                                        string ajaxItemData = reader.ReadToEnd();
                                        if (ajaxItemData.StartsWith("$WowheadPower.registerItem"))//Success?
                                        {
                                            string[] itemData = ajaxItemData.Split('{', '}');
                                            if (itemData.Length == 3)//Success!(?)
                                            {
                                                itemInfo = new ItemInfo(_ItemID, ajaxItemData, itemDatabaseAddress);
                                                if (
                                                    (
                                                        itemDatabaseAddress.Contains("database.wow-one.com") && (
                                                            (_WowVersion == WowVersionEnum.Vanilla && webResponse.Headers.Get("Set-Cookie").Contains("dbVersion=0")) ||
                                                            (_WowVersion == WowVersionEnum.TBC && webResponse.Headers.Get("Set-Cookie").Contains("dbVersion=1"))
                                                            )
                                                    ) ||
                                                    itemDatabaseAddress.Contains("db.vanillagaming.org") ||
                                                    itemDatabaseAddress.Contains("db.valkyrie-wow.com"))
                                                {
                                                    lock (m_ItemInfoLock)
                                                    {
                                                        if (itemInfoCache.ContainsKey(_ItemID) == false)
                                                        {
                                                            itemInfoCache.Add(_ItemID, itemInfo);
                                                        }
                                                        else
                                                        {
                                                            itemInfoCache[_ItemID] = itemInfo;
                                                        }
                                                        m_ItemInfoUpdated = true;
                                                    }
                                                    if (itemDatabaseAddress != m_CurrentItemDatabaseOrder.First())
                                                    {
                                                        var newItemDatabaseOrder = new List <string>(StaticValues.ItemDatabaseAddresses);
                                                        newItemDatabaseOrder.Remove(itemDatabaseAddress);
                                                        newItemDatabaseOrder.Insert(0, itemDatabaseAddress);
                                                        m_CurrentItemDatabaseOrder = newItemDatabaseOrder;
                                                    }
                                                }
                                                else
                                                {
                                                    DatabaseWowOneCookies_Clear();
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception)
                            { }
                        }
                        //http://db.vanillagaming.org/ajax.php?item=19146

                        //http://db.vanillagaming.org/ajax.php?item=19146
                        //http://db.vanillagaming.org/images/icons/large/inv_bracer_04.jpg
                    }
                    return(itemInfo);
                }
                catch (Exception ex)
                {
                    Logger.LogException(ex);
                    return(null);
                }
            }
Beispiel #57
0
        private void Submit(HttpContext context)
        {
            try
            {
                string[] path = context.Request["path"].Split(new char[1] {
                    '/'
                });
                string     className  = path[2].Trim();
                string     methodName = path[3].Trim();
                Type       t          = Type.GetType("PMS.api." + className);
                object     instance   = Activator.CreateInstance(t);
                MethodInfo methodInfo = t.GetMethod(methodName);
                if (instance == null || methodInfo == null)
                {
                    throw new PMSException("api不存在");
                }
                System.IO.StreamReader stream = new System.IO.StreamReader(context.Request.InputStream, Encoding.UTF8);
                string postData = stream.ReadToEnd();
                stream.Close();
                JsonData jd      = new JsonData();//返回JsonData
                string[] key_val = postData.Split('&');
                for (int i = 0; i < key_val.Length; i++)
                {
                    if (key_val[i].Trim() != "")
                    {
                        string[] keys = key_val[i].Split('=');
                        jd[keys[0]] = keys[1];
                    }
                }
                postData = jd.ToJson();
                methodInfo.Invoke(instance, new object[] { context, context.Server.UrlDecode(postData) });
            }
            catch (PMSException ex)
            {
                int    errCode = (int)ex.ReCode;
                string message = string.Empty;
                if (ex.ReCode == PMSCode.ERROR)
                {
                    message = ex.Message; //直接输出消息
                }
                else
                {
                    message = ex.ReCode.ToString();
                }
                Hashtable ht = new Hashtable();
                ht.Add("code", errCode);
                ht.Add("message", message);
                string json = LitJson.JsonMapper.ToJson(ht);
                PMSResponse.WirterString(json);
            }
            catch (Exception ex)
            {
                PMSException ex_ie   = ex.InnerException as PMSException;
                int          errCode = 0;
                string       message = string.Empty;

                if (ex_ie != null) //如果是自定义异常抛出
                {
                    errCode = (int)ex_ie.ReCode;
                    if (ex_ie.ReCode == PMSCode.ERROR)
                    {
                        message = ex_ie.Message; //直接输出消息
                    }
                    else
                    {
                        message = PMSResponse.GetEnumDesc(ex_ie.ReCode);
                    }
                }
                else
                {
                    errCode = -1;
                    message = "系统异常," + ex.Message;
                }
                Hashtable ht = new Hashtable();
                ht.Add("code", errCode);
                ht.Add("message", message);
                string json = LitJson.JsonMapper.ToJson(ht);
                PMSResponse.WirterString(json);
            }
        }
Beispiel #58
0
        static ErrorCode ProcVersionList()
        {
            ErrorCode          ret_code          = ErrorCode.NO_ERROR;
            string             url               = Properties.Settings.Default.PythonURL;
            string             source            = "";
            List <VersionInfo> version_info_list = new List <VersionInfo>();
            List <string>      version_list      = new List <string>();

            System.Net.HttpWebRequest webreq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            Console.Write(url + "を検索中です。 ");
            using (System.Net.HttpWebResponse webres = (System.Net.HttpWebResponse)webreq.GetResponse())
            {
                using (System.IO.Stream st = webres.GetResponseStream())
                {
                    //文字コードを指定して、StreamReaderを作成
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(st, System.Text.Encoding.UTF8))
                    {
                        source = sr.ReadToEnd();
                    }
                }
            }

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(source);
            foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a"))
            {
                Console.Write(WaitChar());
                if (System.Text.RegularExpressions.Regex.IsMatch(link.InnerHtml, @"^[0-9]+(\.[0-9]+)*"))
                {
                    Regex re = new Regex(@"^[0-9]+(\.[0-9]+)*/", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    Match m  = re.Match(link.InnerHtml);
                    while (m.Success)
                    {
                        Console.Write(WaitChar());
                        if (m.Value == link.InnerHtml)
                        {
                            version_list.Add(m.Value.TrimEnd('/'));
                        }
                        m = m.NextMatch();
                    }
                }
            }
            foreach (var ver in version_list)
            {
                webreq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url + '/' + ver + '/');
                using (System.Net.HttpWebResponse webres = (System.Net.HttpWebResponse)webreq.GetResponse())
                {
                    using (System.IO.Stream st = webres.GetResponseStream())
                    {
                        //文字コードを指定して、StreamReaderを作成
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(st, System.Text.Encoding.UTF8))
                        {
                            source = sr.ReadToEnd();
                        }
                    }
                }

                doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(source);
                foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a"))
                {
                    Console.Write(WaitChar());
                    string file_name = "";
                    file_name = string.Format(Properties.Settings.Default.PythonEmbedName, ver, Properties.Settings.Default.ArchAmd64);
                    if (link.InnerHtml.Equals(file_name))
                    {
                        version_info_list.Add(new VersionInfo()
                        {
                            Version = ver, Arch = Properties.Settings.Default.ArchAmd64, FileName = file_name
                        });
                    }
                    file_name = string.Format(Properties.Settings.Default.PythonEmbedName, ver, Properties.Settings.Default.ArchWin32);
                    if (link.InnerHtml.Equals(file_name))
                    {
                        version_info_list.Add(new VersionInfo()
                        {
                            Version = ver, Arch = Properties.Settings.Default.ArchWin32, FileName = file_name
                        });
                    }
                }
            }
            Console.Write("\b ");
            Console.Write(Environment.NewLine);
            version_info_list.Sort((a, b) => string.Compare(Version2String(a.Version), Version2String(b.Version)));

            foreach (var ver in version_info_list)
            {
                Console.WriteLine(ver.VersionName);
            }
            return(ret_code);
        }
Beispiel #59
0
 public override string ReadToEnd()
 {
     return(_actual.ReadToEnd());
 }
Beispiel #60
0
        public MainPage()
        {
            int i;                          // 有象無象

            // おおもとの初期化
            InitializeComponent();
            running = false;
            isSleep = false;

            // 事前のハイスコア処理
            var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
                               + "HighScore.txt";

            if (System.IO.File.Exists(localAppData))
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(localAppData)) {
                    highscore = int.Parse(sr.ReadToEnd());
                }
            }
            else
            {
                highscore = 0;
            }
            highscoreLabel.Text = " HighScore: " + highscore.ToString("####0");

            // イメージ配列の格納
            Grid grid;

            grid    = g;
            _images = new ExImage[9];
            for (i = 0; i < 9; i++)
            {
                _images[i]                 = new ExImage();
                _images[i].Source          = ImageSource.FromResource("PiroZangi.image.plain.png");
                _images[i].BackgroundColor = Color.FromRgb(131, 225, 139);
                _images[i].TabIndex        = i;
                grid.Children.Add(_images[i], i / 3 + 1, i % 3 + 1);
            }

            // タッチイベントの実装
            for (i = 0; i < 9; i++)
            {
                _images[i].Down += (sender, a) => {
                    if ((((ExImage)sender).TabIndex == alive) && (hit == false))
                    {
                        hit = true;
                        // 効果音
                        using (soundEffect as IDisposable) {
                            soundEffect.SoundPlay(character + 1);
                        }
                        // キャラクタに応じてグラフィックを変更
                        switch (character)
                        {
                        case 0:         // ザンギの場合
                            score += 100;
                            _images[alive].Source = ImageSource.FromResource("PiroZangi.image.zangi_p.png");
                            break;

                        case 1:         // 青のりダーの場合
                            score += 200;
                            _images[alive].Source = ImageSource.FromResource("PiroZangi.image.aonori_p.png");
                            break;

                        case 2:         // ピロ助の場合
                            score -= 50;
                            _images[alive].Source = ImageSource.FromResource("PiroZangi.image.piro_p.png");
                            break;

                        case 3:         // 店長の場合
                            score -= 1;
                            _images[alive].Source = ImageSource.FromResource("PiroZangi.image.ten_p.png");
                            break;

                        case 4:         // ゆいまーるの場合
                            score -= 10000;
                            _images[alive].Source = ImageSource.FromResource("PiroZangi.image.yui_p.png");
                            break;

                        case 5:         // キャプテンの場合
                            score = 0;
                            _images[alive].Source = ImageSource.FromResource("PiroZangi.image.cap_p.png");
                            break;

                        default:
                            break;
                        }

                        // スコアとハイスコア処理
                        scoreLabel.Text = "Score: " + score.ToString("####0");
                        if (score > highscore)
                        {
                            highscore           = score;
                            highscoreLabel.Text = "HighScore: " + highscore.ToString("####0");
                        }
                    }
                };
            }

            // タイマー処理
            Device.StartTimer(TimeSpan.FromMilliseconds(10), () => {
                // 走ってなきゃ処理しない
                if (running == false)
                {
                    return(true);
                }

                // 時間減算
                remain--;
                countBtn.Text = (remain / 100).ToString() + "." + (remain % 100).ToString("00");

                // 時間内なら
                if (remain > 0)
                {
                    intervalcnt--;
                    if (intervalcnt <= 0)
                    {
                        // 穴を戻して次の出現場所を選択
                        _images[alive].Source = ImageSource.FromResource("PiroZangi.image.plain.png");
                        hit   = false;
                        alive = (alive + r.Next(1, 8)) % 9;

                        // キャラクタ選択
                        character = r.Next(0, 100);
                        if (character < 70)
                        {
                            character             = 0;
                            _images[alive].Source = ImageSource.FromResource("PiroZangi.image.zangi.png");
                        }
                        else if (character < 80)
                        {
                            character             = 1;
                            _images[alive].Source = ImageSource.FromResource("PiroZangi.image.aonori.png");
                        }
                        else if (character < 87)
                        {
                            character             = 2;
                            _images[alive].Source = ImageSource.FromResource("PiroZangi.image.piro.png");
                        }
                        else if (character < 94)
                        {
                            character             = 3;
                            _images[alive].Source = ImageSource.FromResource("PiroZangi.image.ten.png");
                        }
                        else if (character < 98)
                        {
                            character             = 4;
                            _images[alive].Source = ImageSource.FromResource("PiroZangi.image.yui.png");
                        }
                        else
                        {
                            character             = 5;
                            _images[alive].Source = ImageSource.FromResource("PiroZangi.image.cap.png");
                        }

                        // 時間間隔調整
                        interval -= 3;
                        if (interval <= 10)
                        {
                            interval = 10;
                        }
                        intervalcnt = interval;
                    }
                }
                else     // 時間をオーバーしたらそれで試合終了ですよ
                // 終了BGM
                {
                    DependencyService.Get <IMediaPlayer>().Stop();
                    using (soundEffect as IDisposable) {
                        soundEffect.SoundPlay(7);
                    }

                    // ハイスコアの保存
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(localAppData)) {
                        sw.Write(highscore.ToString());
                    }
                    // 穴を元に戻してリプレイ確認
                    _images[alive].Source = ImageSource.FromResource("PiroZangi.image.plain.png");
                    countBtn.Text         = "も う 1 回 ?";
                    running = false;
                    hit     = false;
                }
                return(true);
            });

            // 開始の効果音
            using (soundEffect as IDisposable)
            {
                soundEffect.SoundPlay(0);
            }
        }