示例#1
1
        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);
        }
示例#2
1
        public void UpdateFiles()
        {
            try
            {
                WriteLine("Local version: " + Start.m_Version);

                WebClient wc = new WebClient();
                string versionstr;
                using(System.IO.StreamReader sr = new System.IO.StreamReader(wc.OpenRead(baseurl + "version.txt")))
                {
                    versionstr = sr.ReadLine();
                }
                Version remoteversion = new Version(versionstr);
                WriteLine("Remote version: " + remoteversion);

                if(Start.m_Version < remoteversion)
                {
                    foreach(string str in m_Files)
                    {
                        WriteLine("Updating: " + str);
                        wc.DownloadFile(baseurl + str, str);
                    }
                }
                wc.Dispose();
                WriteLine("Update complete");
            }
            catch(Exception e)
            {
                WriteLine("Update failed:");
                WriteLine(e);
            }
            this.Button_Ok.Enabled = true;
        }
        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();

            }
        }
示例#4
0
            public override void Configure(Funq.Container container)
            {
                Plugins.Add (new RequestLogsFeature ());
                    this.Config.DefaultContentType = "Json";
                    //container.RegisterAutoWired<InMemoryFileSystem>();

                    InMemoryFileSystem fileSystem = new InMemoryFileSystem ();
                    container.Register<InMemoryFileSystem> (fileSystem);

                    Console.WriteLine ("Application_Start ---->. Begin");

                    //Start the ISIS System
                    IsisSystem.Start ();

                    Console.WriteLine ("ISIS Started :)");

                    FileServerComm.fileServerGroupName = "FileServer";
                    FileServerComm fileSrvComm = FileServerComm.getInstance ();

                    fileSrvComm.getFileHandler ().filesystem = fileSystem;

                    System.IO.StreamReader file = new System.IO.StreamReader ("bootstrap.txt");
                    string line = file.ReadLine ();
                    Console.WriteLine (line);

                    bool isBootStrap = false;
                    if (line.Equals ("1")) {
                        isBootStrap = true;
                    }

                    fileSrvComm.ApplicationStartup(isBootStrap,FileServerComm.fileServerGroupName);

                    Console.WriteLine("Application_Start. End");
            }
 private void Button1_Click(object sender, EventArgs e)
 {
     openFileDialog1.ShowDialog();
     System.IO.StreamReader OpenFile = new System.IO.StreamReader(openFileDialog1.FileName);
     txtphoto.Text = openFileDialog1.FileName;
     OpenFile.Close();
 }
示例#6
0
        private void AnalyzeTweets(string inputFilePath)
        {
            if (inputFilePath == string.Empty)
                return;
            if (!System.IO.File.Exists(inputFilePath))
                return;

            int counter = 0;
            string line;

            System.IO.StreamReader sourceFile = new System.IO.StreamReader(inputFilePath);
            System.IO.StreamWriter ft1File = new System.IO.StreamWriter(outputFt1);
            System.IO.StreamWriter ft2File = new System.IO.StreamWriter(outputFt2);

            while ((line = sourceFile.ReadLine()) != null)
            {
                AnalyzeTweet(line);
                ft2File.WriteLine(GetMedian(numOfUniqueWords).ToString());
            }
            foreach(KeyValuePair<string, int> item in wordCount )
            {
                ft1File.WriteLine(String.Format("{0}\t{1}", item.Key, item.Value.ToString()));
            }
            ft1File.Flush();
            ft1File.Close();

            ft2File.Flush();
            ft2File.Close();

            lblStatus.Text = "Done.";
        }
示例#7
0
文件: OAuth2Helper.cs 项目: JDCB/JDCB
        /// <summary>
        /// 模拟登录
        /// </summary>
        /// <param name="passport"></param>
        /// <param name="password"></param>
        /// <param name="cancelToken"></param>
        /// <returns></returns>
        public async Task<OAuthAccessToken> LoginAsync(string passport, string password, CancellationToken cancelToken)
        {
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
            {
                return true;
            };
            var request = WebRequest.Create(Settings.AuthorizeUrl) as HttpWebRequest;

            request.Referer = GetAuthorizeUrl();
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = new CookieContainer();

            var postBody = GetSimulateLoginPostBody(passport, password);
            var postData = System.Text.Encoding.UTF8.GetBytes(postBody);

            cancelToken.ThrowIfCancellationRequested();
            var result = "";
            using (var requestStream = await request.GetRequestStreamAsync())
            {
                await requestStream.WriteAsync(postData, 0, postData.Length, cancelToken);
            }
            using (var response = await request.GetResponseAsync())
            {
                using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    cancelToken.ThrowIfCancellationRequested();
                    result = await sr.ReadToEndAsync();
                    return ConvertToAccessTokenByRegex(result);
                }
            }
        }
示例#8
0
        public List<string[]> Read()
        {
            try {
                System.IO.FileInfo backlogFile = new System.IO.FileInfo(SQ.Util.Constant.BACKLOG_FILE);
                if (!backlogFile.Exists){
                    backlogFile.Create();
                    return new List<string[]>();
                }

                System.IO.StreamReader sr = new System.IO.StreamReader (SQ.Util.Constant.BACKLOG_FILE);
                Repo.LastSyncTime = backlogFile.LastWriteTime;
                List<string[]> filesInBackLog = new List<string[]>();
                int i = 1;
                while (!sr.EndOfStream) {
                    string [] info = BreakLine (sr.ReadLine (), 5);
                    filesInBackLog.Add (info);
                    i++;
                }
                sr.Dispose();
                sr.Close ();
                return filesInBackLog;
            } catch (Exception e) {
                SQ.Util.Logger.LogInfo("Sync", e);
                return null;
            }
        }
        public FedexDeleteShipmentReply Post()
        {
            FedexDeleteShipmentReply result = null;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.m_FedexAccount.URL);
            byte[] bytes;
            bytes = System.Text.Encoding.ASCII.GetBytes(this.m_ProcessShipmentRequest.ToString());
            request.ContentType = "text/xml; encoding='utf-8'";
            request.ContentLength = bytes.Length;
            request.Method = "POST";
            System.IO.Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                System.IO.Stream responseStream = response.GetResponseStream();
                string responseStr = new System.IO.StreamReader(responseStream).ReadToEnd();
                result = new FedexDeleteShipmentReply(responseStr);
            }
            else
            {
                result = new FedexDeleteShipmentReply(false);
            }

            return result;
        }
示例#10
0
        private void loadFile(string path)
        {
            checkedListBox1.Items.Clear();
            System.IO.StreamReader sr = new
               System.IO.StreamReader(path);
            string line;
            try
            {
                while ((line = sr.ReadLine()) != null)
                {
                    string[] words = line.Split(',');
                    bool isChecked = Convert.ToBoolean(Convert.ToInt16(words[1]));
                    checkedListBox1.Items.Add(words[0]);
                    checkedListBox1.SetItemChecked(checkedListBox1.Items.Count - 1, isChecked);
                }
            }
            catch (IndexOutOfRangeException)
            {
                MessageBox.Show("An error has occured. The file " + openFileDialog1.SafeFileName +
                                " is corrupt or invalid.", "File error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                checkedListBox1.Items.Clear();
            }

            sr.Close();
        }
示例#11
0
        public void UploadFileTest()
        {
            var req = (HttpWebRequest)HttpWebRequest.Create("http://alex/asc/products/files/Services/WCFService/Service.svc/folders/files?id=1");

            req.Method = "POST";
            req.ContentType = "application/octet-stream";
            var reqStream = req.GetRequestStream();

            var fileToSend = System.IO.File.ReadAllBytes(@"c:\1.odt");

            reqStream.Write(fileToSend, 0, fileToSend.Length);
            reqStream.Close();

            var resp = (HttpWebResponse)req.GetResponse();

            var sr = new System.IO.StreamReader(resp.GetResponseStream(), Encoding.Default);
            var count = 0;
            var ReadBuf = new char[1024];
            do
            {
                count = sr.Read(ReadBuf, 0, 1024);
                if (0 != count)
                {
                    Console.WriteLine(new string(ReadBuf));
                }

            } while (count > 0);
            Console.WriteLine("Client: Receive Response HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
        }
示例#12
0
文件: Web.cs 项目: a79361360/GetMoney
        /// <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;
            }
        }
示例#13
0
        /* ----------------------------------------------------------------- */
        //  Parse
        /* ----------------------------------------------------------------- */
        public Container.Dictionary<string, string> Parse(string product, string version, bool init)
        {
            Container.Dictionary<string, string> dest = null;

            var uri = "http://" + host_ + "/" + product + "/update.php?ver=" + System.Web.HttpUtility.UrlEncode(version);
            if (init) uri += "&flag=install";

            var request = System.Net.WebRequest.Create(uri);
            using (var response = request.GetResponse()) {
                using (var input = response.GetResponseStream()) {
                    string line = "";
                    var reader = new System.IO.StreamReader(input, System.Text.Encoding.GetEncoding("UTF-8"));
                    while ((line = reader.ReadLine()) != null) {
                        if (line.Length > 0 && line[0] == '[' && line[line.Length - 1] == ']') {
                            var version_cmp = line.Substring(1, line.Length - 2);
                            if (version_cmp == version) {
                                dest = ExecParse(reader);
                                break;
                            }
                        }
                    }
                }
            }

            return dest;
        }
示例#14
0
        static Regex lineSimpleApply = CreateRegex(@"^Ext.apply\(\s*(?<name>({id}\.)?{idx})(\.prototype)?.*"); // e.g. Ext.apply(Dextop.common, {

        #endregion Fields

        #region Methods

        public override void ProcessFile(String filePath, Dictionary<String, LocalizableEntity> map)
        {
            ClasslikeEntity jsObject = null;
            System.IO.TextReader reader = new System.IO.StreamReader(filePath, Encoding.UTF8);
            //Logger.LogFormat("Processing file {0}", filePath);
            try
            {
                while (reader.Peek() > 0)
                {
                    String line = reader.ReadLine();
                    ClasslikeEntity o = ProcessExtendLine(filePath, line);
                    if (o != null)
                        jsObject = o;

                    else if (jsObject != null) {
                        LocalizableEntity prop = ProcessPropertyLine(jsObject, line);
                        if (prop != null && !map.ContainsKey(prop.FullEntityPath))
                            map.Add(prop.FullEntityPath, prop);
                    }
                }
                Logger.LogFormat("Processing file {0} - Success", filePath);
            }
            catch (Exception ex)
            {
                Logger.LogFormat("Processing file {0} - Error", filePath);
                throw ex;
            }
            finally
            {
                reader.Close();
            }
        }
示例#15
0
        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);
            }

        }
示例#16
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);
            }
        }
        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;
            }
        }
示例#18
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);
            }
        }
示例#19
0
        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;
        }
        public void LoadApplicationConfigurationDefaultsValuesTest()
        {
            var serializer = new XmlSerializer(typeof(ApplicationConfiguration));
            var stream = new System.IO.StreamReader(@"D:\TekWorc\Freetime-G-Business-Platform\1.0.x.x\Freetime.Deployment.Configuration\ApplicationConfiguration\ApplicationConfigurationDefaults.xml");

            var appConfig = serializer.Deserialize(stream) as ApplicationConfiguration;
        }
示例#21
0
        public static decimal ObtenerMedidaVertical ()
        {
            decimal vertical=0m;
            decimal horizontal=0m;
            if (System.IO.File.Exists(path))
            {
                System.IO.StreamReader SR = new System.IO.StreamReader(path);
                vertical = separatevaluefromparameter(SR.ReadLine())*pulgada;
                horizontal = separatevaluefromparameter(SR.ReadLine())*pulgada;
                
                SR.Close();
            }

            if (vertical > pulgada) 
            {
                vertical = 0.375m - (vertical - pulgada);
            }
            else if (vertical < pulgada) 
            {
                vertical = (pulgada - vertical) + 0.375m;
            }
            else if (vertical == pulgada)
            {
                vertical = 0.375m;
            }

            return vertical;
        }
        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);
            }
        }
示例#23
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;
            }
        }
示例#24
0
        private void LoadTestCredential()
        {
            string path = @"C:\Temp\AmazonAwsS3Test.xml";
            Models.AwsCredential credential;
            var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Models.AwsCredential));

            if (!System.IO.File.Exists(path))
            {
                //Cria um arquivo xml novo, se já não existir um
                credential = new Models.AwsCredential();
                credential.User = string.Empty;
                credential.AccessKeyId = string.Empty;
                credential.SecretAccessKey = string.Empty;
                credential.Region = string.Empty;

                using (var streamWriter = new System.IO.StreamWriter(path))
                {
                    xmlSerializer.Serialize(streamWriter, credential);
                }
            }

            //Carrega o xml
            using (var streamReader = new System.IO.StreamReader(path))
            {
                credential = (Models.AwsCredential)xmlSerializer.Deserialize(streamReader);
            }

            txtAccessKeyId.Text = credential.AccessKeyId;
            txtSecretAccessKey.Text = credential.SecretAccessKey;
            txtRegion.Text = credential.Region;
        }
示例#25
0
        private void parseBiografia()
        {
            string line;
            char[] delimiterChars1 = { ':' };
            char[] delimiterChars2 = { '.' };
            List<String> lista = new List<String>();

            int BIO_ESTADO_INDEX = 0;

            // Read the file and display it line by line.
            System.IO.StreamReader file = new System.IO.StreamReader(Biografia);
            while ((line = file.ReadLine()) != null && BIO_ESTADO_INDEX < BioEstado)
            {
                string[] words = line.Split(delimiterChars1);

                if (words[0].Contains("P"))
                {
                    string[] numbers = words[0].Split(delimiterChars2);
                    this.ParagrafosBiografia.Add(Int32.Parse(numbers[0]), words[2]);
                }

                BIO_ESTADO_INDEX++;
            }
            file.Close();
        }
示例#26
0
        static void LoadSampleData()
        {
            int counter = 0;
            string line;

            IHttpClient client = new HttpClient();

            // Simple data import operation
            using (System.IO.StreamReader file = new System.IO.StreamReader(@"C:\GitHub\iAFWeb\data\top-1m.csv"))
            {
                while ((line = file.ReadLine()) != null)
                {
                    String[] values = line.Split(',');
                    if (values.Length == 2)
                    {
                        string url = String.Format("http://{0}", values[1]);
                        Uri uri;
                        if(Uri.TryCreate(url, UriKind.Absolute, out uri))
                        {
                            var response = client.Shorten(uri.ToString());
                            Console.WriteLine(counter + " : " + response.ShortId + " : " + uri.ToString());
                            counter++;
                        }
                    }
                }
            }

            // Suspend the screen.
            Console.ReadLine();
        }
示例#27
0
		/// <summary> Loads a text file and adds every non-comment line as an entry to a HashSet (omitting
		/// leading and trailing whitespace). Every line of the file should contain only
		/// one word. The words need to be in lowercase if you make use of an
		/// Analyzer which uses LowerCaseFilter (like StandardAnalyzer).
		/// </summary>
		/// <param name="wordfile">File containing the wordlist</param>
		/// <param name="comment">The comment string to ignore</param>
		/// <returns> A HashSet with the file's words</returns>
		public static ISet<string> GetWordSet(System.IO.FileInfo wordfile, System.String comment)
		{
            using (var reader = new System.IO.StreamReader(wordfile.FullName, System.Text.Encoding.Default))
            {
                return GetWordSet(reader, comment);
            }
		}
示例#28
0
        public static Move LoadMove(int moveNum)
        {
            Move move = new Move();
            string[] parse = null;
            using (System.IO.StreamReader read = new System.IO.StreamReader(IO.Paths.MovesFolder + "move" + moveNum + ".dat")) {
                while (!(read.EndOfStream)) {
                    parse = read.ReadLine().Split('|');
                    switch (parse[0].ToLower()) {
                        case "movedata":
                            if (parse[1].ToLower() != "v4") {
                                read.Close();
                                return null;
                            }
                            break;
                        case "data":
                            move.Name = parse[1];
                            move.MaxPP = parse[2].ToInt();
                            move.EffectType = (Enums.MoveType)parse[3].ToInt();
                            move.Element = (Enums.PokemonType)parse[4].ToInt();
                            move.MoveCategory = (Enums.MoveCategory)parse[5].ToInt();
                            move.RangeType = (Enums.MoveRange)parse[6].ToInt();
                            move.Range = parse[7].ToInt();
                            move.TargetType = (Enums.MoveTarget)parse[8].ToInt();

                            move.Data1 = parse[9].ToInt();
                            move.Data2 = parse[10].ToInt();
                            move.Data3 = parse[11].ToInt();
                            move.Accuracy = parse[12].ToInt();
                            move.HitTime = parse[13].ToInt();
                            move.AdditionalEffectData1 = parse[14].ToInt();
                            move.AdditionalEffectData2 = parse[15].ToInt();
                            move.AdditionalEffectData3 = parse[16].ToInt();
                            move.PerPlayer = parse[17].ToBool();

                            move.KeyItem = parse[18].ToInt();

                            move.Sound = parse[19].ToInt();

                            move.AttackerAnim.AnimationType = (Enums.MoveAnimationType)parse[20].ToInt();
                            move.AttackerAnim.AnimationIndex = parse[21].ToInt();
                            move.AttackerAnim.FrameSpeed = parse[22].ToInt();
                            move.AttackerAnim.Repetitions = parse[23].ToInt();

                            move.TravelingAnim.AnimationType = (Enums.MoveAnimationType)parse[24].ToInt();
                            move.TravelingAnim.AnimationIndex = parse[25].ToInt();
                            move.TravelingAnim.FrameSpeed = parse[26].ToInt();
                            move.TravelingAnim.Repetitions = parse[27].ToInt();

                            move.DefenderAnim.AnimationType = (Enums.MoveAnimationType)parse[28].ToInt();
                            move.DefenderAnim.AnimationIndex = parse[29].ToInt();
                            move.DefenderAnim.FrameSpeed = parse[30].ToInt();
                            move.DefenderAnim.Repetitions = parse[31].ToInt();

                            break;
                    }
                }
            }

            return move;
        }
示例#29
0
        private static void OtherWaysToGetReport()
        {
            string report = @"d:\bla.rdl";

            // string lalal = System.IO.File.ReadAllText(report);
            // byte[] foo = System.Text.Encoding.UTF8.GetBytes(lalal);
            // byte[] foo = System.IO.File.ReadAllBytes(report);

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {

                using (System.IO.FileStream file = new System.IO.FileStream(report, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    byte[] bytes = new byte[file.Length];
                    file.Read(bytes, 0, (int)file.Length);
                    ms.Write(bytes, 0, (int)file.Length);
                    ms.Flush();
                    ms.Position = 0;
                }

                using (System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("resource"))
                {
                    using (System.IO.TextReader reader = new System.IO.StreamReader(ms))
                    {
                        // rv.LocalReport.LoadReportDefinition(reader);
                    }
                }

                using (System.IO.TextReader reader = System.IO.File.OpenText(report))
                {
                    // rv.LocalReport.LoadReportDefinition(reader);
                }

            }
        }
示例#30
0
文件: Program.cs 项目: Droid108/TTop
 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();
 }
        public JsonResult SaveExcelData()
        {
            var    reader     = new System.IO.StreamReader(HttpContext.Request.InputStream);
            string data       = reader.ReadToEnd();
            var    tempdata   = JsonConvert.DeserializeObject <Dictionary <string, string> >(data);
            var    list       = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(tempdata["data"]);
            var    BidOfferID = this.Request["BidOfferID"];
            var    bid        = this.GetEntityByID <S_M_BidOffer>(BidOfferID);

            if (bid == null)
            {
                throw new Formula.Exceptions.BusinessValidationException("没有找到投标报价记录,无法导入EXCEL");
            }
            var deviceRoot = bid.S_M_BidOffer_CBS.Where(d => d.CBSType == "Device").OrderBy(d => d.CBSFullID).FirstOrDefault();

            if (deviceRoot == null)
            {
                throw new Formula.Exceptions.BusinessValidationException("没有找到投标报价记录中的设备费用节点,无法导入!");
            }
            var BOMMajor = EnumBaseHelper.GetEnumDef("Base.BOMMajor");

            if (BOMMajor == null)
            {
                throw new Formula.Exceptions.BusinessValidationException("没有找到对应的采购专业分类枚举【Base.BOMMajor】");
            }
            var enumItems = BOMMajor.EnumItem.ToList();

            if (deviceRoot.CBSTemplateNode == null)
            {
                throw new Formula.Exceptions.BusinessValidationException("没有找到设备材料费用的定义科目信息,导入失败");
            }
            var deviceTemplate = deviceRoot.CBSTemplateNode;
            var structDic      = new Dictionary <string, S_M_BidOffer_CBS>();

            structDic.SetValue(deviceTemplate.ID, deviceRoot);
            S_M_BidOffer_CBS lastParent = null;

            for (int i = 0; i < list.Count; i++)
            {
                var item     = list[i];
                var nodeType = getNodeType(item);
                if (nodeType != "Detail")
                {
                    var templateNode = deviceTemplate.AllChildren.FirstOrDefault(c => c.NodeType == nodeType);
                    if (templateNode == null)
                    {
                        continue;
                    }
                    if (templateNode.Parent == null)
                    {
                        continue;
                    }
                    lastParent = structDic.GetValue(templateNode.Parent.ID);
                    if (lastParent == null || lastParent.CBSTemplateNode == null)
                    {
                        continue;
                    }
                    var childTemplateNode = lastParent.CBSTemplateNode.Children.FirstOrDefault(c => c.NodeType == nodeType);
                    if (childTemplateNode == null)
                    {
                        continue;
                    }
                    var name      = item.GetValue("Name");
                    var childNode = new S_M_BidOffer_CBS();
                    this.UpdateEntity <S_M_BidOffer_CBS>(childNode, item);
                    childNode.ID          = FormulaHelper.CreateGuid();
                    childNode.NodeType    = nodeType;
                    childNode.CBSDefineID = childTemplateNode.ID;
                    lastParent.AddChild(childNode);
                    structDic.SetValue(childTemplateNode.ID, childNode);
                }
                else
                {
                    var templateNode = deviceTemplate.AllChildren.LastOrDefault();
                    if (templateNode == null)
                    {
                        continue;
                    }
                    var cbsNode = structDic.GetValue(templateNode.ID);
                    if (cbsNode == null)
                    {
                        continue;
                    }
                    var majorName = item.GetValue("MajorName");
                    var codeItem  = enumItems.FirstOrDefault(c => c.Name == majorName);
                    if (codeItem == null)
                    {
                        throw new Formula.Exceptions.BusinessValidationException("没有找到对应的专业内容【" + majorName + "】");
                    }
                    var majorCode = codeItem.Code;
                    item.SetValue("MajorCode", majorCode);
                    var detail = new S_M_BidOffer_CBS_Detail();
                    FormulaHelper.UpdateEntity <S_M_BidOffer_CBS_Detail>(detail, item);
                    detail.BidOfferID     = bid.ID;
                    detail.ID             = FormulaHelper.CreateGuid();
                    detail.CBSParentID    = cbsNode.CBSID;
                    detail.BomID          = FormulaHelper.CreateGuid();
                    detail.OfferCBSFullID = cbsNode.CBSFullID;
                    detail.OfferCBSID     = cbsNode.ID;
                    detail.FullID         = detail.ID;
                    detail.SortIndex      = i;
                    cbsNode.S_M_BidOffer_CBS_Detail.Add(detail);
                }
            }
            this.EPCEntites.SaveChanges();
            return(Json("Success"));
        }
示例#32
0
        private static void archiveDirectoryTest()
        {
            //Create sample file (text)
            string RootPath     = System.IO.Path.GetTempPath();
            string TestFilePath = RootPath + System.IO.Path.DirectorySeparatorChar + "zipFolder2";

            if (System.IO.Directory.Exists(TestFilePath) == false)
            {
                System.IO.Directory.CreateDirectory(TestFilePath);
            }
            string TestFile1Name     = "zipTest1.txt";
            string TestFile1FullPath = TestFilePath + System.IO.Path.DirectorySeparatorChar + TestFile1Name;

            if (System.IO.File.Exists(TestFile1FullPath))
            {
                System.IO.File.Delete(TestFile1FullPath);
            }
            string TestFile2Name     = "zipTest2.txt";
            string TestFile2FullPath = TestFilePath + System.IO.Path.DirectorySeparatorChar + TestFile2Name;

            if (System.IO.File.Exists(TestFile2FullPath))
            {
                System.IO.File.Delete(TestFile2FullPath);
            }

            string TestFileSubPath = TestFilePath + System.IO.Path.DirectorySeparatorChar + "zipSubFolder";

            if (System.IO.Directory.Exists(TestFileSubPath) == false)
            {
                System.IO.Directory.CreateDirectory(TestFileSubPath);
            }
            string TestFile3Name     = "zipTest3.txt";
            string TestFile3FullPath = TestFileSubPath + System.IO.Path.DirectorySeparatorChar + TestFile3Name;

            if (System.IO.File.Exists(TestFile3FullPath))
            {
                System.IO.File.Delete(TestFile3FullPath);
            }

            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(TestFile1FullPath))
            {
                writer.WriteLine("TEST Data aabcdfkdfaa");
                writer.WriteLine("1234566");
                writer.Flush();
            }
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(TestFile2FullPath))
            {
                writer.WriteLine("TEST Data a22343afda");
                writer.WriteLine("1234566");
                writer.Flush();
            }
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(TestFile3FullPath))
            {
                writer.WriteLine("TEST Data 322343afda");
                writer.WriteLine("1234566");
                writer.Flush();
            }
            List <string> OriginalContents = new List <string>();

            using (System.IO.StreamReader reader = new System.IO.StreamReader(TestFile1FullPath))
            {
                OriginalContents.Add(reader.ReadToEnd());
            }
            using (System.IO.StreamReader reader = new System.IO.StreamReader(TestFile2FullPath))
            {
                OriginalContents.Add(reader.ReadToEnd());
            }
            using (System.IO.StreamReader reader = new System.IO.StreamReader(TestFile3FullPath))
            {
                OriginalContents.Add(reader.ReadToEnd());
            }

            string ZipFilename = System.IO.Path.GetTempPath() + "ZipFolderTest.zip";

            if (System.IO.File.Exists(ZipFilename))
            {
                System.IO.File.Delete(ZipFilename);
            }
            //Create zip file from this sample file
            Models.FileTransportInfo transport = new Models.FileTransportInfo(RootPath, "zipFolder2", null, null, null);
            Gyomu.Common.Archive.ZipArchive.Create(ZipFilename, new List <Models.FileTransportInfo>()
            {
                transport
            });

            using (Gyomu.Common.Archive.ZipArchive archive = new Gyomu.Common.Archive.ZipArchive(ZipFilename))
            {
                List <string> entryNames = archive.GetEntryFileNamesFromDirectory(transport);
                foreach (string entryName in entryNames)
                {
                    System.IO.Stream stream = archive.GetEntryFileFromName(entryName);
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
                        Assert.Contains(reader.ReadToEnd(), OriginalContents);
                }
            }
            //System.IO.File.Delete(TestFile1FullPath);
            //System.IO.File.Delete(ZipFilename);
        }
示例#33
0
        static void Main(string[] args)
        {
            System.IO.StreamReader TempFile = new System.IO.StreamReader("../../tests.txt");
            string Data = TempFile.ReadToEnd();

            TempFile.Close();

            int    x     = 1;
            JArray Tests = JsonConvert.DeserializeObject <JArray>(Data);

            foreach (JObject Test in Tests)
            {
                Console.WriteLine("Test #" + x + ":  " + Test["comment"]);

                System.IO.StreamWriter TempFile2 = null;
                if (Test["check_records"] != null)
                {
                    TempFile2 = new System.IO.StreamWriter("../../out.jb64");
                }

                // Test the encoder.
                bool              Passed  = true;
                JB64Encode        Encode  = new JB64Encode();
                List <JB64Header> Headers = new List <JB64Header>();
                if (Test["headers"] != null)
                {
                    Passed = true;
                    foreach (JArray Header in Test["headers"])
                    {
                        try
                        {
                            Headers.Add(new JB64Header((string)Header[0], (string)Header[1]));
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            Passed = false;
                        }
                    }

                    if (Passed)
                    {
                        try
                        {
                            string Line = Encode.EncodeHeaders(Headers);

                            if (Test["check_records"] != null)
                            {
                                TempFile2.Write(Line);
                            }
                        }
                        catch (JB64Exception)
                        {
                            Passed = false;
                        }
                    }

                    if (Passed == (bool)Test["header_result"])
                    {
                        Console.WriteLine("[PASS] Processed headers as expected.");
                    }
                    else
                    {
                        Console.WriteLine("[FAIL] Header processing returned the wrong result.");
                    }
                }

                if (Test["data"] != null)
                {
                    int x2 = 0;
                    foreach (JToken Row in Test["data"])
                    {
                        List <JB64Value> Values = new List <JB64Value>();
                        Passed = true;
                        foreach (JToken Col in Row)
                        {
                            JToken Col2 = Col;
                            if (Col2.Type == JTokenType.Property)
                            {
                                Col2 = ((JProperty)Col2).Value;
                            }

                            if (Col2.Type == JTokenType.Null)
                            {
                                Values.Add(new JB64Value());
                            }
                            else if (Col2.Type == JTokenType.Boolean)
                            {
                                Values.Add(new JB64Value((bool)Col2));
                            }
                            else if (Col2.Type == JTokenType.Integer)
                            {
                                Values.Add(new JB64Value((int)Col2));
                            }
                            else if (Col2.Type == JTokenType.Float)
                            {
                                Values.Add(new JB64Value((double)Col2));
                            }
                            else if (Col2.Type == JTokenType.String)
                            {
                                Values.Add(new JB64Value((string)Col2));
                            }
                            else
                            {
                                Passed = false;
                            }
                        }

                        if (Passed)
                        {
                            try
                            {
                                string Line = Encode.EncodeRecord(Values.ToArray());

                                if (Test["check_records"] != null)
                                {
                                    TempFile2.Write(Line);
                                }
                            }
                            catch (JB64Exception)
                            {
                                Passed = false;
                            }

                            if (Passed == (bool)((JArray)Test["data_results"])[x2])
                            {
                                Console.WriteLine("[PASS] EncodeRecord() for record #" + (x2 + 1) + " returned expected result.");
                            }
                            else
                            {
                                Console.WriteLine("[FAIL] EncodeRecord() for record #" + (x2 + 1) + " returned unexpected result.");
                            }
                        }
                        else
                        {
                            Console.WriteLine("[FAIL] Unexpected column type in test.");
                        }

                        x2++;
                    }
                }

                if (Test["check_records"] != null)
                {
                    TempFile2.Close();

                    // Test the decoder.
                    TempFile = new System.IO.StreamReader("../../out.jb64");
                    JB64Decode Decode = new JB64Decode();
                    string     Line   = TempFile.ReadLine();
                    try
                    {
                        List <JB64Header> Headers2 = Decode.DecodeHeaders(Line);

                        Console.WriteLine("[PASS] DecodeHeaders() succeeded.");

                        Passed = (Headers.Count == Headers2.Count);
                        if (Passed)
                        {
                            int x2;
                            for (x2 = 0; x2 < Headers.Count && Headers[x2].Name == Headers2[x2].Name && Headers[x2].Type == Headers2[x2].Type; x2++)
                            {
                            }

                            Passed = (x2 == Headers.Count);
                        }

                        if (Passed)
                        {
                            Console.WriteLine("[PASS] DecodeHeaders() returned expected result.");

                            if (Test["header_map"] != null)
                            {
                                try
                                {
                                    List <JB64HeaderMap> TempMap = new List <JB64HeaderMap>();
                                    foreach (JArray Col in Test["header_map"])
                                    {
                                        TempMap.Add(new JB64HeaderMap((string)Col[0], (string)Col[1], (bool)Col[2]));
                                    }
                                    Decode.SetHeaderMap(TempMap);

                                    Console.WriteLine("[PASS] SetHeaderMap() succeeded.");
                                }
                                catch (JB64Exception)
                                {
                                    Console.WriteLine("[FAIL] SetHeaderMap() failed.");
                                }
                            }

                            foreach (JArray Row in Test["check_records"])
                            {
                                Line = TempFile.ReadLine();
                                try
                                {
                                    JB64Value[] Result = Decode.DecodeRecord(Line);

                                    Console.WriteLine("[PASS] DecodeRecord() succeeded.");

                                    // Convert checking row to something easier to test.
                                    List <JB64Value> Values = new List <JB64Value>();
                                    Passed = true;
                                    foreach (JToken Col in Row)
                                    {
                                        JToken Col2 = Col;
                                        if (Col2.Type == JTokenType.Property)
                                        {
                                            Col2 = ((JProperty)Col2).Value;
                                        }

                                        if (Col2.Type == JTokenType.Null)
                                        {
                                            Values.Add(new JB64Value());
                                        }
                                        else if (Col2.Type == JTokenType.Boolean)
                                        {
                                            Values.Add(new JB64Value((bool)Col2));
                                        }
                                        else if (Col2.Type == JTokenType.Integer)
                                        {
                                            Values.Add(new JB64Value((int)Col2));
                                        }
                                        else if (Col2.Type == JTokenType.Float)
                                        {
                                            Values.Add(new JB64Value((double)Col2));
                                        }
                                        else if (Col2.Type == JTokenType.String)
                                        {
                                            Values.Add(new JB64Value((string)Col2));
                                        }
                                    }

                                    Passed = (Result.Length == Values.Count);
                                    if (Passed)
                                    {
                                        int x2;
                                        for (x2 = 0; x2 < Result.Length; x2++)
                                        {
                                            Values[x2].ConvertTo(Result[x2].Type);

                                            if (!Values[x2].Equals(Result[x2]))
                                            {
                                                Passed = false;
                                            }
                                        }
                                    }

                                    if (Passed)
                                    {
                                        Console.WriteLine("[PASS] DecodeRecord() returned matching record data.");
                                    }
                                    else
                                    {
                                        Console.WriteLine("[FAIL] DecodeRecord() returned record data that does not match.");
                                    }
                                }
                                catch (JB64Exception)
                                {
                                    Console.WriteLine("[FAIL] DecodeRecord() failed.");
                                }
                            }

                            Line = TempFile.ReadLine();
                            if (Line == null || Line == "")
                            {
                                Console.WriteLine("[PASS] File contained the correct amount of data.");
                            }
                            else
                            {
                                Console.WriteLine("[FAIL] File contained more data than expected.");
                            }
                        }
                        else
                        {
                            Console.WriteLine("[PASS] DecodeHeaders() returned unexpected result.");
                        }
                    }
                    catch (JB64Exception e)
                    {
                        Console.WriteLine("[FAIL] DecodeHeaders() failed (" + e.Message + ").");
                    }

                    TempFile.Close();
                }

                Console.WriteLine();
                x++;
            }

            Console.ReadKey();
        }
        private FR_Base Load(DbConnection Connection, DbTransaction Transaction, Guid ObjectID, string ConnectionString)
        {
            //Standard return type
            FR_Base retStatus = new FR_Base();

            bool cleanupConnection  = false;
            bool cleanupTransaction = false;

            try
            {
                #region Verify/Create Connections
                //Create connection if Connection is null
                if (Connection == null)
                {
                    cleanupConnection = true;
                    Connection        = CSV2Core_MySQL.Support.DBSQLSupport.CreateConnection(ConnectionString);
                    Connection.Open();
                }
                //If transaction is not open/not valid
                if (Transaction == null)
                {
                    cleanupTransaction = true;
                    Transaction        = Connection.BeginTransaction();
                }
                #endregion
                //Get the SelectQuerry
                string SelectQuery = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("CL1_HEC.HEC_Patient_UniversalPropertyValue.SQL.Select.sql")).ReadToEnd();

                DbCommand command = Connection.CreateCommand();
                //Set Connection/Transaction
                command.Connection  = Connection;
                command.Transaction = Transaction;
                //Set Query/Timeout
                command.CommandText    = SelectQuery;
                command.CommandTimeout = QueryTimeout;

                //Firstly, before loading, set the GUID to empty
                //So the entity does not exist, it will have a GUID set to empty
                _HEC_Patient_UniversalPropertyValueID = Guid.Empty;
                CSV2Core_MySQL.Support.DBSQLSupport.SetParameter(command, "HEC_Patient_UniversalPropertyValueID", ObjectID);

                #region Command Execution
                try
                {
                    var loader = new CSV2Core_MySQL.Dictionaries.MultiTable.Loader.DictionaryLoader(Connection, Transaction);
                    var reader = new CSV2Core_MySQL.Support.DBSQLReader(command.ExecuteReader());
                    reader.SetOrdinals(new string[] { "HEC_Patient_UniversalPropertyValueID", "HEC_Patient_RefID", "HEC_Patient_UniversalProperty_RefID", "Value_String", "Value_Number", "Value_Boolean", "Creation_Timestamp", "Tenant_RefID", "IsDeleted", "Modification_Timestamp" });
                    if (reader.HasRows == true)
                    {
                        reader.Read();                         //Single result only
                        //0:Parameter HEC_Patient_UniversalPropertyValueID of type Guid
                        _HEC_Patient_UniversalPropertyValueID = reader.GetGuid(0);
                        //1:Parameter HEC_Patient_RefID of type Guid
                        _HEC_Patient_RefID = reader.GetGuid(1);
                        //2:Parameter HEC_Patient_UniversalProperty_RefID of type Guid
                        _HEC_Patient_UniversalProperty_RefID = reader.GetGuid(2);
                        //3:Parameter Value_String of type String
                        _Value_String = reader.GetString(3);
                        //4:Parameter Value_Number of type double
                        _Value_Number = reader.GetDouble(4);
                        //5:Parameter Value_Boolean of type Boolean
                        _Value_Boolean = reader.GetBoolean(5);
                        //6:Parameter Creation_Timestamp of type DateTime
                        _Creation_Timestamp = reader.GetDate(6);
                        //7:Parameter Tenant_RefID of type Guid
                        _Tenant_RefID = reader.GetGuid(7);
                        //8:Parameter IsDeleted of type Boolean
                        _IsDeleted = reader.GetBoolean(8);
                        //9:Parameter Modification_Timestamp of type DateTime
                        _Modification_Timestamp = reader.GetDate(9);
                    }
                    //Close the reader so other connections can use it
                    reader.Close();

                    loader.Load();

                    if (_HEC_Patient_UniversalPropertyValueID != Guid.Empty)
                    {
                        //Successfully loaded
                        Status_IsAlreadySaved = true;
                        Status_IsDirty        = false;
                    }
                    else
                    {
                        //Fault in loading due to invalid UUID (Guid)
                        Status_IsAlreadySaved = false;
                        Status_IsDirty        = false;
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
                #endregion

                #region Cleanup Transaction/Connection
                //If we started the transaction, we will commit it
                if (cleanupTransaction && Transaction != null)
                {
                    Transaction.Commit();
                }

                //If we opened the connection we will close it
                if (cleanupConnection && Connection != null)
                {
                    Connection.Close();
                }

                #endregion
            } catch (Exception ex) {
                try
                {
                    if (cleanupTransaction == true && Transaction != null)
                    {
                        Transaction.Rollback();
                    }
                }
                catch { }

                try
                {
                    if (cleanupConnection == true && Connection != null)
                    {
                        Connection.Close();
                    }
                }
                catch { }

                throw;
            }

            return(retStatus);
        }
        protected FR_Base Save(DbConnection Connection, DbTransaction Transaction, string ConnectionString)
        {
            //Standard return type
            FR_Base retStatus = new FR_Base();

            bool cleanupConnection  = false;
            bool cleanupTransaction = false;

            try
            {
                bool saveDictionary = false;
                bool saveORMClass   = !Status_IsAlreadySaved || Status_IsDirty;


                //If Status Is Dirty (Meaning the data has been changed) or Status_IsAlreadySaved (Meaning the data is in the database, when loaded) just return
                if (saveORMClass == false && saveDictionary == false)
                {
                    return(FR_Base.Status_OK);
                }


                #region Verify/Create Connections
                //Create Connection if Connection is null
                if (Connection == null)
                {
                    cleanupConnection = true;
                    Connection        = CSV2Core_MySQL.Support.DBSQLSupport.CreateConnection(ConnectionString);
                    Connection.Open();
                }

                //Create Transaction if null
                if (Transaction == null)
                {
                    cleanupTransaction = true;
                    Transaction        = Connection.BeginTransaction();
                }

                #endregion

                #region Dictionary Management

                //Save dictionary management
                if (saveDictionary == true)
                {
                    var loader = new CSV2Core_MySQL.Dictionaries.MultiTable.Loader.DictionaryLoader(Connection, Transaction);
                    //Save the dictionary or update based on if it has already been saved to the database
                    if (Status_IsAlreadySaved)
                    {
                        loader.Update();
                    }
                    else
                    {
                        loader.Save();
                    }
                }
                #endregion

                #region Command Execution
                if (saveORMClass == true)
                {
                    //Retrieve Querry
                    string Query = "";

                    if (Status_IsAlreadySaved == true)
                    {
                        Query = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("CL1_HEC.HEC_Patient_UniversalPropertyValue.SQL.Update.sql")).ReadToEnd();
                    }
                    else
                    {
                        Query = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("CL1_HEC.HEC_Patient_UniversalPropertyValue.SQL.Insert.sql")).ReadToEnd();
                    }

                    DbCommand command = Connection.CreateCommand();
                    command.Connection     = Connection;
                    command.Transaction    = Transaction;
                    command.CommandText    = Query;
                    command.CommandTimeout = QueryTimeout;

                    CSV2Core_MySQL.Support.DBSQLSupport.SetParameter(command, "HEC_Patient_UniversalPropertyValueID", _HEC_Patient_UniversalPropertyValueID);
                    CSV2Core_MySQL.Support.DBSQLSupport.SetParameter(command, "HEC_Patient_RefID", _HEC_Patient_RefID);
                    CSV2Core_MySQL.Support.DBSQLSupport.SetParameter(command, "HEC_Patient_UniversalProperty_RefID", _HEC_Patient_UniversalProperty_RefID);
                    CSV2Core_MySQL.Support.DBSQLSupport.SetParameter(command, "Value_String", _Value_String);
                    CSV2Core_MySQL.Support.DBSQLSupport.SetParameter(command, "Value_Number", _Value_Number);
                    CSV2Core_MySQL.Support.DBSQLSupport.SetParameter(command, "Value_Boolean", _Value_Boolean);
                    CSV2Core_MySQL.Support.DBSQLSupport.SetParameter(command, "Creation_Timestamp", _Creation_Timestamp);
                    CSV2Core_MySQL.Support.DBSQLSupport.SetParameter(command, "Tenant_RefID", _Tenant_RefID);
                    CSV2Core_MySQL.Support.DBSQLSupport.SetParameter(command, "IsDeleted", _IsDeleted);
                    CSV2Core_MySQL.Support.DBSQLSupport.SetParameter(command, "Modification_Timestamp", _Modification_Timestamp);


                    try
                    {
                        var dbChangeCount = command.ExecuteNonQuery();
                        Status_IsAlreadySaved = true;
                        Status_IsDirty        = false;
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                    #endregion

                    #region Cleanup Transaction/Connection
                    //If we started the transaction, we will commit it
                    if (cleanupTransaction && Transaction != null)
                    {
                        Transaction.Commit();
                    }

                    //If we opened the connection we will close it
                    if (cleanupConnection && Connection != null)
                    {
                        Connection.Close();
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                try
                {
                    if (cleanupTransaction == true && Transaction != null)
                    {
                        Transaction.Rollback();
                    }
                }
                catch { }

                try
                {
                    if (cleanupConnection == true && Connection != null)
                    {
                        Connection.Close();
                    }
                }
                catch { }

                throw;
            }

            return(retStatus);
        }
示例#36
0
        /// <summary>
        /// Constructs exception composing details from response, method specific error description and actual inner exception
        /// </summary>
        /// <param name="response">Response of failed request</param>
        /// <param name="stripeErrorMessage">Method specific error description</param>
        /// <param name="inner">Actual inner exception</param>
        /// <returns>Composed exception</returns>
        public static PaymentStripeException Compose(HttpWebResponse response, string stripeErrorMessage, Exception inner)
        {
            int statusCode = (int)response.StatusCode;

            string responseErrMsg = string.Empty;

            try
            {
                using (var reponseStream = response.GetResponseStream())
                {
                    using (var responseReader = new System.IO.StreamReader(reponseStream))
                    {
                        string  responseStr = responseReader.ReadToEnd();
                        dynamic responseObj = responseStr.JSONToDynamic();
                        responseErrMsg = responseObj.error.message;
                    }
                }
            }
            catch (Exception)
            {
                // dlatushkin 2014/04/07:
                // there is no way to test some cases (50X errors for example)
                // so try/catch is used to swallow exception
            }

            string specificError = System.Environment.NewLine;

            if (responseErrMsg.IsNotNullOrWhiteSpace())
            {
                specificError += StringConsts.PAYMENT_STRIPE_ERR_MSG_ERROR.Args(responseErrMsg) + System.Environment.NewLine;
            }

            specificError += stripeErrorMessage;

            PaymentStripeException ex = null;

            if (statusCode == 400)
            {
                ex = new PaymentStripeException(StringConsts.PAYMENT_STRIPE_400_ERROR + specificError, inner);
            }

            if (statusCode == 401)
            {
                ex = new PaymentStripeException(StringConsts.PAYMENT_STRIPE_401_ERROR + specificError, inner);
            }

            if (statusCode == 402)
            {
                ex = new PaymentStripeException(StringConsts.PAYMENT_STRIPE_402_ERROR + specificError, inner);
            }

            if (statusCode == 404)
            {
                ex = new PaymentStripeException(StringConsts.PAYMENT_STRIPE_404_ERROR + specificError, inner);
            }

            if (statusCode == 500 || statusCode == 502 || statusCode == 503 || statusCode == 504)
            {
                ex = new PaymentStripeException(StringConsts.PAYMENT_STRIPE_50X_ERROR.Args(statusCode) + specificError, inner);
            }

            return(ex);
        }
示例#37
0
        static void Main(string[] args)
        {
            bool   postolDefined        = false;
            bool   slopetolDefined      = false;
            bool   mapsizeDefined       = false;
            bool   maxposoffsetDefined  = false;
            bool   minmatchesDefined    = false;
            bool   quickDefined         = false;
            bool   inputrefFileDefined  = false;
            bool   inputaddFileDefined  = false;
            bool   outputFileDefined    = false;
            bool   refdatasetDefined    = false;
            bool   adddatasetDefined    = false;
            bool   filterdatasetDefined = false;
            bool   inputConfigDefined   = false;
            bool   logfileDefined       = false;
            bool   filterDefined        = false;
            bool   refbrickDefined      = false;
            bool   addbrickDefined      = false;
            string FilterText           = "";
            string RefFileIn            = "";
            string AddFileIn            = "";
            string OutFile           = "";
            string RefDataSetName    = "";
            string AddDataSetName    = "";
            string FilterDataSetName = "";
            string ConfigFile        = "";
            string LogFile           = null;
            long   RefBrick          = 0;
            long   AddBrick          = 0;

            SySal.Processing.MapMerge.MapMerger             MM     = new SySal.Processing.MapMerge.MapMerger();
            SySal.Processing.MapMerge.Configuration         C      = (SySal.Processing.MapMerge.Configuration)MM.Config;
            SySal.Processing.MapMerge.MapManager.dMapFilter Filter = null;
            try
            {
                int argnum;
                for (argnum = 0; argnum < args.Length; argnum++)
                {
                    switch (args[argnum].ToLower())
                    {
                    case swEditConfig:
                    {
                        System.Windows.Forms.Application.EnableVisualStyles();
                        System.Xml.Serialization.XmlSerializer xmls2 = new System.Xml.Serialization.XmlSerializer(typeof(SySal.Processing.MapMerge.Configuration));
                        try
                        {
                            C = (SySal.Processing.MapMerge.Configuration)xmls2.Deserialize(new System.IO.StringReader(System.IO.File.ReadAllText(args[argnum + 1])));
                        }
                        catch (Exception) { };
                        SySal.Processing.MapMerge.EditConfigForm ec = new SySal.Processing.MapMerge.EditConfigForm();
                        ec.C = C;
                        if (ec.ShowDialog() == DialogResult.OK)
                        {
                            System.IO.StringWriter w = new System.IO.StringWriter();
                            xmls2.Serialize(w, C);
                            System.IO.File.WriteAllText(args[argnum + 1], w.ToString());
                        }
                        return;
                    }

                    case swPosTol:
                    {
                        postolDefined = true;
                        C.PosTol      = System.Convert.ToDouble(args[argnum + 1], System.Globalization.CultureInfo.InvariantCulture);
                        argnum++;
                        break;
                    }

                    case swSlopeTol:
                    {
                        slopetolDefined = true;
                        C.SlopeTol      = System.Convert.ToDouble(args[argnum + 1], System.Globalization.CultureInfo.InvariantCulture);
                        argnum++;
                        break;
                    }

                    case swMaxOffset:
                    {
                        maxposoffsetDefined = true;
                        C.MaxPosOffset      = System.Convert.ToDouble(args[argnum + 1], System.Globalization.CultureInfo.InvariantCulture);
                        argnum++;
                        break;
                    }

                    case swMapSize:
                    {
                        mapsizeDefined = true;
                        C.MapSize      = System.Convert.ToDouble(args[argnum + 1], System.Globalization.CultureInfo.InvariantCulture);
                        argnum++;
                        break;
                    }

                    case swMinMatches:
                    {
                        minmatchesDefined = true;
                        C.MinMatches      = System.Convert.ToInt32(args[argnum + 1], System.Globalization.CultureInfo.InvariantCulture);
                        argnum++;
                        break;
                    }

                    case swQuick:
                    {
                        quickDefined = true;
                        break;
                    }

                    case swFilter:
                    {
                        filterDefined = true;
                        FilterText    = args[argnum + 1];
                        argnum++;
                        break;
                    }

                    case swRefInput:
                    {
                        inputrefFileDefined = true;
                        RefFileIn           = args[argnum + 1];
                        argnum++;
                        break;
                    }

                    case swAddInput:
                    {
                        inputaddFileDefined = true;
                        AddFileIn           = args[argnum + 1];
                        argnum++;
                        break;
                    }

                    case swOutput:
                    {
                        outputFileDefined = true;
                        OutFile           = args[argnum + 1];
                        argnum++;
                        break;
                    }

                    case swConfig:
                    {
                        inputConfigDefined = true;
                        ConfigFile         = args[argnum + 1];
                        argnum++;
                        break;
                    }

                    case swRefDataSet:
                    {
                        refdatasetDefined = true;
                        RefDataSetName    = args[argnum + 1];
                        argnum++;
                        break;
                    }

                    case swAddDataSet:
                    {
                        adddatasetDefined = true;
                        AddDataSetName    = args[argnum + 1];
                        argnum++;
                        break;
                    }

                    case swFilterDataSet:
                    {
                        filterdatasetDefined = true;
                        FilterDataSetName    = args[argnum + 1];
                        argnum++;
                        break;
                    }

                    case swLog:
                    {
                        logfileDefined = true;
                        LogFile        = args[argnum + 1];
                        argnum++;
                        break;
                    }

                    case swRefBrick:
                    {
                        refbrickDefined = true;
                        RefBrick        = System.Convert.ToInt64(args[argnum + 1], System.Globalization.CultureInfo.InvariantCulture);
                        argnum++;
                        break;
                    }

                    case swAddBrick:
                    {
                        addbrickDefined = true;
                        AddBrick        = System.Convert.ToInt64(args[argnum + 1], System.Globalization.CultureInfo.InvariantCulture);
                        argnum++;
                        break;
                    }

                    default: throw new Exception("Unsupported switch: \"" + args[argnum] + "\".");
                    }
                }
                if (quickDefined)
                {
                    C.FavorSpeedOverAccuracy = true;
                }
                if (filterDefined)
                {
                    Filter = new SySal.Processing.MapMerge.MapManager.dMapFilter(new ObjFilter(SegmentFilterFunctions, FilterText).Value);
                }
                if (inputConfigDefined)
                {
                    System.Xml.Serialization.XmlSerializer xmls1 = new System.Xml.Serialization.XmlSerializer(typeof(SySal.Processing.MapMerge.Configuration));
                    System.IO.StreamReader r1 = new System.IO.StreamReader(ConfigFile);
                    C = (SySal.Processing.MapMerge.Configuration)xmls1.Deserialize(r1);
                    r1.Close();
                }
                if (inputrefFileDefined == false)
                {
                    throw new Exception("Reference volume must be defined.");
                }
                if (refdatasetDefined == false)
                {
                    RefDataSetName = "TSR";
                }
                if (inputaddFileDefined == false)
                {
                    throw new Exception("Please define the volume to be imported.");
                }
                if (adddatasetDefined == false)
                {
                    throw new Exception("Please define the dataset name to assign to imported data.");
                }
                if (outputFileDefined == false)
                {
                    throw new Exception("The output file must be defined.");
                }
            }
            catch (Exception x)
            {
                Console.WriteLine("Usage: MapMerge.exe {parameters}");
                Console.WriteLine("parameters");
                Console.WriteLine(swPosTol + " -> position tolerance (optional).");
                Console.WriteLine(swSlopeTol + " -> slope tolerance (optional).");
                Console.WriteLine(swMapSize + " -> map size (optional).");
                Console.WriteLine(swMaxOffset + " -> maximum position offset (optional).");
                Console.WriteLine(swMinMatches + " -> minimum number of matches per map (optional).");
                Console.WriteLine(swQuick + " -> favor speed over accuracy (optional).");
                Console.WriteLine(swRefInput + " -> reference volume.");
                Console.WriteLine(swRefDataSet + " -> dataset name to assign to reference data (default is \"TSR\").");
                Console.WriteLine(swRefBrick + " -> reset reference brick to specified brick number.");
                Console.WriteLine(swAddInput + " -> volume to import.");
                Console.WriteLine(swAddDataSet + " -> dataset name to assign to imported data.");
                Console.WriteLine(swFilterDataSet + " -> dataset name to filter imported data (leave blank for no filter).");
                Console.WriteLine(swAddBrick + " -> reset brick to assign to imported data.");
                Console.WriteLine(swOutput + " -> output file name.");
                Console.WriteLine(swLog + " -> log file (optional) - use \"con\" for console output.");
                Console.WriteLine(swConfig + " -> configuration file (optional).");
                Console.WriteLine(swFilter + " -> selection function for track matching (optional).");
                Console.WriteLine();
                Console.WriteLine("Variables that can be used for track filtering:");
                foreach (FilterF ff in SegmentFilterFunctions)
                {
                    Console.WriteLine(ff.Name + " -> " + ff.HelpText);
                }
                Console.WriteLine();
                Console.WriteLine(x.ToString());
                return;
            }
            System.IO.TextWriter logw = null;
            if (logfileDefined)
            {
                if (String.Compare(LogFile.Trim(), "con", true) == 0)
                {
                    logw = Console.Out;
                }
                else
                {
                    logw = new System.IO.StreamWriter(LogFile);
                }
            }
            MM.Config = C;
            SySal.TotalScan.NamedAttributeIndex.RegisterFactory();
            SySal.TotalScan.BaseTrackIndex.RegisterFactory();
            SySal.TotalScan.MIPMicroTrackIndex.RegisterFactory();
            SySal.OperaDb.TotalScan.DBMIPMicroTrackIndex.RegisterFactory();
            SySal.OperaDb.TotalScan.DBNamedAttributeIndex.RegisterFactory();
            SySal.TotalScan.Flexi.Volume  refv = new SySal.TotalScan.Flexi.Volume();
            SySal.TotalScan.Flexi.DataSet rds  = new SySal.TotalScan.Flexi.DataSet();
            rds.DataId   = RefBrick;
            rds.DataType = RefDataSetName;
            refv.ImportVolume(rds, (SySal.TotalScan.Volume)SySal.OperaPersistence.Restore(RefFileIn, typeof(SySal.TotalScan.Volume)));
            if (RefBrick > 0)
            {
                int n = refv.Layers.Length;
                int i;
                for (i = 0; i < n; i++)
                {
                    if (refv.Layers[i].BrickId == 0)
                    {
                        ((SySal.TotalScan.Flexi.Layer)refv.Layers[i]).SetBrickId(RefBrick);
                    }
                }
            }
            SySal.TotalScan.Flexi.DataSet ads = new SySal.TotalScan.Flexi.DataSet();
            ads.DataId   = AddBrick;
            ads.DataType = AddDataSetName;
            SySal.TotalScan.Flexi.DataSet fds = new SySal.TotalScan.Flexi.DataSet();
            if (FilterDataSetName.Length > 0)
            {
                fds.DataId   = AddBrick;
                fds.DataType = FilterDataSetName.Trim();
            }
            else
            {
                fds = null;
            }
            SySal.TotalScan.Flexi.Volume addv = new SySal.TotalScan.Flexi.Volume();
            addv.ImportVolume(ads, (SySal.TotalScan.Volume)SySal.OperaPersistence.Restore(AddFileIn, typeof(SySal.TotalScan.Volume)), fds);
            if (AddBrick > 0)
            {
                int n = addv.Layers.Length;
                int i;
                for (i = 0; i < n; i++)
                {
                    if (addv.Layers[1].BrickId == 0)
                    {
                        ((SySal.TotalScan.Flexi.Layer)addv.Layers[i]).SetBrickId(AddBrick);
                    }
                }
            }
            MM.AddToVolume(refv, addv, ads, null, Filter, logw);
            if (logw != null && logw != Console.Out)
            {
                logw.Flush();
                logw.Close();
                logw = null;
            }
            Console.WriteLine("Result written to " + SySal.OperaPersistence.Persist(OutFile, refv));
        }
示例#38
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //Session["PatientInformation"]
            //Session["PatientSex"] = "Female";
            //Session["PatientAge"] = "12";
            int PatientId  = 0;
            int visitPK    = 0;
            int locationId = 0;
            int userId     = 0;

            if (!IsPostBack)
            {
                if (Session["AppLocation"] == null || Session.Count == 0 || Session["AppUserID"].ToString() == "")
                {
                    Response.Redirect("~/frmlogin.aspx", true);
                }

                if (!object.Equals(Session["PatientId"], null))
                {
                    PatientId = Convert.ToInt32(Session["PatientId"]);
                    if (PatientId == 0)
                    {
                        Response.Redirect("~/ClinicalForms/frmPatient_Home.aspx", true);
                    }
                    this.hidPID.Value = PatientId.ToString();
                }

                if (!object.Equals(Session["PatientVisitId"], null))
                {
                    if (!object.Equals(Request.QueryString["add"], null))
                    {
                        if (Request.QueryString["add"].ToString() == "0")
                        {
                            visitPK = 0;
                            Session["PatientVisitId"] = "0";
                        }
                    }
                    else
                    {
                        visitPK = Convert.ToInt32(Session["PatientVisitId"]);
                    }
                }
                else
                {
                    if (!object.Equals(Request.QueryString["add"], null))
                    {
                        if (Request.QueryString["add"].ToString() == "0")
                        {
                            visitPK = 0;
                        }
                    }
                }
                this.hidVId.Value = visitPK.ToString();

                if (!object.Equals(Session["AppLocationId"], null))
                {
                    locationId = Convert.ToInt32(Session["AppLocationId"]);
                }
                if (!object.Equals(Session["AppUserId"], null))
                {
                    userId = Convert.ToInt32(Session["AppUserId"]);
                }
                if (!object.Equals(Session["PatientSex"], null))
                {
                    this.hidGender.Value = Session["PatientSex"].ToString();
                }
                if (!object.Equals(Session["PatientAge"], null))
                {
                    this.hidDOB.Value = Session["PatientAge"].ToString();
                }
                if (!object.Equals(Session["patientageinyearmonth"], null))
                {
                    this.hidPAYM.Value = Session["patientageinyearmonth"].ToString();
                }
                if (!object.Equals(Session["TechnicalAreaName"], null))
                {
                    this.hidsrvNm.Value = Session["TechnicalAreaName"].ToString();
                }
                if (!object.Equals(Session["TechnicalAreaId"], null))
                {
                    this.hidMOD.Value = Session["TechnicalAreaId"].ToString();
                }

                string tabName = "triage";// ((HtmlInputHidden)this.hidTabName).Value.ToString();
                if (!object.Equals(Request.QueryString["data"], null))
                {
                    if (Request.QueryString["data"].ToString() == "gettriagedata")
                    {
                        tabName = "triage";
                    }
                    if (Request.QueryString["data"].ToString() == "getassessmentdata")
                    {
                        tabName = "assessment";
                    }
                    if (Request.QueryString["data"].ToString() == "getinitiationdata")
                    {
                        tabName = "initiation";
                    }

                    if (Request.QueryString["data"].ToString() == "getzscore")
                    {
                        tabName = "triage";
                    }
                }

                Authenticate();

                if (!object.Equals(Request.QueryString["data"], null))
                {
                    string response = string.Empty;


                    if (Session["AppLocation"] == null || Session.Count == 0 || Session["AppUserID"].ToString() == "")
                    {
                        CLogger.WriteLog(ELogLevel.ERROR, "Session expired!!");

                        ResponseType responsetype = new ResponseType()
                        {
                            Success = EnumUtil.GetEnumDescription(Success.False), ErrorMessage = "Session expired"
                        };
                        response = SerializerUtil.ConverToJson <ResponseType>(responsetype);
                        SendResponse(response);
                    }

                    if (Request.QueryString["data"].ToString() == "gettriagedata")
                    {
                        response = GetPrEPTriage(Convert.ToInt32(PatientId), visitPK, locationId);
                        SendResponse(response);
                    }
                    if (Request.QueryString["data"].ToString() == "getassessmentdata")
                    {
                        response = GetPrEPAssessment(Convert.ToInt32(PatientId), visitPK, locationId);
                        SendResponse(response);
                    }
                    if (Request.QueryString["data"].ToString() == "getinitiationdata")
                    {
                        response = GetPrEPInitiation(Convert.ToInt32(PatientId), visitPK, locationId);
                        SendResponse(response);
                    }
                    if (Request.QueryString["data"].ToString() == "getfacility")
                    {
                        response = GetFacilities(Convert.ToInt32(PatientId), visitPK, locationId);
                        SendResponse(response);
                    }
                    if (Request.QueryString["data"].ToString() == "getzscore")
                    {
                        response = GetZScoreDetails(Convert.ToInt32(PatientId), visitPK, locationId);
                        SendResponse(response);
                    }

                    if (Request.QueryString["data"].ToString() == "savetriage")
                    {
                        System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream);
                        string jsonString         = "";
                        jsonString = sr.ReadToEnd();

                        response = SavePrEPTriage(jsonString, PatientId, visitPK, locationId, userId);
                        SendResponse(response);
                    }

                    if (Request.QueryString["data"].ToString() == "saveassessment")
                    {
                        System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream);
                        string jsonString         = "";
                        jsonString = sr.ReadToEnd();

                        //response = SaveAssessmentData(jsonString, PatientId, visitPK, locationId, userId);
                        SendResponse(response);
                    }
                    if (Request.QueryString["data"].ToString() == "saveinitiation")
                    {
                        System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream);
                        string jsonString         = "";
                        jsonString = sr.ReadToEnd();

                        response = SaveInitiationData(jsonString, PatientId, visitPK, locationId, userId);
                        SendResponse(response);
                    }

                    if (Request.QueryString["data"].ToString() == "deleteform")
                    {
                        response = DeleteForm();
                        SendResponse(response);
                    }
                }
            }
        }
示例#39
0
        /* Parses a network file, and returns a mcNetwork network object. */
        public static mcNetwork GetNetwork(string NetworkName)
        {
            mcNetwork NewNetwork = new mcNetwork();
            System.IO.StreamReader fd;
            string line;
            string temp;
            string[] parts;

            try
            {
                fd = new System.IO.StreamReader("networks\\" + NetworkName + "\\network.dat");
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("An exception occured while trying to read network " + NetworkName + ": " + ex.ToString(), "Error!");
                return null;
            }

            NewNetwork.NetworkName = NetworkName;

            try
            {
                while (true)
                {
                    /* no, this does actually end ;) */
                    line = fd.ReadLine();
                    if (line == null)
                        break;

                    parts = line.Split(' ');

                    switch (line[0])
                    {
                        case 'N':
                            /* nickname token */
                            if (parts.Length < 2)
                            {
                                System.Windows.Forms.MessageBox.Show("Malformed 'N' token in network file " + NetworkName + ", aborting read effort.", "Error!");
                                return null;
                            }
                            NewNetwork.Nickname = parts[1];
                            break;
                        case 'U':
                            /* username token */
                            if (parts.Length < 2)
                            {
                                System.Windows.Forms.MessageBox.Show("Malformed 'U' token in network file " + NetworkName + ", aborting read effort.", "Error!");
                                return null;
                            }
                            NewNetwork.Username = parts[1];
                            break;
                        case 'R':
                            /* realname token */
                            if (parts.Length < 2)
                            {
                                System.Windows.Forms.MessageBox.Show("Malformed 'R' token in network file " + NetworkName + ", aborting read effort.", "Error!");
                                return null;
                            }
                            NewNetwork.Realname = String.Join(" ", parts, 1, parts.Length - 1);
                            break;
                        case 's':
                            /* connect on startup */
                            /* optional token- if it's here, we're supposed to connect on startup. */
                            NewNetwork.ConnectOnStartup = true;
                            break;
                        case 'S':
                            /* a server/port combination */
                            NewNetwork.Servers.Add(parts[1]);
                            break;
                        case '#':
                            /* perform comment */
                            NewNetwork.Perform.Add(line);
                            break;
                        case 'P':
                            /* perform line */
                            temp = String.Join(" ", parts, 1, parts.Length - 1);
                            NewNetwork.Perform.Add(temp);
                            break;
                        case 'B':
                            /* buddy line */
                            if (parts.Length < 2)
                            {
                                System.Windows.Forms.MessageBox.Show("Malformed 'U' token in network file " + NetworkName + ", aborting read effort.", "Error!");
                                return null;
                            }
                            NewNetwork.Buddies.Add(parts[1]);
                            break;
                    }
                }
                return NewNetwork;
            }
            finally
            {
                fd.Close();
            }
        }
示例#40
0
        static void Main(string[] args)
        {
            string fileName = @"C:\Users\wolfg\source\repos\AdventofCode2020\AdventofCode-17\input-17.txt";

            System.IO.StreamReader              file          = new System.IO.StreamReader(fileName);
            List <List <List <char> > >         conway_cube   = new List <List <List <char> > >();
            List <List <List <List <char> > > > conway_cube4d = new List <List <List <List <char> > > >();

            Console.WriteLine(fileName);
            Console.WriteLine(file);

            string data = file.ReadToEnd();

            string[] lines = data.Split();

            conway_cube.Add(new List <List <char> >());
            conway_cube4d.Add(new List <List <List <char> > >());
            conway_cube4d[0].Add(new List <List <char> >());

            int skipped = 0;

            for (int i = 0; i < lines.Length; i++)
            {
                if (string.IsNullOrEmpty(lines[i]))
                {
                    skipped += 1;
                    continue;
                }

                conway_cube[0].Add(new List <char>());
                conway_cube4d[0][0].Add(new List <char>());

                foreach (char c in lines[i])
                {
                    if (!char.IsWhiteSpace(c))
                    {
                        conway_cube[0][i - skipped].Add(c);
                        conway_cube4d[0][0][i - skipped].Add(c);
                    }
                }
            }

            print_cube3d(conway_cube);
            Console.WriteLine("--- Cycle 1 ---");
            conway_cube = update_cube3d(conway_cube);
            print_cube3d(conway_cube);
            Console.WriteLine("--- Cycle 2 ---");
            conway_cube = update_cube3d(conway_cube);
            print_cube3d(conway_cube);
            Console.WriteLine("--- Cycle 3 ---");
            conway_cube = update_cube3d(conway_cube);
            print_cube3d(conway_cube);
            Console.WriteLine("--- Cycle 4 ---");
            conway_cube = update_cube3d(conway_cube);
            print_cube3d(conway_cube);
            Console.WriteLine("--- Cycle 5 ---");
            conway_cube = update_cube3d(conway_cube);
            print_cube3d(conway_cube);
            Console.WriteLine("--- Cycle 6 ---");
            conway_cube = update_cube3d(conway_cube);
            print_cube3d(conway_cube);

            Console.WriteLine($"Total Active Count: {count_all_active3d(conway_cube)}");


            print_cube4d(conway_cube4d);
            Console.WriteLine("--- Cycle 1 ---");
            conway_cube4d = update_cube4d(conway_cube4d);
            print_cube4d(conway_cube4d);
            Console.WriteLine("--- Cycle 2 ---");
            conway_cube4d = update_cube4d(conway_cube4d);
            print_cube4d(conway_cube4d);
            Console.WriteLine("--- Cycle 3 ---");
            conway_cube4d = update_cube4d(conway_cube4d);
            print_cube4d(conway_cube4d);
            Console.WriteLine("--- Cycle 4 ---");
            conway_cube4d = update_cube4d(conway_cube4d);
            print_cube4d(conway_cube4d);
            Console.WriteLine("--- Cycle 5 ---");
            conway_cube4d = update_cube4d(conway_cube4d);
            print_cube4d(conway_cube4d);
            Console.WriteLine("--- Cycle 6 ---");
            conway_cube4d = update_cube4d(conway_cube4d);
            print_cube4d(conway_cube4d);

            Console.WriteLine($"Total Active Count: {count_all_active4d(conway_cube4d)}");
        }
示例#41
0
        static private void GetRoomBarriers(ref AreaMapTemplate template, string start, ref System.IO.StreamReader reader)
        {
            line = reader.ReadLine();

            if (line == start)
            {
                while ((line = reader.ReadLine()) != lineStop)
                {
                    if (CheckLine(ref line) == TileSetFlags.OK)
                    {
                        template.roomBarrierSizes.Add(Convert.ToInt32(line));
                    }
                }
            }
        }
示例#42
0
        public async Task RegisterUserAsync([FromBody, Required] UserRegistration id)
        {
            if (id == null)
            {
                var body = new System.IO.StreamReader(ControllerContext.HttpContext.Request.Body);
                body.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
                var requestBody = body.ReadToEnd();

                _logger.Log(requestBody);

                await "Model is Invalid!".ToResponse(500).ExecuteResultAsync(ControllerContext);
                return;
            }

            var user = _client.GetUser(id.DiscordUserId);

            if (user == null)
            {
                await "User not found!".ToResponse(404).ExecuteResultAsync(ControllerContext);
                return;
            }

            using (var db = new Database.UserContext(_config))
            {
                var botUser = db.Users.FirstOrDefault(x => x.Id == id.DiscordUserId);
                if (botUser != null)
                {
                    if (botUser.Shinden != 0)
                    {
                        await "User already connected!".ToResponse(404).ExecuteResultAsync(ControllerContext);
                        return;
                    }
                }

                var response = await _shClient.Search.UserAsync(id.Username);

                if (!response.IsSuccessStatusCode())
                {
                    await "Can't connect to shinden!".ToResponse(403).ExecuteResultAsync(ControllerContext);
                    return;
                }

                var sUser = (await _shClient.User.GetAsync(response.Body.First())).Body;
                if (sUser.ForumId.Value != id.ForumUserId)
                {
                    await "Something went wrong!".ToResponse(500).ExecuteResultAsync(ControllerContext);
                    return;
                }

                var exe = new Executable($"api-register u{id.DiscordUserId}", new Task(() =>
                {
                    using (var dbs = new Database.UserContext(_config))
                    {
                        botUser         = dbs.GetUserOrCreateAsync(id.DiscordUserId).Result;
                        botUser.Shinden = sUser.Id;

                        dbs.SaveChanges();

                        QueryCacheManager.ExpireTag(new string[] { $"user-{user.Id}", "users" });
                    }
                }));

                await _executor.TryAdd(exe, TimeSpan.FromSeconds(1));

                await "User connected!".ToResponse(200).ExecuteResultAsync(ControllerContext);
            }
        }
示例#43
0
        static private void GetRoomTypeProbabilities(ref AreaMapTemplate template, string start, ref System.IO.StreamReader reader)
        {
            line = reader.ReadLine();

            if (line == start)
            {
                int prev_prob = 0;          int curr_prob = 0;

                while ((line = reader.ReadLine()) != lineStop)
                {
                    if (CheckLine(ref line) == TileSetFlags.OK)
                    {
                        curr_prob  = Convert.ToInt32(line);
                        curr_prob += prev_prob;

                        template.roomTypeProbs.Add(curr_prob);
                        prev_prob = curr_prob;
                    }
                }
            }
        }
示例#44
0
        static private void GetRoomSizesRange(ref AreaMapTemplate template, string start, ref System.IO.StreamReader reader)
        {
            line = reader.ReadLine();
            int try_room;
            int room = 0;

            if (line == start)
            {
                while ((line = reader.ReadLine()) != lineStop)
                {
                    if (CheckLine(ref line) == TileSetFlags.OK)
                    {
                        if (Int32.TryParse(line, out try_room)) // get room #
                        {
                            room = try_room;
                            template.roomSizesRange.Add(new List <Sizes>());
                        }
                        else
                        {
                            template.roomSizesRange[room].Add(StringToRoomSizesRange(line));
                        }
                    }
                }
            }
        }
示例#45
0
        public JsonResult SaveExcelData()
        {
            var param       = Request["param"].Split(new char[] { ',' });
            var belongYear  = Convert.ToInt32(param[0]);
            var belongMonth = Convert.ToInt32(param[1]);
            var createDate  = DateTime.Now;

            var    reader         = new System.IO.StreamReader(HttpContext.Request.InputStream);
            string data           = reader.ReadToEnd();
            var    tempdata       = JsonConvert.DeserializeObject <Dictionary <string, string> >(data);
            var    list           = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(tempdata["data"]);
            var    BaseSQLDB      = SQLHelper.CreateSqlHelper(ConnEnum.Base);
            var    sqlUser        = "******";
            var    sqlSubject     = "select * from S_EP_DefineSubject where Code='{0}' ";
            var    sqlCBSUnitNode = @"select S_EP_CBSNode.*,S_EP_CostUnit.ID CostUnitID from S_EP_CostUnit inner join S_EP_CBSNode 
                                       on S_EP_CostUnit.CBSNodeID = S_EP_CBSNode.ID where S_EP_CostUnit.Code = '{0}'";

            var sqlSubjectCBSNode = @"select * from S_EP_CBSNode where FullID like '%{0}%' and Code = '{1}'";

            var       sqlCBSInfo     = "select * from S_EP_CBSInfo where ID ='{0}' ";
            var       sqlInsert      = string.Empty;
            var       sqlUpdate      = string.Empty;
            DataTable dt             = new DataTable();
            var       dic            = new Dictionary <string, object>();
            var       cbsInfoDicList = new List <Dictionary <string, object> >();

            foreach (var item in list)
            {
                dic.Clear();
                try
                {
                    dt = this.SQLDB.ExecuteDataTable(string.Format(sqlSubject, item.GetValue("SubjectCode")));
                    dic.SetValue("SubjectCode", dt.Rows[0]["Code"]);
                    dic.SetValue("Name", dt.Rows[0]["Name"]);
                    dic.SetValue("ExpenseType", dt.Rows[0]["ExpenseType"]);

                    dt = BaseSQLDB.ExecuteDataTable(string.Format(sqlUser, item.GetValue("UserCode")));
                    dic.SetValue("UserID", dt.Rows[0]["ID"]);
                    dic.SetValue("UserName", dt.Rows[0]["Name"]);
                    dic.SetValue("UserDept", dt.Rows[0]["DeptID"]);
                    dic.SetValue("UserDeptName", dt.Rows[0]["DeptName"]);

                    dt = SQLDB.ExecuteDataTable(string.Format(sqlCBSUnitNode, item.GetValue("UnitCode")));
                    var subjectCbsNodeDt = SQLDB.ExecuteDataTable(string.Format(sqlSubjectCBSNode, dt.Rows[0]["FullID"], item.GetValue("SubjectCode")));

                    dic.SetValue("Code", dt.Rows[0]["Code"]);
                    dic.SetValue("CBSInfoID", dt.Rows[0]["CBSInfoID"]);
                    dic.SetValue("CostUnitID", dt.Rows[0]["CostUnitID"]);
                    dic.SetValue("CBSFullCode", subjectCbsNodeDt.Rows[0]["FullCode"]);
                    dic.SetValue("CBSNodeID", subjectCbsNodeDt.Rows[0]["ID"]);
                    dic.SetValue("CBSNodeFullID", subjectCbsNodeDt.Rows[0]["FullID"]);
                    dic.SetValue("BelongDept", subjectCbsNodeDt.Rows[0]["ChargerDept"]);
                    dic.SetValue("BelongDeptName", subjectCbsNodeDt.Rows[0]["ChargerDeptName"]);
                    dic.SetValue("BelongUser", subjectCbsNodeDt.Rows[0]["ChargerUser"]);
                    dic.SetValue("BelongUserName", subjectCbsNodeDt.Rows[0]["ChargerUserName"]);



                    var cbsDt = SQLDB.ExecuteDataTable(string.Format(sqlCBSInfo, dt.Rows[0]["CBSInfoID"]));
                    cbsInfoDicList.Add(FormulaHelper.DataRowToDic(cbsDt.Rows[0]));
                }
                catch (Exception)
                {
                    throw new Formula.Exceptions.BusinessValidationException("信息有误,无法导入!");
                }

                dic.SetValue("ID", FormulaHelper.CreateGuid());
                dic.SetValue("CreateDate", createDate.ToString("yyyy-MM-dd"));
                dic.SetValue("CreateUserID", CurrentUserInfo.UserID);
                dic.SetValue("CreateUser", CurrentUserInfo.UserName);
                dic.SetValue("ModifyDate", createDate.ToString("yyyy-MM-dd"));
                dic.SetValue("ModifyUserID", CurrentUserInfo.UserID);
                dic.SetValue("ModifyUser", CurrentUserInfo.UserName);
                dic.SetValue("BelongYear", belongYear);
                dic.SetValue("BelongQuarter", (belongMonth + 2) / 3);
                dic.SetValue("BelongMonth", belongMonth);
                dic.SetValue("State", "Finish");
                dic.SetValue("Status", "Finish");

                dic.SetValue("CostType", "DirectCost");
                dic.SetValue("TotalPrice", item.GetValue("TotalPrice"));
                dic.SetValue("Quantity", 1);
                dic.SetValue("UnitPrice", item.GetValue("TotalPrice"));
                dic.SetValue("CostDate", DateTime.Now.ToString("yyyy-MM-dd"));

                sqlInsert += dic.CreateInsertSql(SQLDB, "S_EP_CostInfo", dic.GetValue("ID"));
            }
            string allSql = sqlInsert + " " + sqlUpdate;

            if (!string.IsNullOrEmpty(allSql))
            {
                SQLDB.ExecuteNonQuery(allSql);
            }

            foreach (var item in cbsInfoDicList)
            {
                var cbsInfo = new S_EP_CBSInfo(item);
                cbsInfo.SummaryCostValue();
            }
            return(Json("Success"));
        }
示例#46
0
 protected System.IO.TextReader LoadImageMatrix(string filename)
 {
     System.IO.TextReader tr = new System.IO.StreamReader(filename);
     return(LoadImageMatrix(tr));
 }
示例#47
0
        static void Main(string[] args)
        {
            Console.WriteLine("Assignment 6 - Asserts and Try/Catch.");
            Console.WriteLine();

            // **********************************************************
            // ***************** Assignment 6 Section 1 *****************
            // **********************************************************

            string value = string.Empty;

            Debug.Assert((string.IsNullOrEmpty(value) == false), "Parameter must not be empty of null.");

            int number = 0;

            Debug.Assert((number > 0), "Parameter must be greater than zero.");

            // **********************************************************
            // ***************** Assignment 6 Section 2 *****************
            // **********************************************************

            try
            {
                string[] names = { "Ed", "Fred", "Ted", "Mel", "Stan" };

                string someName;

                for (int i = 0; i <= names.Length; i++)
                {
                    someName = names[i];
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ArrayOutOfBounds error occurred.");
                Console.WriteLine(ex.Message.ToString());
            }


            // **********************************************************
            // ***************** Assignment 6 Section 3 *****************
            // **********************************************************

            try
            {
                int    lineCounter = 0;
                string line;
                using (System.IO.StreamReader file = new System.IO.StreamReader("NoFileNamedThis.txt"))
                {
                    while ((line = file.ReadLine()) != null)
                    {
                        lineCounter++;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("FileDoesNotExist eror occurred.");
                Console.WriteLine(ex.Message.ToString());
            }

            // **********************************************************
            // ***************** Assignment 6 Section 4 *****************
            // **********************************************************

            try
            {
                DivideByZero(42, 0);
            }
            catch (Exception ex)
            {
                Console.WriteLine("DivideByZero error occurred");
                Console.WriteLine(ex.Message.ToString());
            }
            Console.Read();
        }
示例#48
0
        public JsonResult ValidateExcelData()
        {
            var    reader    = new System.IO.StreamReader(HttpContext.Request.InputStream);
            string data      = reader.ReadToEnd();
            var    tempdata  = JsonConvert.DeserializeObject <Dictionary <string, string> >(data);
            var    excelData = JsonConvert.DeserializeObject <ExcelData>(tempdata["data"]);

            var BaseSQLDB  = SQLHelper.CreateSqlHelper(ConnEnum.Base);
            var sqlUser    = "******";
            var sqlSubject = "select ID,Name from S_EP_DefineSubject where Code='{0}' ";

            var sqlSubjectCBSNode = @"select * from S_EP_CBSNode where FullID like '{0}' and Code = '{1}'";

            DataTable dt         = new DataTable();
            decimal   applyValue = 0m;
            var       errors     = excelData.Vaildate(e =>
            {
                switch (e.FieldName)
                {
                case "TotalPrice":
                    if (string.IsNullOrWhiteSpace(e.Value))
                    {
                        e.IsValid   = false;
                        e.ErrorText = "不能为空";
                    }
                    else if (!decimal.TryParse(e.Value, out applyValue))
                    {
                        e.IsValid   = false;
                        e.ErrorText = "金额格式不正确";
                    }
                    break;

                case "SubjectCode":
                    if (string.IsNullOrWhiteSpace(e.Value))
                    {
                        e.IsValid   = false;
                        e.ErrorText = "不能为空";
                    }
                    else
                    {
                        dt = this.SQLDB.ExecuteDataTable(string.Format(sqlSubject, e.Value));
                        if (dt.Rows.Count == 0)
                        {
                            e.IsValid   = false;
                            e.ErrorText = "科目信息不存在";
                        }
                    }
                    break;

                case "UserCode":
                    if (!string.IsNullOrWhiteSpace(e.Value))
                    {
                        dt = BaseSQLDB.ExecuteDataTable(string.Format(sqlUser, e.Value));
                        if (dt.Rows.Count == 0)
                        {
                            e.IsValid   = false;
                            e.ErrorText = "工号信息不存在";
                        }
                    }
                    break;

                case "UnitCode":
                    if (!string.IsNullOrWhiteSpace(e.Value))
                    {
                        var objDT = this.SQLDB.ExecuteDataTable(@"select S_EP_CostUnit.*, isnull(S_EP_CBSNode.IsClosed,'false') IsClosed from S_EP_CostUnit inner join S_EP_CBSNode 
                                       on S_EP_CostUnit.CBSNodeID = S_EP_CBSNode.ID where S_EP_CostUnit.Code = '" + e.Value.Trim() + "'");
                        if (objDT.Rows.Count == 0)
                        {
                            e.ErrorText = "未找到该编号的项目";
                            e.IsValid   = false;
                        }
                        else if (objDT.Rows[0]["IsClosed"].ToString().ToLower() == "true")
                        {
                            e.ErrorText = "该项目已经关闭";
                            e.IsValid   = false;
                        }
                    }
                    break;

                default:
                    break;
                }
            });

            return(Json(errors));
        }
示例#49
0
 private void GameOver_Load(object sender, EventArgs e)
 {
     System.IO.StreamReader file = new System.IO.StreamReader(@"Records");
     label1.Text = file.ReadToEnd();
 }
示例#50
0
        private void Get_timer_Tick(object sender, EventArgs e)
        {
            try
            {
                setting.checkBox1.Checked = Properties.Settings.Default.check;
                setting.checkBox2.Checked = Properties.Settings.Default.check2;
                string json;
                using (var wc = new System.Net.WebClient())
                {
                    wc.Encoding = System.Text.Encoding.UTF8;
                    json        = wc.DownloadString("https://kwatch-24h.net/EQLevel.json");
                }
                var jsonData = JsonConvert.DeserializeObject <EQJson>(json);

                levellabel.Text  = $"振動レベル\nLv.{jsonData.l}";
                redlabrl.Text    = $"赤:{jsonData.r}";
                yellowlabel.Text = $"黄:{jsonData.y}";
                greenlabel.Text  = $"緑:{jsonData.g}";


                using (System.IO.StreamReader file = new System.IO.StreamReader(@"sounds/sound.txt", System.Text.Encoding.UTF8))
                {
                    string        line = "";
                    List <string> list = new List <string>();

                    while ((line = file.ReadLine()) != null)
                    {
                        list.Add(line);
                    }
                    if (jsonData.l < int.Parse(list[1]))
                    {
                        switch (setting.checkBox1.Checked)
                        {
                        case true:
                            Console.WriteLine("効果音1有効です。");
                            PlaySound(@"sounds/alarm1.wav");
                            break;

                        case false:
                            Console.WriteLine("効果音1は無効です。");
                            break;
                        }
                    }
                    if (jsonData.l > int.Parse(list[3]))
                    {
                        switch (setting.checkBox1.Checked)
                        {
                        case true:
                            Console.WriteLine("効果音2有効です。");
                            PlaySound(@"sounds/alarm2.wav");
                            break;

                        case false:
                            Console.WriteLine("効果音2は無効です。");
                            break;
                        }
                    }
                    if (jsonData.l > int.Parse(list[5]))
                    {
                        switch (setting.checkBox2.Checked)
                        {
                        case true:
                            Console.WriteLine("効果音3有効です。");
                            PlaySound(@"sounds/alarm3.wav");
                            break;

                        case false:
                            Console.WriteLine("効果音3は無効です。");
                            break;
                        }
                    }
                    if (jsonData.l > int.Parse(list[7]))
                    {
                        switch (setting.checkBox2.Checked)
                        {
                        case true:
                            Console.WriteLine("効果音4有効です。");
                            PlaySound(@"sounds/alarm4.wav");
                            break;

                        case false:
                            Console.WriteLine("効果音4は無効です。");
                            break;
                        }
                    }
                    if (jsonData.l > int.Parse(list[9]))
                    {
                        switch (setting.checkBox2.Checked)
                        {
                        case true:
                            Console.WriteLine("効果音5有効です。");
                            PlaySound(@"sounds/alarm5.wav");
                            break;

                        case false:
                            Console.WriteLine("効果音5は無効です。");
                            break;
                        }
                    }
                    if (jsonData.l > int.Parse(list[11]))
                    {
                        switch (setting.checkBox2.Checked)
                        {
                        case true:
                            Console.WriteLine("効果音6有効です。");
                            PlaySound(@"sounds/alarm6.wav");
                            break;

                        case false:
                            Console.WriteLine("効果音6は無効です。");
                            break;
                        }
                        if (jsonData.l > int.Parse(list[13]))
                        {
                            switch (setting.checkBox2.Checked)
                            {
                            case true:
                                Console.WriteLine("効果音7有効です。");
                                PlaySound(@"sounds/alarm7.wav");
                                break;

                            case false:
                                Console.WriteLine("効果音7は無効です。");
                                break;
                            }
                        }
                    }
                }
            }
            catch { }
        }
        // Credits Cristian Romanescu @ http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data
        static void HttpUploadFile(string url, byte[] fileContents, string fileParam, string fileName, string contentType, System.Collections.Specialized.NameValueCollection nvc)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            //HACK: add proxy
            IWebProxy proxy = WebRequest.GetSystemWebProxy();

            proxy.Credentials  = System.Net.CredentialCache.DefaultCredentials;
            wr.Proxy           = proxy;
            wr.PreAuthenticate = true;
            //HACK: end add proxy
            wr.Accept      = "text/html,application/xml";
            wr.UserAgent   = "Mozilla/5.0"; // Fix HTTP Error 406 Not acceptable - Security incident detected
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method      = "POST";

            System.IO.Stream rs = wr.GetRequestStream();

            {
                string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n";
                foreach (string key in nvc.Keys)
                {
                    // Parameter Header (+ boundary)
                    rs.Write(boundarybytes, 0, boundarybytes.Length);
                    string header      = string.Format(formdataTemplate, key);
                    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                    rs.Write(headerbytes, 0, headerbytes.Length);

                    // Parameter Content
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(nvc[key].ToString());
                    rs.Write(buffer, 0, buffer.Length);
                }
            }
            {
                // File Header (+ boundary)
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                string header         = string.Format(headerTemplate, fileParam, fileName, contentType);
                byte[] headerbytes    = System.Text.Encoding.UTF8.GetBytes(header);
                rs.Write(headerbytes, 0, headerbytes.Length);

                // File Content
                rs.Write(fileContents, 0, fileContents.Length);
            }
            {
                // WebRequest Trailer
                byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                rs.Write(trailer, 0, trailer.Length);
            }
            rs.Close();

            try
            {
                using (System.Net.WebResponse wresp = wr.GetResponse())
                {
                    System.IO.StreamReader respReader = new System.IO.StreamReader(wresp.GetResponseStream());
                    //MessageBox.Show(respReader.ReadToEnd());
                }
            }
            catch (System.Net.WebException ex)
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(ex.Response.GetResponseStream());
                MessageBox.Show(ex.Message + " " + reader.ReadToEnd());
            }
        }
示例#52
0
        private async void HttpPushReceived(object sender, HttpNotificationEventArgs e)
        {
            bool   found = false;
            string message;

            string[] separators = { ":" };
            string[] decode     = new string[4];
            string   sentby     = null;
            int      count      = 0;
            int      index      = 0;

            using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
            {
                count++;
                message = reader.ReadToEnd();
            }


            decode = message.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            switch (decode[0])
            {
            case "message":
                foreach (ChatData i in App.ViewModel.Items)
                {
                    if (i.PhoneNumber.Equals(decode[1]))
                    {
                        sentby = i.ContactName;
                        found  = true;
                        break;
                    }
                }
                if (!found)
                {
                    foreach (Favourites c in App.ViewModel.Favcontacts)
                    {
                        if (c.Favouritenumber.Equals(decode[1]))
                        {
                            sentby = c.Name;
                            found  = true;
                            break;
                        }
                    }
                }

                if (!found)
                {
                    sentby = decode[1];
                }
                var toastDescriptor = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
                var txtNodes        = toastDescriptor.GetElementsByTagName("text");
                var audio           = toastDescriptor.CreateElement("audio");
                audio.SetAttribute("src", "ms-winsoundevent:Notification.SMS");
                audio.SetAttribute("loop", "false");

                txtNodes[0].AppendChild(toastDescriptor.CreateTextNode(sentby));
                txtNodes[1].AppendChild(toastDescriptor.CreateTextNode(decode[3]));


                var toast = new ToastNotification(toastDescriptor);
                toast.Activated += new Windows.Foundation.TypedEventHandler <ToastNotification, object>(toast_Activated);


                toast.Group = sentby;
                toast.Tag   = decode[2];


                toast.SuppressPopup = false;

                var toastNotifier = ToastNotificationManager.CreateToastNotifier();
                toastNotifier.Show(toast);
                found = false;
                break;

            case "secret":
                foreach (ChatData i in App.ViewModel.Items)
                {
                    if (i.PhoneNumber.Equals(decode[1]))
                    {
                        for (index = (i.Chats.Count - 1); index >= 0; index--)
                        {
                            if (i.Chats[index].Id.Equals(decode[2]))
                            {
                                i.Chats[index].Secret = true;
                                break;
                            }
                        }
                        break;
                    }
                }
                break;

            case "edit":
                foreach (ChatData i in App.ViewModel.Items)
                {
                    if (i.PhoneNumber.Equals(decode[1]))
                    {
                        sentby = i.ContactName;
                        for (index = (i.Chats.Count - 1); index >= 0; index--)
                        {
                            if (i.Chats[index].Id.Equals(decode[2]))
                            {
                                i.Chats[index].Text = i.Chats[index].Text + Environment.NewLine + "[Edited]" + Environment.NewLine + decode[3];
                                found = true;
                                break;
                            }
                        }
                        break;
                    }
                }
                if (!found)
                {
                    decode[3] = "[Edited] " + (await App.ViewModel.RetreiveMessage(decode[2]));
                }
                await App.ViewModel.UpdateChats();

                toastDescriptor = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
                txtNodes        = toastDescriptor.GetElementsByTagName("text");
                txtNodes[0].AppendChild(toastDescriptor.CreateTextNode(sentby));
                txtNodes[1].AppendChild(toastDescriptor.CreateTextNode(decode[3]));
                toast            = new ToastNotification(toastDescriptor);
                toast.Activated += new Windows.Foundation.TypedEventHandler <ToastNotification, object>(toast_Activated);
                toast.Group      = sentby;
                toast.Tag        = decode[2];


                toast.SuppressPopup = true;
                if (!found)
                {
                    toast.SuppressPopup = false;
                }

                toastNotifier = ToastNotificationManager.CreateToastNotifier();
                toastNotifier.Show(toast);

                found = false;
                break;
            }
        }
示例#53
0
        private string CreateRowXml(string vergelijking, string[] fieldnames, string[] fieldvalues)
        {
            var doc = new System.Xml.XmlDocument();

            /*
             * if (Properties.Settings.Default.output_format == "html")
             * {
             */
            var table     = doc.CreateElement("table");
            var tablename = doc.CreateAttribute("name");

            tablename.Value = vergelijking.ToLower();
            table.Attributes.Append(tablename);
            doc.AppendChild(table);

            for (int i = 0; i < fieldnames.Length; i++)
            {
                var tr = doc.CreateElement("tr");
                table.AppendChild(tr);

                var tdname = doc.CreateElement("td");
                tdname.InnerText = fieldnames[i].ToLower();
                tr.AppendChild(tdname);

                var tdvalue = doc.CreateElement("td");
                if (fieldvalues[i] == null || Convert.ToString(fieldvalues[i]).Length == 0)
                {
                    // we moeten er iets in hebben staan om de uitlijning altijd goed te houden
                    tdvalue.InnerXml = "&nbsp;";
                }
                else
                {
                    tdvalue.InnerText = fieldvalues[i];
                }
                tr.AppendChild(tdvalue);
            }

            /*
             * }
             * else {
             *  var rootnode = doc.CreateElement(System.Xml.XmlConvert.EncodeName(vergelijking).ToLower());
             *  if (fieldnames.Length > 0)
             *  {
             *      for(int i=0; i < fieldnames.Length; i++)
             *      {
             *          var element = doc.CreateElement(System.Xml.XmlConvert.EncodeName(fieldnames[i]).ToLower());
             *          if(fieldvalues[i] == null || Convert.ToString(fieldvalues[i]).Length == 0)
             *          {
             *              var nil = doc.CreateAttribute("nil", "xsi", "http://w3.org/2001/XMLSchema-instance");
             *              nil.Value = Convert.ToString(true);
             *              element.Attributes.Append(nil);
             *          }
             *          else
             *          {
             *              element.InnerText = fieldvalues[i];
             *          }
             *          rootnode.AppendChild(element);
             *      }
             *  }
             *  else
             *  {
             *      var nil = doc.CreateAttribute("nil", "xsi", "http://w3.org/2001/XMLSchema-instance");
             *      nil.Value = Convert.ToString(true);
             *      rootnode.Attributes.Append(nil);
             *  }
             *  doc.AppendChild(rootnode);
             * }
             */
            var stream = new System.IO.MemoryStream();
            var writer = new System.Xml.XmlTextWriter(stream, Encoding.Unicode);

            writer.Formatting = System.Xml.Formatting.Indented;
            doc.WriteContentTo(writer);
            writer.Flush();
            stream.Flush();
            stream.Position = 0;
            var reader = new System.IO.StreamReader(stream);

            return(reader.ReadToEnd());
        }
示例#54
0
        private static long[] ReadFromFile()
        {
            var file = new System.IO.StreamReader(@"input.txt");

            return(file.ReadLine()?.Split(' ').Select(long.Parse).ToArray());
        }
示例#55
0
        public GCode(string fileName)
        {
            this.fileName = fileName;

            inputfile = new System.IO.StreamReader(fileName);
        }
示例#56
0
        public ActionResult Webhook(string id)
        {
            string securityId = ConfigurationManager.AppSettings["SecurityId"];

            if (!String.IsNullOrEmpty(securityId))
            {
                if (securityId != id)
                {
                    return(new HttpStatusCodeResult((int)System.Net.HttpStatusCode.BadRequest));
                }
            }

            // Verify the content type is json
            if (!this.Request.ContentType.StartsWith("application/json"))
            {
                return(new HttpStatusCodeResult((int)System.Net.HttpStatusCode.BadRequest));
            }

            // TODO: Verify the user agent

            // Parse the JSON content simply to validate it as proper JSON
            this.Request.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
            var textReader = new System.IO.StreamReader(this.Request.InputStream);

            {
                Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(textReader);
                JObject jObject = JObject.Load(reader);
            }

            // All is OK, so seek back to the start
            this.Request.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
            // and re-read the content
            string messageBody = textReader.ReadToEnd();

            string queueUrl = ConfigurationManager.AppSettings["SqsQueueUrl"];

            if (String.IsNullOrEmpty(queueUrl))
            {
                throw new Exception("Null or empty SqsQueueUrl setting.");
            }

            Amazon.SQS.AmazonSQS sqsClient;

            string endPointName = ConfigurationManager.AppSettings["SqsEndpoint"];

            if (!String.IsNullOrEmpty(endPointName))
            {
                Amazon.RegionEndpoint endPoint = Amazon.RegionEndpoint.GetBySystemName(endPointName);
                if (endPoint == null)
                {
                    throw new Exception("Invalid Amazon AWS endpoint name: " + endPointName);
                }

                sqsClient = new Amazon.SQS.AmazonSQSClient(endPoint);
            }
            else
            {
                sqsClient = new Amazon.SQS.AmazonSQSClient();
            }

            // Build our request
            var request = new Amazon.SQS.Model.SendMessageRequest()
                          .WithMessageBody(messageBody)
                          .WithQueueUrl(queueUrl);

            // Send to SQS
            var    response  = sqsClient.SendMessage(request);
            string messageId = response.SendMessageResult.MessageId;

            return(new EmptyResult());
        }
示例#57
0
 Input(System.IO.Stream stream, InputType inputType)
 {
     _sr        = new System.IO.StreamReader(stream);
     _inputType = inputType;
 }
示例#58
0
        public static Npc LoadNpc(int npcNum)
        {
            Npc    npc      = new Npc();
            string FileName = IO.Paths.NpcsFolder + "npc" + npcNum + ".dat";
            string s;

            string[] parse;
            using (System.IO.StreamReader read = new System.IO.StreamReader(FileName)) {
                while (!(read.EndOfStream))
                {
                    s     = read.ReadLine();
                    parse = s.Split('|');
                    switch (parse[0].ToLower())
                    {
                    case "npcdata":
                        if (parse[1].ToLower() != "v4")
                        {
                            read.Close();
                            return(null);
                        }
                        break;

                    case "data": {
                        npc.Name      = parse[1];
                        npc.AttackSay = parse[2];
                        npc.Sprite    = parse[3].ToInt();
                        npc.SpawnSecs = parse[4].ToInt();
                        npc.Behavior  = (Enums.NpcBehavior)parse[5].ToInt();
                        npc.Range     = parse[6].ToInt();
                        npc.Species   = parse[7].ToInt();
                        npc.Big       = parse[8].ToBool();
                        npc.SpawnTime = parse[9].ToInt();
                        if (parse.Length > 11)
                        {
                            npc.Spell = parse[10].ToInt();
                        }
                        if (parse.Length > 12)
                        {
                            npc.Frequency = parse[11].ToInt();
                        }
                        if (parse.Length > 13)
                        {
                            npc.AIScript = parse[12];
                        }
                    }
                    break;

                    case "recruit":
                        npc.RecruitRate  = parse[1].ToInt();
                        npc.RecruitLevel = parse[2].ToInt();
                        break;

                    case "items": {
                        if (parse[1].ToInt() < npc.Drops.Length)
                        {
                            npc.Drops[parse[1].ToInt()].ItemNum   = parse[2].ToInt();
                            npc.Drops[parse[1].ToInt()].ItemValue = parse[3].ToInt();
                            npc.Drops[parse[1].ToInt()].Chance    = parse[4].ToInt();
                        }
                    }
                    break;
                    }
                }
            }
            return(npc);
        }
        private FR_Base Load(DbConnection Connection, DbTransaction Transaction, Guid ObjectID, string ConnectionString)
        {
            //Standard return type
            FR_Base retStatus = new FR_Base();

            bool cleanupConnection  = false;
            bool cleanupTransaction = false;

            try
            {
                #region Verify/Create Connections
                //Create connection if Connection is null
                if (Connection == null)
                {
                    cleanupConnection = true;
                    Connection        = CSV2Core_MySQL.Support.DBSQLSupport.CreateConnection(ConnectionString);
                    Connection.Open();
                }
                //If transaction is not open/not valid
                if (Transaction == null)
                {
                    cleanupTransaction = true;
                    Transaction        = Connection.BeginTransaction();
                }
                #endregion
                //Get the SelectQuerry
                string SelectQuery = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("CL1_USR.USR_Device_ConfigurationCode.SQL.Select.sql")).ReadToEnd();

                DbCommand command = Connection.CreateCommand();
                //Set Connection/Transaction
                command.Connection  = Connection;
                command.Transaction = Transaction;
                //Set Query/Timeout
                command.CommandText    = SelectQuery;
                command.CommandTimeout = QueryTimeout;

                //Firstly, before loading, set the GUID to empty
                //So the entity does not exist, it will have a GUID set to empty
                _USR_Device_ConfigurationCodeID = Guid.Empty;
                CSV2Core_MySQL.Support.DBSQLSupport.SetParameter(command, "USR_Device_ConfigurationCodeID", ObjectID);

                #region Command Execution
                try
                {
                    var loader = new CSV2Core_MySQL.Dictionaries.MultiTable.Loader.DictionaryLoader(Connection, Transaction);
                    var reader = new CSV2Core_MySQL.Support.DBSQLReader(command.ExecuteReader());
                    reader.SetOrdinals(new string[] { "USR_Device_ConfigurationCodeID", "DeviceConfigurationCode", "DateOfExpiry", "IsMultipleUsagesAllowed", "Exclusively_UsableBy_Device_RefID", "Preconfigured_ApplicationBaseURL", "Preconfigured_OtherConfigurationInformation", "Preconfigured_PrimaryUser_RefID", "Creation_Timestamp", "Tenant_RefID", "IsDeleted", "Modification_Timestamp" });
                    if (reader.HasRows == true)
                    {
                        reader.Read();                         //Single result only
                        //0:Parameter USR_Device_ConfigurationCodeID of type Guid
                        _USR_Device_ConfigurationCodeID = reader.GetGuid(0);
                        //1:Parameter DeviceConfigurationCode of type String
                        _DeviceConfigurationCode = reader.GetString(1);
                        //2:Parameter DateOfExpiry of type DateTime
                        _DateOfExpiry = reader.GetDate(2);
                        //3:Parameter IsMultipleUsagesAllowed of type Boolean
                        _IsMultipleUsagesAllowed = reader.GetBoolean(3);
                        //4:Parameter Exclusively_UsableBy_Device_RefID of type Guid
                        _Exclusively_UsableBy_Device_RefID = reader.GetGuid(4);
                        //5:Parameter Preconfigured_ApplicationBaseURL of type String
                        _Preconfigured_ApplicationBaseURL = reader.GetString(5);
                        //6:Parameter Preconfigured_OtherConfigurationInformation of type String
                        _Preconfigured_OtherConfigurationInformation = reader.GetString(6);
                        //7:Parameter Preconfigured_PrimaryUser_RefID of type Guid
                        _Preconfigured_PrimaryUser_RefID = reader.GetGuid(7);
                        //8:Parameter Creation_Timestamp of type DateTime
                        _Creation_Timestamp = reader.GetDate(8);
                        //9:Parameter Tenant_RefID of type Guid
                        _Tenant_RefID = reader.GetGuid(9);
                        //10:Parameter IsDeleted of type Boolean
                        _IsDeleted = reader.GetBoolean(10);
                        //11:Parameter Modification_Timestamp of type DateTime
                        _Modification_Timestamp = reader.GetDate(11);
                    }
                    //Close the reader so other connections can use it
                    reader.Close();

                    loader.Load();

                    if (_USR_Device_ConfigurationCodeID != Guid.Empty)
                    {
                        //Successfully loaded
                        Status_IsAlreadySaved = true;
                        Status_IsDirty        = false;
                    }
                    else
                    {
                        //Fault in loading due to invalid UUID (Guid)
                        Status_IsAlreadySaved = false;
                        Status_IsDirty        = false;
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
                #endregion

                #region Cleanup Transaction/Connection
                //If we started the transaction, we will commit it
                if (cleanupTransaction && Transaction != null)
                {
                    Transaction.Commit();
                }

                //If we opened the connection we will close it
                if (cleanupConnection && Connection != null)
                {
                    Connection.Close();
                }

                #endregion
            } catch (Exception ex) {
                try
                {
                    if (cleanupTransaction == true && Transaction != null)
                    {
                        Transaction.Rollback();
                    }
                }
                catch { }

                try
                {
                    if (cleanupConnection == true && Connection != null)
                    {
                        Connection.Close();
                    }
                }
                catch { }

                throw;
            }

            return(retStatus);
        }
示例#60
0
        public void Index()
        {
            var    context = HttpContext;
            string id      = context.Request["id"] + string.Empty;

            if (!string.IsNullOrEmpty(id))
            {
                Newtonsoft.Json.Linq.JObject ret = new Newtonsoft.Json.Linq.JObject();
                string sql  = string.Format("select OBJECTID,DETAILENAME from C_RULEDETAILS where PID='{0}'and state=1 ", id);
                var    data = GetJson(sql);
                sql = string.Format("select EXPRESSION from C_RuleExpression where RULENAMEID='{0}'", id);
                var    dt     = AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteDataTable(sql);
                string expStr = "";
                if (dt.Rows.Count > 0)
                {
                    expStr = dt.Rows[0]["EXPRESSION"] + string.Empty;
                }
                expStr = expStr.Replace('*', '×');
                expStr = expStr.Replace('/', '÷');

                //var exp = GetEXP(sql, out expStr);
                ret.Add("data", data);
                ret.Add("expression", expStr);
                //ret.Add("exp", exp);
                context.Response.Write(ret);
            }
            else
            {
                System.IO.Stream s = context.Request.InputStream;
                int i = 0;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                {
                    var t = sr.ReadToEnd();
                    //Expersion exp = JsonConvert.DeserializeObject<Expersion>(t);
                    Newtonsoft.Json.Linq.JObject ret = Newtonsoft.Json.Linq.JObject.Parse(t);
                    string expe = ret["exp"] + string.Empty;
                    id = ret["id"] + string.Empty;

                    expe = expe.Replace('×', '*');
                    expe = expe.Replace('÷', '/');

                    string sql       = string.Format("select count(1) from C_RuleExpression where RULENAMEID='{0}'", id);
                    object sqlResult = AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteScalar(sql);
                    if (sqlResult != null && sqlResult != DBNull.Value && int.TryParse(sqlResult.ToString(), out i))
                    {
                        if (i > 0)
                        {
                            sql = string.Format("update C_RuleExpression set EXPRESSION='{0}' where RULENAMEID='{1}'", expe, id);
                        }
                        else
                        {
                            sql = string.Format("insert into C_RuleExpression(objectid,RULENAMEID,EXPRESSION) values('{0}','{1}','{2}')", Guid.NewGuid().ToString(), id, expe);
                        }
                    }
                    i = AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteNonQuery(sql);
                }
                if (i > 0)
                {
                    context.Response.Write("success");
                }
                else
                {
                    context.Response.Write("failed");
                }
            }
        }