static void Main(string[] args) { AppSettingsReader asr = new AppSettingsReader(); // Получаем специальные данные из файла *.config. int repeatCount = (int) asr.GetValue("RepeatCount", typeof(int) ); string textColor = (string) asr.GetValue("TextColor", typeof(string) ); Console.Write("RepeatCount:{0} TextColor:{1}", repeatCount, textColor); }
public static string Decrypt(string cipherString, bool useHashing) { byte[] keyArray; byte[] toEncryptArray = Convert.FromBase64String(cipherString); System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader(); string key = (string)settingsReader.GetValue("search", typeof(String)); if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); hashmd5.Clear(); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); tdes.Clear(); return UTF8Encoding.UTF8.GetString(resultArray); }
public static string Encrypt(string toEncrypt, bool useHashing) { byte[] keyArray; byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader(); // Get the key from config file string key = (string)settingsReader.GetValue("SecurityKey", typeof(String)); //System.Windows.Forms.MessageBox.Show(key); if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); hashmd5.Clear(); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); tdes.Clear(); return Convert.ToBase64String(resultArray, 0, resultArray.Length); }
public static string Decrypt(string cipherString, bool useHashing) { /* * Reference to: Syed Moshiur - Software Developer * http://www.codeproject.com/Articles/14150/Encrypt-and-Decrypt-Data-with-C * */ byte[] keyArray; //get the byte code of the string byte[] toEncryptArray = Convert.FromBase64String(cipherString); System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader(); //Get your key from config file to open the lock! string key = (string)settingsReader.GetValue("SecurityKey", typeof(String)); if (useHashing) { //if hashing was used get the hash code with regards to your key MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); //release any resource held by the MD5CryptoServiceProvider hashmd5.Clear(); } else { //if hashing was not implemented get the byte code of the key keyArray = UTF8Encoding.UTF8.GetBytes(key); } TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); //set the secret key for the tripleDES algorithm tdes.Key = keyArray; //mode of operation. there are other 4 modes. //We choose ECB(Electronic code Book) tdes.Mode = CipherMode.ECB; //padding mode(if any extra byte added) tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock( toEncryptArray, 0, toEncryptArray.Length); //Release resources held by TripleDes Encryptor tdes.Clear(); //return the Clear decrypted TEXT return UTF8Encoding.UTF8.GetString(resultArray); }
public static string Encrypt(string toEncrypt, bool useHashing) { /* * Reference to: Syed Moshiur - Software Developer * http://www.codeproject.com/Articles/14150/Encrypt-and-Decrypt-Data-with-C * */ byte[] keyArray; byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader(); // Get the key from config file string key = (string)settingsReader.GetValue("SecurityKey", typeof(String)); //If hashing use get hashcode regards to your key if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); //Always release the resources and flush data // of the Cryptographic service provide. Best Practice hashmd5.Clear(); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); //set the secret key for the tripleDES algorithm tdes.Key = keyArray; //mode of operation. there are other 4 modes. //We choose ECB(Electronic code Book) tdes.Mode = CipherMode.ECB; //padding mode(if any extra byte added) tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateEncryptor(); //transform the specified region of bytes array to resultArray byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); //Release resources held by TripleDes Encryptor tdes.Clear(); //Return the encrypted data into unreadable string format return Convert.ToBase64String(resultArray, 0, resultArray.Length); }
/// <summary> /// 初始化引擎 /// </summary> private void InitEngines() { //读取配置文件 AppSettingsReader reader = new AppSettingsReader(); string appId = (string)reader.GetValue("APP_ID", typeof(string)); string sdkKey64 = (string)reader.GetValue("SDKKEY64", typeof(string)); string sdkKey32 = (string)reader.GetValue("SDKKEY32", typeof(string)); rgbCameraIndex = (int)reader.GetValue("RGB_CAMERA_INDEX", typeof(int)); irCameraIndex = (int)reader.GetValue("IR_CAMERA_INDEX", typeof(int)); //判断CPU位数 var is64CPU = Environment.Is64BitProcess; if (string.IsNullOrWhiteSpace(appId) || string.IsNullOrWhiteSpace(is64CPU?sdkKey64: sdkKey32)) { //禁用相关功能按钮 ControlsEnable(false, chooseMultiImgBtn, matchBtn, btnClearFaceList, chooseImgBtn); MessageBox.Show(string.Format("请在App.config配置文件中先配置APP_ID和SDKKEY{0}!", is64CPU ? "64" : "32")); return; } //在线激活引擎 如出现错误,1.请先确认从官网下载的sdk库已放到对应的bin中,2.当前选择的CPU为x86或者x64 int retCode = 0; try { retCode = ASFFunctions.ASFActivation(appId, is64CPU ? sdkKey64 : sdkKey32); } catch (Exception ex) { //禁用相关功能按钮 ControlsEnable(false, chooseMultiImgBtn, matchBtn, btnClearFaceList, chooseImgBtn); if (ex.Message.Contains("无法加载 DLL")) { MessageBox.Show("请将sdk相关DLL放入bin对应的x86或x64下的文件夹中!"); } else { MessageBox.Show("激活引擎失败!"); } return; } Console.WriteLine("Activate Result:" + retCode); //初始化引擎 uint detectMode = DetectionMode.ASF_DETECT_MODE_IMAGE; //Video模式下检测脸部的角度优先值 int videoDetectFaceOrientPriority = ASF_OrientPriority.ASF_OP_0_HIGHER_EXT; //Image模式下检测脸部的角度优先值 int imageDetectFaceOrientPriority = ASF_OrientPriority.ASF_OP_0_ONLY; //人脸在图片中所占比例,如果需要调整检测人脸尺寸请修改此值,有效数值为2-32 int detectFaceScaleVal = 16; //最大需要检测的人脸个数 int detectFaceMaxNum = 5; //引擎初始化时需要初始化的检测功能组合 int combinedMask = FaceEngineMask.ASF_FACE_DETECT | FaceEngineMask.ASF_FACERECOGNITION | FaceEngineMask.ASF_AGE | FaceEngineMask.ASF_GENDER | FaceEngineMask.ASF_FACE3DANGLE; //初始化引擎,正常值为0,其他返回值请参考http://ai.arcsoft.com.cn/bbs/forum.php?mod=viewthread&tid=19&_dsign=dbad527e retCode = ASFFunctions.ASFInitEngine(detectMode, imageDetectFaceOrientPriority, detectFaceScaleVal, detectFaceMaxNum, combinedMask, ref pImageEngine); Console.WriteLine("InitEngine Result:" + retCode); AppendText((retCode == 0) ? "引擎初始化成功!\n" : string.Format("引擎初始化失败!错误码为:{0}\n", retCode)); if (retCode != 0) { //禁用相关功能按钮 ControlsEnable(false, chooseMultiImgBtn, matchBtn, btnClearFaceList, chooseImgBtn); } //初始化视频模式下人脸检测引擎 uint detectModeVideo = DetectionMode.ASF_DETECT_MODE_VIDEO; int combinedMaskVideo = FaceEngineMask.ASF_FACE_DETECT | FaceEngineMask.ASF_FACERECOGNITION; retCode = ASFFunctions.ASFInitEngine(detectModeVideo, videoDetectFaceOrientPriority, detectFaceScaleVal, detectFaceMaxNum, combinedMaskVideo, ref pVideoEngine); //RGB视频专用FR引擎 detectFaceMaxNum = 1; combinedMask = FaceEngineMask.ASF_FACE_DETECT | FaceEngineMask.ASF_FACERECOGNITION | FaceEngineMask.ASF_LIVENESS; retCode = ASFFunctions.ASFInitEngine(detectMode, imageDetectFaceOrientPriority, detectFaceScaleVal, detectFaceMaxNum, combinedMask, ref pVideoRGBImageEngine); //IR视频专用FR引擎 combinedMask = FaceEngineMask.ASF_FACE_DETECT | FaceEngineMask.ASF_FACERECOGNITION | FaceEngineMask.ASF_IR_LIVENESS; retCode = ASFFunctions.ASFInitEngine(detectMode, imageDetectFaceOrientPriority, detectFaceScaleVal, detectFaceMaxNum, combinedMask, ref pVideoIRImageEngine); Console.WriteLine("InitVideoEngine Result:" + retCode); initVideo(); }
public EmployeeWindow(Window _window, MainWindow _mainWindow, EmployeeList _empList, DepartmentList _depList) { InitializeComponent(); //горячие клавиши AppSettingsReader reader = new AppSettingsReader(); KeyGestureConverter gestureConverter = new KeyGestureConverter(); try { string tmp = (string)reader.GetValue("Save", typeof(string)); KeyGesture saveKeyGesture = (KeyGesture)gestureConverter.ConvertFromString(tmp); KeyBinding saveKeyBinding = new KeyBinding(new RelayCommand(o => { FileManager.Save(empList, depList); }, o => true), saveKeyGesture); InputBindings.Add(saveKeyBinding); } catch { } try { string tmp = (string)reader.GetValue("Load", typeof(string)); gestureConverter = new KeyGestureConverter(); KeyGesture loadKeyGesture = (KeyGesture)gestureConverter.ConvertFromString(tmp); KeyBinding loadKeyBinding = new KeyBinding(new RelayCommand(o => { FileManager.Load(empList, depList); }, o => true), loadKeyGesture); InputBindings.Add(loadKeyBinding); } catch { } try { string tmp = (string)reader.GetValue("Plugins", typeof(string)); gestureConverter = new KeyGestureConverter(); KeyGesture pluginsKeyGesture = (KeyGesture)gestureConverter.ConvertFromString(tmp); KeyBinding pluginsKeyBinding = new KeyBinding(new RelayCommand(o => { PluginMenu window = new PluginMenu(mainWindow.pluginList); window.Show(); }, o => true), pluginsKeyGesture); InputBindings.Add(pluginsKeyBinding); } catch { } try { string tmp = (string)reader.GetValue("Esc", typeof(string)); gestureConverter = new KeyGestureConverter(); KeyGesture escKeyGesture = (KeyGesture)gestureConverter.ConvertFromString(tmp); KeyBinding escKeyBinding = new KeyBinding(new RelayCommand(o => { MinHeight = 0; var animation = new DoubleAnimation(); animation.From = Height; animation.To = MinHeight; animation.Duration = TimeSpan.FromSeconds(0.5); animation.Completed += Window_Closed; this.BeginAnimation(HeightProperty, animation); }, o => true), escKeyGesture); InputBindings.Add(escKeyBinding); } catch { } empList = _empList; depList = _depList; window = _window; mainWindow = _mainWindow; int[] day = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; string[] month = new string[] { "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" }; List <int> year = new List <int>(); int currentDate = DateTime.Today.Year; for (int i = 0; currentDate >= 1982; i++) { year.Add(currentDate); currentDate--; } employmentDay.ItemsSource = day; employmentMonth.ItemsSource = month; employmentYear.ItemsSource = year; dismissalDay.ItemsSource = day; dismissalMonth.ItemsSource = month; dismissalYear.ItemsSource = year; empDepartment.ItemsSource = depList.depManager; empBoss.ItemsSource = empList.empManager; empSubWorkers.ItemsSource = empList.empManager; foreach (Employee item in empList.empManager) { employeeList.Items.Add(item); } }
private void button1_Click(object sender, EventArgs e) { //transaction using (SqlConnection connection1 = new SqlConnection(aps.GetValue("myconnection", typeof(string)).ToString())) { connection1.Open(); // Start a local transaction. SqlTransaction sqlTran = connection1.BeginTransaction(); // Enlist a command in the current transaction. SqlCommand command = connection1.CreateCommand(); command.Transaction = sqlTran; { try { Connect(); ShowStatusBar(string.Empty, true); ICollection <MachineInfo> machineInfoCollection = manipulator.GetLogData(objZkeeper, int.Parse(tbxMachineNumber.Text.Trim())); List <MachineInfo> lstMachineInfo = machineInfoCollection.ToList(); DataTable dt = bllGetAttendanceData.GetLastAttendanceLogPull(); DateTime LastPulledDateTime; DateTime LastPulledDateOnly; var todaysDateTime = DateTime.Now; if (dt.Rows.Count > 0) { LastPulledDateTime = Convert.ToDateTime(dt.Rows[0]["LastPulledDateTime"]); LastPulledDateOnly = Convert.ToDateTime(Convert.ToDateTime(dt.Rows[0]["LastPulledDateTime"]).ToShortDateString()); } else { LastPulledDateTime = Convert.ToDateTime(lstMachineInfo.Where(x => Convert.ToDateTime(x.DateTimeRecord) < DateTime.Now).OrderBy(x => x.DateTimeRecord).FirstOrDefault().DateTimeRecord); LastPulledDateOnly = Convert.ToDateTime(LastPulledDateTime.ToShortDateString()); } var newAttendanceRecords = lstMachineInfo.Where(x => Convert.ToDateTime(x.DateTimeRecord) >= LastPulledDateTime).ToList(); int daysGap = Convert.ToInt32((todaysDateTime - LastPulledDateTime).TotalDays); DataTable allUsers = bllGetAttendanceData.GetAllUser(); for (int i = 0; i <= daysGap; i++) { var DaywiseAttendanceRecords = newAttendanceRecords.Where(x => Convert.ToDateTime(x.DateOnlyRecord) == LastPulledDateOnly.AddDays(i)); if (DaywiseAttendanceRecords.Count() > 0 && allUsers.Rows.Count > 0) { for (int j = 0; j < allUsers.Rows.Count; j++) { int personId = Convert.ToInt32(allUsers.Rows[j]["PersonID"]); if (i == 0) { DataTable logData = bllGetAttendanceData.GetPersonLogDataByDate(personId, LastPulledDateOnly); if (logData.Rows.Count > 0) { var UserwiseLastAttendancerecords = DaywiseAttendanceRecords.Where(x => x.IndRegID == personId).LastOrDefault(); if (UserwiseLastAttendancerecords != null) { int val = bllGetAttendanceData.UpdateLogData(personId, UserwiseLastAttendancerecords.TimeOnlyRecord.ToShortTimeString()); } } else { //insert var UserwiseFirstAttendancerecords = DaywiseAttendanceRecords.Where(x => x.IndRegID == personId).FirstOrDefault(); var UserwiseLastAttendancerecords = DaywiseAttendanceRecords.Where(x => x.IndRegID == personId).LastOrDefault(); if (UserwiseFirstAttendancerecords != null && UserwiseLastAttendancerecords != null) { DeviceRecord dr = new DeviceRecord(); dr.PersonalId = personId; dr.AttendanceDate = UserwiseFirstAttendancerecords.DateOnlyRecord; dr.AttendanceDateTime = Convert.ToDateTime(UserwiseFirstAttendancerecords.DateTimeRecord); dr.InTime = UserwiseFirstAttendancerecords.TimeOnlyRecord.ToShortTimeString(); dr.OutTime = UserwiseLastAttendancerecords.TimeOnlyRecord.ToShortTimeString(); int a = bllGetAttendanceData.Insert(dr); } } } else { var UserwiseFirstAttendancerecords = DaywiseAttendanceRecords.Where(x => x.IndRegID == personId).FirstOrDefault(); var UserwiseLastAttendancerecords = DaywiseAttendanceRecords.Where(x => x.IndRegID == personId).LastOrDefault(); if (UserwiseFirstAttendancerecords != null && UserwiseLastAttendancerecords != null) { DeviceRecord dr = new DeviceRecord(); dr.PersonalId = personId; dr.AttendanceDate = UserwiseFirstAttendancerecords.DateOnlyRecord; dr.AttendanceDateTime = Convert.ToDateTime(UserwiseFirstAttendancerecords.DateTimeRecord); dr.InTime = UserwiseFirstAttendancerecords.TimeOnlyRecord.ToShortTimeString(); dr.OutTime = UserwiseLastAttendancerecords.TimeOnlyRecord.ToShortTimeString(); int a = bllGetAttendanceData.Insert(dr); } } } } } int b = bllGetAttendanceData.InsertLatestPullRecord(todaysDateTime); sqlTran.Commit(); DisplayListOutput("Attendance pulled sucessfully"); } catch (Exception ex) { sqlTran.Rollback(); DisplayListOutput(ex.Message); } } } }
public static void Main(string[] args) { // read credentials and settings from app.config file var configReader = new AppSettingsReader(); // the base URL should be stricly the instance name // --no "/Relativity" appended at the end string url = configReader.GetValue("RelativityBaseURI", typeof(string)).ToString(); string user = configReader.GetValue("RelativityUserName", typeof(string)).ToString(); string password = configReader.GetValue("RelativityPassword", typeof(string)).ToString(); int workspaceId = 0; string workspaceIdAsStr = configReader.GetValue("WorkspaceId", typeof(string)).ToString(); if (!String.IsNullOrEmpty(workspaceIdAsStr)) { workspaceId = Int32.Parse(workspaceIdAsStr); } if (workspaceId == 0) { Console.WriteLine("Invalid workspace ID."); return; } var config = new ExportApiHelperConfig { BlockSize = 1000, QueryRequest = new QueryRequest { Fields = new FieldRef[] { new FieldRef { Name = "Control Number" }, new FieldRef { Name = "Extracted Text" } }, // this is the cutoff value--anything greater // than this many bytes will be streamed MaxCharactersForLongTextValues = 1000 * 1024 }, WorkspaceId = workspaceId, RelativityUrl = new Uri(url), Credentials = new UsernamePasswordCredentials(user, password), ScaleFactor = 8 }; ExportApiHelper exportHelper = config.Create(); var cts = new System.Threading.CancellationTokenSource(); // Extracted Text is the second field in the config.Fields collection int extractedTextIndex = 1; exportHelper.Run(new MyExportHandler(extractedTextIndex), cts.Token); Pause(); }
public IHttpActionResult GuessAnswer(GuessAnswer guessAnswer) { var settingsReader = new AppSettingsReader(); var consumerKey = settingsReader.GetValue("TwitterKey", typeof(string)).ToString(); var consumerSecret = settingsReader.GetValue("TwitterSecret", typeof(string)).ToString(); var service = new TwitterService(consumerKey, consumerSecret); service.AuthenticateWith(guessAnswer.Token, guessAnswer.TokenSecret); var response = service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { ScreenName = guessAnswer.Screenname }) ?? new List <TwitterStatus>(); var statuses = new List <Tweets>(); var missionName = string.Empty; var result = false; foreach (var twitterStatus in response) { if (twitterStatus.Entities == null) { continue; } var urls = twitterStatus.Entities.Media.Select(rawLinks => rawLinks.MediaUrl).ToList(); foreach (var media in twitterStatus.Entities.Media) { if (media.MediaType != TwitterMediaType.Photo) { continue; } using (var client = new WebClient()) { var image = client.DownloadData(media.MediaUrl); var ms = new MemoryStream(image); var bmp = new Bitmap(Image.FromStream(ms)); var extracted = Steganography.Extract(bmp); var decryptedMessage = Encryption.Decrypt(extracted); if (string.IsNullOrEmpty(decryptedMessage)) { continue; } var embedded = new JavaScriptSerializer().Deserialize <EmbeddedDetails>(decryptedMessage); if (embedded.FinalMystery != null) { if (embedded.FinalMystery.ToLower().Equals(guessAnswer.Guess.ToLower())) { result = true; missionName = embedded.Mystery; } } } } } if (result) { service.AuthenticateWith(guessAnswer.Token, guessAnswer.TokenSecret); service.SendTweet(new SendTweetOptions { Status = $"{guessAnswer.Screenname} mission '{missionName}' accomplished!", }); return(Ok(new GuessResult { message = "Congratulations! You win!" })); } return(Ok(new GuessResult { message = "Incorrect, try again." })); }
public static string GetSlackApiUrl() { AppSettingsReader configurationAppSettings = new AppSettingsReader(); return((string)configurationAppSettings.GetValue(ConfigKeys.SlackApiUrl, typeof(string))); }
public ActionResult UploadFiles() { AppSettingsReader reader = new AppSettingsReader(); string storageroot = reader.GetValue("storageroot", typeof(string)).ToString(); if (Request.Files == null || Request.Files.Count == 0) { return(Json(new { message = "请选择文件" })); } for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; if (file.ContentLength == 0) { return(Json(new { message = "文件不合法" })); } int size = file.ContentLength / 1024; if (size > 10240) { return(Json(new { message = "单个文件大小超出限制,请不要超过10M" })); } } string date = DateTime.Now.ToString("yyyyMMdd"); string applicationid = User.Identity.GetAccount().RootApplicationId; string path = Path.Combine(storageroot, applicationid, date); if (Directory.Exists(path) == false) { Directory.CreateDirectory(path); } List <object> list = new List <object>(); for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; string newfilename = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName); string fileName = Path.Combine(path, newfilename); try { file.SaveAs(fileName); //文件信息存入数据库 AttachmentInfo info = new AttachmentInfo() { Name = newfilename, Path = fileName, Size = file.ContentLength }; SaveAttachmentInfo(info); list.Add(new { name = file.FileName, url = Url.Action("Transmit", "upload", new { id = info.Id }, Request.Url.Scheme), size = GetFileSizeFriendly(file.ContentLength) }); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); return(Json(new { message = "上传出错" })); } } return(Json(new { message = "ok", urls = list })); }
public static string GetString(string str) { AppSettingsReader config = new AppSettingsReader(); return((string)(config.GetValue(str, typeof(string)))); }
public static string GetPassword() { AppSettingsReader reader = new AppSettingsReader(); return(reader.GetValue("Password", typeof(string)).ToString()); }
public static string GetUserName() { AppSettingsReader reader = new AppSettingsReader(); return(reader.GetValue("UserName", typeof(string)).ToString()); }
public static string GetAccessToken() { AppSettingsReader reader = new AppSettingsReader(); return(reader.GetValue("AccessToken", typeof(string)).ToString()); }
public static string GetCoreID() { AppSettingsReader reader = new AppSettingsReader(); return(reader.GetValue("CoreID", typeof(string)).ToString()); }
private string getASRV(string key) { AppSettingsReader asr = new AppSettingsReader(); string v = asr.GetValue(key, typeof(string)) as string; return v; }
public bool Send(long deviceId, long count = 1) { Message message = null; var deviceEndpointId = String.Empty; using (var db = new IoTContext()) { var device = db.Devices.Find(deviceId); deviceEndpointId = device.DeviceEndpointId; message = new Message { ClientId = Guid.NewGuid().ToString(), Source = device.DeviceEndpointId, Destination = "", Priority = "LOW", Reliability = "BEST_EFFORT", EventTime = (long)((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds), Sender = "", Type = "DATA", Payload = new CoffeePayload { Format = "urn:com:keurig:coffee:machine:attributes", Data = new CoffeeData { BeansLevel = 10, WaterLevel = 80, Latitude = 37.39, Longitude = -121.95 } } }; } var messages = new List <Message> { message }; var data = JsonConvert.SerializeObject(messages, Newtonsoft.Json.Formatting.Indented); Console.WriteLine("Message: " + data); var bearerToken = new Authentication().GetBearerToken(Scope.General, deviceId); var appSettingsReader = new AppSettingsReader(); var url = appSettingsReader.GetValue("serverBase", typeof(string)).ToString() + appSettingsReader.GetValue("messEndpoint", typeof(string)).ToString(); //Message messageResponse = null; for (var i = 0; i < count; i++) { using (var httpClient = new HttpClient()) { var content = new StringContent(data, Encoding.UTF8, "application/json"); content.Headers.Clear(); content.Headers.Add("Content-Type", "application/json"); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken.AccessToken); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Add("X-EndpointId", deviceEndpointId); Console.WriteLine(url); HttpResponseMessage response = httpClient.PostAsync(url, content).Result; IJsonSerializer serializer = new JsonNetSerializer(); Console.WriteLine($"Response Code: {response.StatusCode}"); using (var responseStream = response.Content.ReadAsStreamAsync().Result) { if (responseStream == null) { return(false); } using (var streamReader = new StreamReader(responseStream)) { var responseContent = streamReader.ReadToEnd(); Console.WriteLine(responseContent); //messageResponse = serializer.Deserialize<Message>(responseContent); } } } } return(true); }
/// <summary> /// return from web.config [key] value /// </summary> /// <param name="key">config app key</param> /// <returns></returns> public static string GetConfigKey(string key) { AppSettingsReader configurationAppSettings = new AppSettingsReader(); return((string)configurationAppSettings.GetValue(key, typeof(string))); }
public IHttpActionResult GetFeedPath(string token, string tokenSecret, double latitude, double longitude, string screenname) { var settingsReader = new AppSettingsReader(); var consumerKey = settingsReader.GetValue("TwitterKey", typeof(string)).ToString(); var consumerSecret = settingsReader.GetValue("TwitterSecret", typeof(string)).ToString(); var service = new TwitterService(consumerKey, consumerSecret); service.AuthenticateWith(token, tokenSecret); var response = service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { ScreenName = screenname, Count = 5 }) ?? new List <TwitterStatus>(); var statuses = new List <Tweets>(); foreach (var twitterStatus in response) { if (twitterStatus.Entities == null) { continue; } var urls = twitterStatus.Entities.Media.Select(rawLinks => rawLinks.MediaUrl).ToList(); var encrypted = false; foreach (var media in twitterStatus.Entities.Media) { if (media.MediaType != TwitterMediaType.Photo) { continue; } using (var client = new WebClient()) { var image = client.DownloadData(media.MediaUrl); var ms = new MemoryStream(image); var bmp = new Bitmap(Image.FromStream(ms)); var extracted = Steganography.Extract(bmp); var decryptedMessage = Encryption.Decrypt(extracted); if (string.IsNullOrEmpty(decryptedMessage)) { continue; } var embedded = new JavaScriptSerializer().Deserialize <EmbeddedDetails>(decryptedMessage); var currentLocation = new GeoCoordinate { Latitude = latitude, Longitude = longitude }; var requiredLocation = new GeoCoordinate { Latitude = embedded.Latitude, Longitude = embedded.Longitude }; if (!GeoLocation.WithinRadius(currentLocation, requiredLocation)) { continue; } embedded.FinalMystery = null; encrypted = true; statuses.Add(new Tweets { Text = twitterStatus.Text, ScreenName = twitterStatus.User.ScreenName, Name = twitterStatus.User.Name, MediaUrls = urls, ProfileImageUrl = twitterStatus.User.ProfileImageUrl, DecryptedMessage = embedded }); } } if (!encrypted) { statuses.Add(new Tweets { Text = twitterStatus.Text, ScreenName = twitterStatus.User.ScreenName, Name = twitterStatus.User.Name, MediaUrls = urls, ProfileImageUrl = twitterStatus.User.ProfileImageUrl }); } } return(Ok(statuses)); }
public static String GetValue(String key) { return((string)configurationAppSettings.GetValue(key, typeof(string))); }
/// <summary> /// 初始化引擎 /// </summary> private void InitEngines() { //读取配置文件 AppSettingsReader reader = new AppSettingsReader(); string appId = (string)reader.GetValue("APP_ID", typeof(string)); string sdkKey64 = (string)reader.GetValue("SDKKEY64", typeof(string)); string sdkKey32 = (string)reader.GetValue("SDKKEY32", typeof(string)); var is64CPU = Environment.Is64BitProcess; if (is64CPU) { if (string.IsNullOrWhiteSpace(appId) || string.IsNullOrWhiteSpace(sdkKey64)) { chooseMultiImgBtn.Enabled = false; matchBtn.Enabled = false; btnClearFaceList.Enabled = false; chooseImgBtn.Enabled = false; MessageBox.Show("请在App.config配置文件中先配置APP_ID和SDKKEY64!"); return; } } else { if (string.IsNullOrWhiteSpace(appId) || string.IsNullOrWhiteSpace(sdkKey32)) { chooseMultiImgBtn.Enabled = false; matchBtn.Enabled = false; btnClearFaceList.Enabled = false; chooseImgBtn.Enabled = false; MessageBox.Show("请在App.config配置文件中先配置APP_ID和SDKKEY32!"); return; } } //激活引擎 如出现错误,1.请先确认从官网下载的sdk库已放到对应的bin中,2.当前选择的CPU为x86或者x64 int retCode = 0; try { retCode = ASFFunctions.ASFActivation(appId, is64CPU ? sdkKey64 : sdkKey32); } catch (Exception ex) { chooseMultiImgBtn.Enabled = false; matchBtn.Enabled = false; btnClearFaceList.Enabled = false; chooseImgBtn.Enabled = false; if (ex.Message.IndexOf("无法加载 DLL") > -1) { MessageBox.Show("请将sdk相关DLL放入bin对应的x86或x64下的文件夹中!"); } else { MessageBox.Show("激活引擎失败!"); } return; } Console.WriteLine("Activate Result:" + retCode); //初始化引擎 uint detectMode = DetectionMode.ASF_DETECT_MODE_IMAGE; //检测脸部的角度优先值 int detectFaceOrientPriority = ASF_OrientPriority.ASF_OP_0_HIGHER_EXT; //人脸在图片中所占比例,如果需要调整检测人脸尺寸请修改此值,有效数值为2-32 int detectFaceScaleVal = 16; //最大需要检测的人脸个数 int detectFaceMaxNum = 5; //引擎初始化时需要初始化的检测功能组合 int combinedMask = FaceEngineMask.ASF_FACE_DETECT | FaceEngineMask.ASF_FACERECOGNITION | FaceEngineMask.ASF_AGE | FaceEngineMask.ASF_GENDER | FaceEngineMask.ASF_FACE3DANGLE; //初始化引擎,正常值为0,其他返回值请参考http://ai.arcsoft.com.cn/bbs/forum.php?mod=viewthread&tid=19&_dsign=dbad527e retCode = ASFFunctions.ASFInitEngine(detectMode, detectFaceOrientPriority, detectFaceScaleVal, detectFaceMaxNum, combinedMask, ref pEngine); Console.WriteLine("InitEngine Result:" + retCode); AppendText((retCode == 0) ? "引擎初始化成功!\n" : string.Format("引擎初始化失败!错误码为:{0}\n", retCode)); if (retCode != 0) { chooseMultiImgBtn.Enabled = false; matchBtn.Enabled = false; btnClearFaceList.Enabled = false; chooseImgBtn.Enabled = false; } }
public event setResultValue setFormResultValue; //第二步:声明一个委托类型的事件 /// <summary> /// 激活并初始化引擎 /// </summary> private void ActiveAndInitEngines() { //读取配置文件中的 APP_ID 和 SDKKEY AppSettingsReader reader = new AppSettingsReader(); string appId = (string)reader.GetValue("APP_ID", typeof(string)); string sdkKey = (string)reader.GetValue("SDKKEY", typeof(string)); int retCode = 0; //激活引擎 try { retCode = ASFFunctions.ASFActivation(appId, sdkKey); } catch (Exception ex) { //异常处理 return; } #region 图片引擎pImageEngine初始化 //初始化引擎 uint detectMode = DetectionMode.ASF_DETECT_MODE_IMAGE; //检测脸部的角度优先值 int detectFaceOrientPriority = ASF_OrientPriority.ASF_OP_0_HIGHER_EXT; //人脸在图片中所占比例,如果需要调整检测人脸尺寸请修改此值,有效数值为2-32 int detectFaceScaleVal = 16; //最大需要检测的人脸个数 int detectFaceMaxNum = 5; //引擎初始化时需要初始化的检测功能组合 int combinedMask = FaceEngineMask.ASF_FACE_DETECT | FaceEngineMask.ASF_FACERECOGNITION | FaceEngineMask.ASF_AGE | FaceEngineMask.ASF_GENDER | FaceEngineMask.ASF_FACE3DANGLE; //初始化引擎,正常值为0,其他返回值请参考http://ai.arcsoft.com.cn/bbs/forum.php?mod=viewthread&tid=19&_dsign=dbad527e retCode = ASFFunctions.ASFInitEngine(detectMode, detectFaceOrientPriority, detectFaceScaleVal, detectFaceMaxNum, combinedMask, ref pImageEngine); if (retCode == 0) { lbl_msg.Text = ("图片引擎初始化成功!\n"); } else { lbl_msg.Text = (string.Format("图片引擎初始化失败!错误码为:{0}\n", retCode)); } #endregion #region 初始化视频模式下人脸检测引擎 uint detectModeVideo = DetectionMode.ASF_DETECT_MODE_VIDEO; int combinedMaskVideo = FaceEngineMask.ASF_FACE_DETECT | FaceEngineMask.ASF_FACERECOGNITION; retCode = ASFFunctions.ASFInitEngine(detectModeVideo, detectFaceOrientPriority, detectFaceScaleVal, detectFaceMaxNum, combinedMaskVideo, ref pVideoEngine); if (retCode == 0) { lbl_msg.Text = ("视频引擎初始化成功!\n"); } else { lbl_msg.Text = (string.Format("视频引擎初始化失败!错误码为:{0}\n", retCode)); } #endregion #region 视频专用FR引擎 detectFaceMaxNum = 1; combinedMask = FaceEngineMask.ASF_FACERECOGNITION | FaceEngineMask.ASF_FACE3DANGLE | FaceEngineMask.ASF_LIVENESS; retCode = ASFFunctions.ASFInitEngine(detectMode, detectFaceOrientPriority, detectFaceScaleVal, detectFaceMaxNum, combinedMask, ref pVideoImageEngine); Console.WriteLine("InitVideoEngine Result:" + retCode); if (retCode == 0) { lbl_msg.Text = ("视频专用FR引擎初始化成功!\n"); } else { lbl_msg.Text = (string.Format("视频专业FR引擎初始化失败!错误码为:{0}\n", retCode)); } // 摄像头初始化 filterInfoCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice); lbl_msg.Text = (string.Format("摄像头初始化完成...\n")); #endregion }
public static string GetValue(string key) { return((string)reader.GetValue(key, typeof(string))); }
public DataSet RetriveTransactions() { int rowCnt = 1; int rowCnt2 = 1; string ltrTot, ltrTot2, amnt, amnt2, vatAmnt, vatAmnt2, chldCust, chldCust2, rebate, rebate2; DataSet ds = new DataSet(); using (con = new SqlConnection(this.conString)) { try { con.Open(); fileName = (string)apReader.GetValue("FileName", typeof(string)) + "_" + DateTime.Now.ToString("yyyyMMdd") + ".xls"; int counter = 0; counter += 1; QueryString = "sp_KWS_Transactions"; SqlCommand cmd = new SqlCommand(QueryString, con); cmd.CommandType = CommandType.StoredProcedure; // cmd.Parameters.AddWithValue("depoGuid", Depot); SqlDataAdapter dscmd = new SqlDataAdapter(cmd); DataSet ds1 = new DataSet(); dscmd.Fill(ds1); foreach (DataTable table in ds1.Tables) { using (ExcelPackage excel = new ExcelPackage()) { excel.Workbook.Worksheets.Add("Introduction"); excel.Workbook.Worksheets.Add("Organisation statement"); //excel.Workbook.Worksheets.Add("Purchase Orders"); // Target a worksheet var worksheet = excel.Workbook.Worksheets["Introduction"]; var worksheetTransSalesOrder = excel.Workbook.Worksheets["Organisation statement"]; worksheetTransSalesOrder.Cells[rowCnt, 2].LoadFromDataTable(table, true); formatSheetColumns(table, worksheet, worksheetTransSalesOrder, rowCnt); rowCnt = worksheetTransSalesOrder.Dimension.End.Row; rowCnt2 = worksheetTransSalesOrder.Dimension.End.Row; rowCnt += 1; string rCount = Convert.ToString(rowCnt); worksheetTransSalesOrder.Cells["O1:O" + rCount].Style.Numberformat.Format = "#,##0.00"; worksheetTransSalesOrder.Cells["R1:R" + rCount].Style.Numberformat.Format = "R#,##0.00"; worksheetTransSalesOrder.Cells["S1:S" + rCount].Style.Numberformat.Format = "R#,##0.00"; worksheetTransSalesOrder.Cells["T1:T" + rCount].Style.Numberformat.Format = "R#,##0.00"; worksheetTransSalesOrder.Cells["U1:U" + rCount].Style.Numberformat.Format = "R#,##0.00"; worksheetTransSalesOrder.Cells["AA1:AA" + rCount].Style.Numberformat.Format = "R#,##0.00"; ltrTot = 'O' + rowCnt.ToString(); ltrTot2 = 'O' + rowCnt2.ToString(); amnt = 'R' + rowCnt.ToString(); amnt2 = 'R' + rowCnt2.ToString(); vatAmnt = 'S' + rowCnt.ToString(); vatAmnt2 = 'S' + rowCnt2.ToString(); chldCust = 'T' + rowCnt.ToString(); chldCust2 = 'T' + rowCnt2.ToString(); rebate = 'U' + rowCnt.ToString(); rebate2 = 'U' + rowCnt2.ToString(); worksheetTransSalesOrder.Cells[ltrTot].Formula = "=SUM(O2:" + ltrTot2 + ")"; worksheetTransSalesOrder.Cells[amnt].Formula = "=SUM(R2:" + amnt2 + ")"; worksheetTransSalesOrder.Cells[vatAmnt].Formula = "=SUM(S2:" + vatAmnt2 + ")"; worksheetTransSalesOrder.Cells[chldCust].Formula = "=SUM(T2:" + chldCust2 + ")"; worksheetTransSalesOrder.Cells[rebate].Formula = "=SUM(U2:" + rebate2 + ")"; worksheetTransSalesOrder.Cells["O1:O" + rCount].AutoFitColumns(); worksheetTransSalesOrder.Cells[ltrTot].Style.Border.Top.Style = ExcelBorderStyle.Double; worksheetTransSalesOrder.Cells[amnt].Style.Border.Top.Style = ExcelBorderStyle.Double; worksheetTransSalesOrder.Cells[vatAmnt].Style.Border.Top.Style = ExcelBorderStyle.Double; worksheetTransSalesOrder.Cells[chldCust].Style.Border.Top.Style = ExcelBorderStyle.Double; worksheetTransSalesOrder.Cells[rebate].Style.Border.Top.Style = ExcelBorderStyle.Double; worksheetTransSalesOrder.Cells[ltrTot].Style.Font.Color.SetColor(Color.Navy); worksheetTransSalesOrder.Cells[ltrTot].Style.Font.Bold = true; worksheetTransSalesOrder.Cells[ltrTot].Style.Font.Size = 12; worksheetTransSalesOrder.Cells[amnt].Style.Font.Color.SetColor(Color.Navy); worksheetTransSalesOrder.Cells[amnt].Style.Font.Bold = true; worksheetTransSalesOrder.Cells[amnt].Style.Font.Size = 12; worksheetTransSalesOrder.Cells[vatAmnt].Style.Font.Color.SetColor(Color.Navy); worksheetTransSalesOrder.Cells[vatAmnt].Style.Font.Bold = true; worksheetTransSalesOrder.Cells[vatAmnt].Style.Font.Size = 12; worksheetTransSalesOrder.Cells[chldCust].Style.Font.Color.SetColor(Color.Navy); worksheetTransSalesOrder.Cells[chldCust].Style.Font.Bold = true; worksheetTransSalesOrder.Cells[chldCust].Style.Font.Size = 12; worksheetTransSalesOrder.Cells[rebate].Style.Font.Color.SetColor(Color.Navy); worksheetTransSalesOrder.Cells[rebate].Style.Font.Bold = true; worksheetTransSalesOrder.Cells[rebate].Style.Font.Size = 12; root = @"C:\IBS_Dev\IBS_KWS_DailyTransaction_Extract_Console\" + EntityName + ""; // If directory does not exist, create it. if (!Directory.Exists(root)) { Directory.CreateDirectory(root); } path = root + @"\" + fileName; FileInfo excelFile = new FileInfo(path); excel.SaveAs(excelFile); } } con.Close(); //Get All billed transaction for the previos business day //End //Send email Start emailer.SendNotifyMailUser(path, toEmailAddress); //con.Open(); //QueryString = "sp_Update_Billed_Transactions"; //SqlCommand cmd1 = new SqlCommand(QueryString, con); //cmd1.CommandType = CommandType.StoredProcedure; //cmd1.ExecuteNonQuery(); //con.Close(); ////Flag all sent Records. To avoid Duplicates } catch (Exception ex) { emailer.SendNotifyErrorMail("Error", ex.Message); } } return(ds); }
public static int GetIntValue(string settingName) { return(int.Parse(Settings.GetValue(settingName, type: Type.GetType("System.Int32")).ToString())); }
private void refreshMenu() { reader = new AppSettingsReader(); try { readConfig = (string)reader.GetValue("newFile", typeof(string)); newButton.InputGestureText = readConfig; hotkey = (KeyGesture) new KeyGestureConverter().ConvertFromString(readConfig); KeyBinding newFileHotkey = new KeyBinding(new RelayCommand(o => { newButton.RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent)); }, o => true), hotkey); InputBindings.Add(newFileHotkey); readConfig = (string)reader.GetValue("openFile", typeof(string)); openButton.InputGestureText = readConfig; hotkey = (KeyGesture) new KeyGestureConverter().ConvertFromString(readConfig); KeyBinding openFileHotkey = new KeyBinding(new RelayCommand(o => { openButton.RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent)); }, o => true), hotkey); InputBindings.Add(openFileHotkey); readConfig = (string)reader.GetValue("saveFile", typeof(string)); saveButton.InputGestureText = readConfig; hotkey = (KeyGesture) new KeyGestureConverter().ConvertFromString(readConfig); KeyBinding saveFileHotkey = new KeyBinding(new RelayCommand(o => { saveButton.RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent)); }, o => true), hotkey); InputBindings.Add(saveFileHotkey); readConfig = (string)reader.GetValue("closeWindow", typeof(string)); exitButton.InputGestureText = readConfig; hotkey = (KeyGesture) new KeyGestureConverter().ConvertFromString(readConfig); KeyBinding closeWindowHotkey = new KeyBinding(new RelayCommand(o => { if (Directory.Exists(Directory.GetCurrentDirectory() + @"\Buffer")) { Directory.Delete(Directory.GetCurrentDirectory() + @"\Buffer", true); } Environment.Exit(1); }, o => true), hotkey); InputBindings.Add(closeWindowHotkey); readConfig = (string)reader.GetValue("pluginsMenu", typeof(string)); openPlMenuButton.InputGestureText = readConfig; hotkey = (KeyGesture) new KeyGestureConverter().ConvertFromString(readConfig); KeyBinding pluginsMenuHotkey = new KeyBinding(new RelayCommand(o => { Plugins pluginsWindow = new Plugins(this); pluginsWindow.ShowDialog(); }, o => true), hotkey); InputBindings.Add(pluginsMenuHotkey); readConfig = (string)reader.GetValue("runPlugins", typeof(string)); runButton.InputGestureText = readConfig; hotkey = (KeyGesture) new KeyGestureConverter().ConvertFromString(readConfig); KeyBinding runPluginsHotkey = new KeyBinding(new RelayCommand(o => { Plugins pluginsWindow = new Plugins(this); pluginsWindow.JustRun(); }, o => true), hotkey); InputBindings.Add(runPluginsHotkey); readConfig = (string)reader.GetValue("settings", typeof(string)); settingsButton.InputGestureText = readConfig; hotkey = (KeyGesture) new KeyGestureConverter().ConvertFromString(readConfig); KeyBinding settingsHotkey = new KeyBinding(new RelayCommand(o => { settingsButton.RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent)); }, o => true), hotkey); InputBindings.Add(settingsHotkey); } catch (Exception) { MessageBox.Show("Config file not loaded, loaded standart settings", "Warning", MessageBoxButton.OK, MessageBoxImage.Error); hotkey = (KeyGesture) new KeyGestureConverter().ConvertFromString("Ctrl+N"); newButton.InputGestureText = "Ctrl+N"; KeyBinding newFileHotkey = new KeyBinding(new RelayCommand(o => { newButton.RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent)); }, o => true), hotkey); InputBindings.Add(newFileHotkey); openButton.InputGestureText = "Ctrl+L"; hotkey = (KeyGesture) new KeyGestureConverter().ConvertFromString("Ctrl+L"); KeyBinding openFileHotkey = new KeyBinding(new RelayCommand(o => { openButton.RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent)); }, o => true), hotkey); InputBindings.Add(openFileHotkey); saveButton.InputGestureText = "Ctrl+S"; hotkey = (KeyGesture) new KeyGestureConverter().ConvertFromString("Ctrl+S"); KeyBinding saveFileHotkey = new KeyBinding(new RelayCommand(o => { saveButton.RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent)); }, o => true), hotkey); InputBindings.Add(saveFileHotkey); exitButton.InputGestureText = "Esc"; hotkey = (KeyGesture) new KeyGestureConverter().ConvertFromString("Esc"); KeyBinding closeWindowHotkey = new KeyBinding(new RelayCommand(o => { if (Directory.Exists(Directory.GetCurrentDirectory() + @"\Buffer")) { Directory.Delete(Directory.GetCurrentDirectory() + @"\Buffer", true); } Environment.Exit(1); }, o => true), hotkey); InputBindings.Add(closeWindowHotkey); openPlMenuButton.InputGestureText = "F2"; hotkey = (KeyGesture) new KeyGestureConverter().ConvertFromString("F2"); KeyBinding pluginsMenuHotkey = new KeyBinding(new RelayCommand(o => { Plugins pluginsWindow = new Plugins(this); pluginsWindow.ShowDialog(); }, o => true), hotkey); InputBindings.Add(pluginsMenuHotkey); runButton.InputGestureText = "F1"; hotkey = (KeyGesture) new KeyGestureConverter().ConvertFromString("F1"); KeyBinding runPluginsHotkey = new KeyBinding(new RelayCommand(o => { Plugins pluginsWindow = new Plugins(this); pluginsWindow.JustRun(); }, o => true), hotkey); InputBindings.Add(runPluginsHotkey); settingsButton.InputGestureText = "F9"; hotkey = (KeyGesture) new KeyGestureConverter().ConvertFromString("F9"); KeyBinding settingsHotkey = new KeyBinding(new RelayCommand(o => { settingsButton.RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent)); }, o => true), hotkey); InputBindings.Add(settingsHotkey); } }
private void button1_Click(object sender, EventArgs e) { Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook wk; Microsoft.Office.Interop.Excel.Worksheet mysheet; int temprow; List <string> mygonghaolist = new List <string>(); Range myrng; object[] myobj; System.Data.DataTable mytb = new System.Data.DataTable(); if (app == null) { MessageBox.Show("Excel 没有正常打开。 "); return; } app.DisplayAlerts = false; AppSettingsReader myread = new AppSettingsReader(); string filedir; try { filedir = myread.GetValue("directory", Type.GetType("System.String")).ToString(); } catch (Exception ex) { MessageBox.Show(ex.Message); app.Quit(); return; } wk = app.Workbooks.Open(filedir + "月销售利润表模板(外贸).xls"); if (wk == null) { MessageBox.Show("模板文件没找到!"); return; } try { 销售成本结算DAL dal1 = new 销售成本结算DAL(); SqlDataReader dr = dal1.get外贸利润表(mydate.Value); myobj = new object[29]; mysheet = wk.Worksheets["外贸销售利润表"]; if (dr.HasRows) { temprow = 5; while (dr.Read()) { dr.GetValues(myobj); myrng = mysheet.Range[mysheet.Cells[temprow, 1], mysheet.Cells[temprow, 29]]; myrng.NumberFormatLocal = "0.00"; myrng.Value2 = myobj; temprow++; } } dr.Close(); if (saveFileDialog1.ShowDialog() == DialogResult.OK) { string myfilename = saveFileDialog1.FileName; wk.SaveAs(myfilename); } wk.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { app.Quit(); MessageBox.Show("导出完成!"); } }
private string GetClientIp() { var appSettings = new AppSettingsReader(); return((string)appSettings.GetValue("ClientIp", typeof(string))); }
private int GetClientPort() { var appSettings = new AppSettingsReader(); return((int)appSettings.GetValue("ClientPort", typeof(int))); }
public static string LeerParametro(string pNombreParam) { string Resultado; //obtener la ruta del archivo de configuracion AppSettingsReader _configReader = new AppSettingsReader(); // Leer el valor de configuracion Resultado = _configReader.GetValue(pNombreParam, typeof(string)).ToString(); if (Resultado == null) { Resultado = ""; } return Resultado; }
public static string GetPath() { AppSettingsReader asr = new AppSettingsReader(); string v = asr.GetValue("path", typeof(string)) as string; return v; }
public IList <TFSProductBacklogItem> GetPBIList() { IList <TFSProductBacklogItem> tfsPBIList = new List <TFSProductBacklogItem>(); try { //create a wiql object and build our query Wiql wiql = new Wiql() { Query = "Select [ID],[Title],[ServiceNow InternalId] " + "From WorkItems " + "Where [Work Item Type] = 'Product Backlog Item' " + "And [ServiceNow InternalId] <> '' " + "And (([State] = 'Approved') Or ([State] = 'Committed'))" }; string serverUrl = (string)configReader.GetValue("TFSServerUrl", typeof(string)); //Initialise the connection to the TFS server VssConnection connection = new VssConnection(new Uri(serverUrl), new VssCredentials(new WindowsCredential(true))); //create instance of work item tracking http client using (WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient <WorkItemTrackingHttpClient>()) { //execute the query to get the list of work items in teh results WorkItemQueryResult workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result; //Some error handling if (workItemQueryResult.WorkItems.Count() != 0) { //need to get the list work item Ids to put them into array List <int> list = new List <int>(); foreach (var item in workItemQueryResult.WorkItems) { list.Add(item.Id); } int[] arr = list.ToArray(); //build a list of the fields we want to see string[] fields = new string[5]; fields[0] = "System.Id"; fields[1] = "System.Title"; fields[2] = "System.State"; fields[3] = "FET.SNEnhancement"; fields[4] = "FET.SNInternalId"; var workItemList = workItemTrackingHttpClient.GetWorkItemsAsync(arr, fields, workItemQueryResult.AsOf).Result; foreach (var workItem in workItemList) { tfsPBIList.Add(new TFSProductBacklogItem() { ID = workItem.Id.Value, Title = (string)workItem.Fields[fields[1]], State = (string)workItem.Fields[fields[2]], ServiceNowEnhancement = (string)workItem.Fields[fields[3]], ServiceNowInternalId = (string)workItem.Fields[fields[4]] }); } } } } catch (Exception ex) { logger.Error(ex); } return(tfsPBIList); }
public MainClass() { spoolerAssembly = Assembly.LoadFrom("Micro3DSpooler.exe"); // Load configuration from app.config var reader = new AppSettingsReader(); filamentType = (String)reader.GetValue("filamentType", typeof(String)); printingTemperature = (int)reader.GetValue("printingTemperature", typeof(int)); backlashX = (float)reader.GetValue("backlashX", typeof(float)); backlashY = (float)reader.GetValue("backlashY", typeof(float)); backlashSpeed = (float)reader.GetValue("backlashSpeed", typeof(float)); badOffset = (float)reader.GetValue("badOffset", typeof(float)); badOffsetFrontLeft = (float)reader.GetValue("badOffsetFrontLeft", typeof(float)); badOffsetBackLeft = (float)reader.GetValue("badOffsetBackLeft", typeof(float)); badOffsetFrontRight = (float)reader.GetValue("badOffsetFrontRight", typeof(float)); badOffsetBackRight = (float)reader.GetValue("badOffsetBackRight", typeof(float)); waveBonding = (bool)reader.GetValue("waveBonding", typeof(bool)); }
public Device RegisterDevice(long deviceId) { var username = appSettingsReader.GetValue("username", typeof(string)).ToString(); var password = appSettingsReader.GetValue("password", typeof(string)).ToString(); var url = appSettingsReader.GetValue("serverBase", typeof(string)).ToString() + appSettingsReader.GetValue("regEndpoint", typeof(string)).ToString(); JObject data; using (var db = new IoTContext()) { var device = db.Devices.Where(d => d.Id == deviceId).Include(d => d.Registration).First(); var registration = device.Registration; data = JObject.FromObject(new { hardwareId = registration.HardwareId, sharedSecret = Convert.ToBase64String(Encoding.ASCII.GetBytes(registration.SharedSecret)), name = registration.Name }); registration.Request = data.ToString(); db.SaveChanges(); } String responseContent; using (var httpClient = new HttpClient()) { var content = new StringContent(data.ToString(), Encoding.UTF8, "application/json"); content.Headers.Clear(); content.Headers.Add("Content-Type", "application/json"); String authHeader = System.Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(username + ":" + password)); //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "Bearer " + authHeader); httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + authHeader); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); Console.WriteLine($"Registration URL {url}"); HttpResponseMessage response = httpClient.PostAsync(url, content).Result; IJsonSerializer serializer = new JsonNetSerializer(); var registration = new Registration(); using (var responseStream = response.Content.ReadAsStreamAsync().Result) { if (responseStream == null) { return(null); } using (var streamReader = new StreamReader(responseStream)) { responseContent = streamReader.ReadToEnd(); Console.WriteLine(responseContent); registration = serializer.Deserialize <Registration>(responseContent); Console.WriteLine($"Registration Status: {registration.State}"); } } } using (var db = new IoTContext()) { var device = db.Devices.Where(d => d.Id == deviceId).Include(d => d.Registration).First(); var registration = device.Registration; registration.Response = responseContent; var deviceRSA = new RSACryptoServiceProvider(2048); var deviceRSAXml = deviceRSA.ToXmlString(true); device.RSAKeyXML = deviceRSAXml; db.SaveChanges(); } return(null); }
/// <summary> /// 获取配置文件里appsettings的数据 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetAppsettingStr(string str) { AppSettingsReader appReader = new AppSettingsReader(); return(appReader.GetValue(str, typeof(string)).ToString()); }
protected override void ReadAppConfigInternal(AppSettingsReader asr) { this.ConnectionString = (string)asr.GetValue("PostGisConnectionString", typeof(string)); }