public void DiagnosticsTest() { object[,] actual = ApplicationHelper.Diagnostics(); const int expectedItems = 8; Assert.AreEqual(expectedItems - 1, actual.GetUpperBound(0)); Assert.AreEqual(1, actual.GetUpperBound(1)); for (int i = 0; i < expectedItems - 1; i++) { Debug.Print("{0}: {1}", actual[i, 0], actual[i, 1]); Assert.IsFalse(string.IsNullOrEmpty(actual[i, 0].ToString())); Assert.IsFalse(string.IsNullOrEmpty(actual[i, 1].ToString())); } //When there is a Public Key Token Assert.IsFalse(string.IsNullOrEmpty(actual[expectedItems - 1, 1].ToString())); //When Public Key Token is empty, this is true. //Assert.IsTrue(string.IsNullOrEmpty(actual[expectedItems - 1, 1].ToString())); }
public IHttpActionResult UpdateUser(User user, string token) { if (!ModelState.IsValid || !ApplicationHelper.IsTokenValid(token, user.id)) { return(Content(HttpStatusCode.BadRequest, "BadRequest")); } var userDb = UsersLogic.GetUser(user); if (userDb == null) { return(Content(HttpStatusCode.NotFound, "NotFound")); } var result = UsersLogic.UpdateUser(user); return(Content(HttpStatusCode.OK, result)); }
public IActionResult SaveImplementationFile(string org, string app, string fileName, string fileContent) { if (!ApplicationHelper.IsValidFilename(fileName)) { return(BadRequest()); } if (fileName == "RuleHandler.js") { _repository.SaveResourceFile(org, app, fileName, fileContent); } else { _repository.SaveAppLogicFile(org, app, fileName, fileContent); } return(StatusCode(200)); }
/// <summary> /// This method returns the content of a file. /// </summary> /// <param name="org">Unique identifier of the organisation responsible for the app.</param> /// <param name="app">Application identifier which is unique within an organisation.</param> /// <param name="name">The file name.</param> /// <returns>The content of the file.</returns> public IActionResult GetFile(string org, string app, string name) { if (!ApplicationHelper.IsValidFilename(name)) { return(BadRequest()); } if (name == "RuleHandler.js") { string fileContent = _repository.GetResourceFile(org, app, name); return(Content(fileContent)); } else { string fileContent = _repository.GetAppLogic(org, app, name); return(Content(fileContent)); } }
/// <summary> /// Configura os valores padrões para as chaves de configuração do sistema. /// </summary> /// <param name="services">Configurador de serviços da aplicação web.</param> /// <param name="configuration">Configuração de inicilização.</param> /// <returns>Configurador de serviços da aplicação web.</returns> public static IServiceCollection AddLog(this IServiceCollection services, IConfiguration configuration) { var config = OptionsHelper.GetConfiguration <StackdriverOptions>(configuration); services.AddGoogleExceptionLogging(options => { options.ProjectId = config.ProjectId; options.ServiceName = ApplicationHelper.Name(); options.Version = ApplicationHelper.Version(); }); services.AddGoogleTrace(options => { options.ProjectId = config.ProjectId; }); return(services); }
/// <summary> /// 发送图片消息 /// </summary> /// <returns></returns> public static string SendNewsContent(string AdminHotelid, string ToUserName, string FromUserName) { string context = "欢迎关注!"; DataTable dt = ApplicationHelper.GetHotelTweetsInfo(ToUserName.Trim()); StringBuilder sb = new StringBuilder(); if (dt != null && dt.Rows.Count > 0) { string url = ConfigHelper.GetAppSettings("Url"); string picUrl = url + "/Marketing/images/fuli.jpg"; string images = dt.Rows[0]["images"].ToString(); if (images != "") { picUrl = url + "/upload/photo/SN" + images; } string wyrul = url + "/Reservation/HotelList.aspx?AdminHotelid=" + AdminHotelid; context = "欢迎关注" + dt.Rows[0]["Name"] + "!"; string contexts = "倾听感动,分享喜悦,“" + dt.Rows[0]["Name"] + "微管家”与您24小时贴身相伴。立即点击预订吧!"; //自定义关注图文推送 try { contexts = dt.Rows[0]["content"].ToString() == "" ? contexts : dt.Rows[0]["content"].ToString(); context = dt.Rows[0]["bt"].ToString() == "" ? context : dt.Rows[0]["bt"].ToString(); wyrul = dt.Rows[0]["url"].ToString() == "" ? wyrul : dt.Rows[0]["url"].ToString(); picUrl = dt.Rows[0]["photo"].ToString() == "" ? picUrl : url + "/upload/Reply/" + dt.Rows[0]["photo"].ToString(); } catch { } sb.Append("{"); sb.AppendFormat("\"touser\":\"{0}\",", FromUserName); //用户openid sb.AppendFormat("\"msgtype\":\"{0}\",", "news"); // 发送文本格式 sb.Append("\"news\":{"); sb.Append("\"articles\":[{"); //文字描述 sb.AppendFormat("\"title\":\"{0}\",", context); //标题 sb.AppendFormat("\"description\":\"{0}\",", contexts); //文字描述 sb.AppendFormat("\"url\":\"{0}\",", wyrul); //跳转链接路径 sb.AppendFormat("\"picurl\":\"{0}\"", picUrl); //图片路径 sb.Append("}]"); sb.Append("}"); sb.Append("}"); } return(sb.ToString()); }
public MainWindow() { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); InitializeComponent(); DataContext = this; Settings.Reload(); TextSize = Settings.FontSize; TextColor = Settings.FontColor; Descriptions_Origin = AnalyzeTxt.AnalyzeTextFile(App.Filename_Origin); Descriptions_Chinese = AnalyzeTxt.AnalyzeTextFile(App.Filename_Translate); Dictionary_ItemName = AnalyzeDatcs.GetDictionary(AnalyzeDatcs.ConvertDatToCSV(App.Filename_Words)); if (!Directory.Exists(App.Directory_BaseType) || !File.Exists(Path.Combine(App.Directory_BaseType, "Active+Skill+Gem.json"))) { BaseTypeHelper.DownloadAsync().Wait(); } var jsonList = Directory.GetFiles(App.Directory_BaseType, "*.json").ToList(); foreach (var x in jsonList) { Dictionary_BaseType = BaseType.AnalyzeJsonFile(x, Dictionary_BaseType); } if (!string.IsNullOrWhiteSpace(Settings.AddonFile)) { Dictionary_Addons.Reload(Settings.AddonFile); } ApplicationHelper applicationHelper = new ApplicationHelper(); applicationHelper.ForegroundWindowChanged += () => { POE_Foreground = ApplicationHelper.IsPathOfExileTop(Handle); Opacity = POE_Foreground ? 1 : 0; if (POE_Foreground) { POE_Rect = ApplicationHelper.PathOfExileDimentions; Left = POE_Rect.Left; Top = POE_Rect.Top; Width = POE_Rect.Right - POE_Rect.Left; Height = POE_Rect.Bottom - POE_Rect.Top; } }; }
public IResult <EdgeWebFeedTimeline> GetUserTimelineMedias(string endCursor = null) { try { var uri = ""; var variables = ""; var signature = ""; HttpWebRequest request = null; if (String.IsNullOrEmpty(endCursor)) { uri = InstagramCustomApiConstants.USER_TIMELINE_MEDIAS_INIT; request = HttpHelper.GetDefaultRequest(uri); request.Headers["Cookie"] = _user.UserCookie; } else { uri = string.Format(InstagramCustomApiConstants.USER_TIMELINE_MEDIAS, endCursor); variables = string.Format("{0}:{{\"cached_feed_item_ids\":[],\"fetch_media_item_count\":12,\"fetch_media_item_cursor\":\"{0}\",\"fetch_comment_count\":4,\"fetch_like\":3,\"has_stories\":false,\"has_threaded_comments\":true}}", _user.UserRhxGis, endCursor); signature = ApplicationHelper.CreateMD5(variables); request = HttpHelper.GetDefaultRequest(uri); request.Headers["Cookie"] = _user.UserCookie; request.Headers["X-Instagram-GIS"] = signature; } var response = HttpHelper.GetDefaultResponse(request); var json = response.ReadAsString(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <EdgeWebFeedTimeline>(response, json)); } var objRetorno = JsonConvert.DeserializeObject <UserMedias>(json); var medias = objRetorno.Data.User.EdgeWebFeedTimeline; return(Result.Success(medias)); } catch (Exception ex) { return(Result.Fail <EdgeWebFeedTimeline>(ex.Message)); } }
public void Regist(bool buildHbmFile, string exportHbmFolder) { IEnumerable <Assembly> fluentAssemblies = GetFluenAssembly(); IEnumerable <Assembly> nhAssembilies = GetHbmXmlFile(); foreach (Type type in _regType.Keys) { OrnamentContext.DaoFactory.Regist(type, _regType[type]); } SessionManager.Regist("default", () => { var config = new Configuration(); string configFileName = ConfigurationManager.AppSettings["nhConfig"]; if (String.IsNullOrEmpty(configFileName)) { throw new ArgumentNullException( "nhConfig section can't be find in the config file. please set it up in the appSettiong section."); } config.Configure(ApplicationHelper.MapPath(configFileName)); FluentConfiguration result = Fluently.Configure(config); foreach (Assembly assembly in fluentAssemblies) { if (buildHbmFile) { Assembly assembly1 = assembly; result.Mappings(s => s.FluentMappings.AddFromAssembly(assembly1) .ExportTo(exportHbmFolder)); } else { result.Mappings(s => s.FluentMappings.AddFromAssembly(assembly)); } } foreach (Assembly assembly in nhAssembilies) { result.Mappings(s => s.HbmMappings.AddFromAssembly(assembly)); } return(result.BuildConfiguration()); }); }
private async void CheckForUpdatesAsync() { if (_application.Preferences.LastSeenVersion == null) { _application.Preferences.LastSeenVersion = _application.GetVersion(); return; } if (IsPermissionDenied(Manifest.Permission.Internet)) { RequestPermissions(InternetPermissionRequestCode, Manifest.Permission.Internet); return; } String version = await ApplicationHelper.GetCurrentVersionAsync(); if (version == null) { return; } String current = _application.GetVersion(); if (version != current && version != _application.Preferences.LastSeenVersion) { CustomAlertDialog dialog = new CustomAlertDialog(this) .SetTitle(Resource.String.updateApplicationTitle) .SetMessage(Resource.String.applicationUpdateAvailableMessage) .SetPositiveButton( Resource.String.viewActionText, () => { _application.Preferences.LastSeenVersion = version; String releaseUrl = ApplicationHelper.LatestReleaseUrl; StartActivity(new Intent(Intent.ActionView, Uri.Parse(releaseUrl))); } ); dialog.DismissEvent += (s, e) => _application.Preferences.LastSeenVersion = version; RunOnUiThread(dialog.Show); } }
private static Settings LoadSetttings() { var settings = new Settings(); try { var filename = Path.Combine(ApplicationHelper.GetUserDataPath(), "Halloumi.Shuffler.Settings.xml"); if (File.Exists(filename)) { settings = SerializationHelper <Settings> .FromXmlFile(filename); } } catch { // ignored } return(settings); }
public async Task <LoginOutputDto> Login(LoginInputDto loginInputDto) { var user = _defaultDbContext.MbpUsers.Where(u => u.LoginName == loginInputDto.LoginName).FirstOrDefault(); if (user != null) { if (user.Password != ApplicationHelper.EncryptPwdMd5(loginInputDto.Password)) { return(new LoginOutputDto() { AccessToken = new Jwt(), IsPassPwdCheck = false }); } // 如果是管理员权限就给管理员属性,如果是用户就给用户属性,这里只定义两种角色,一种是超管,一种是普通用户,这里的角色只做身份鉴定,不做鉴权用 var token = await _jwtBearerService.CreateJwt(loginInputDto.LoginName, loginInputDto.ClientID, new List <Claim>() { new Claim(ClaimTypes.Role, user.IsAdmin?"admin":"user") }); // 取出用户的菜单权限 var menus = (from tuser in _defaultDbContext.Set <MbpUser>() join tuserrole in _defaultDbContext.Set <MbpUserRole>() on tuser.Id equals tuserrole.UserId join trole in _defaultDbContext.Set <MbpRole>() on tuserrole.RoleId equals trole.Id join trolemenu in _defaultDbContext.Set <MbpRoleMenu>() on trole.Id equals trolemenu.RoleId join tmenu in _defaultDbContext.Set <MbpMenu>() on trolemenu.RoleId equals tmenu.Id select tmenu.Path).ToList(); return(new LoginOutputDto() { AccessToken = token, Menus = menus, UserName = user.UserName, Role = user.IsAdmin ? "admin" : "user", IsPassPwdCheck = true }); } return(new LoginOutputDto() { AccessToken = new Jwt(), IsPassPwdCheck = false }); }
internal void ConsumirReserva(string entregaid) { var appService = new ApplicationHelper(_context); using (var tran = new TransactionScope()) { var model = get(entregaid) as ReservasstockModel; GenerarMovimientosLineas(model, model.Lineas, TipoOperacionService.EliminarReservaStock); var configuracionModel = appService.GetConfiguracion(_db); model.Fkestados = configuracionModel.Estadoreservasparcial; var aux = _validationService as ReservasstockValidation; aux.CambiarEstado = true; _flagconsumirreserva = true; edit(model); _flagconsumirreserva = false; aux.CambiarEstado = false; tran.Complete(); } }
public TraillingStopSystem() { //Property or indexer cannot be used as parameter. //This variable here is only a place holder. float TrailingStopPrice; int ContractQuantity; config = new Dictionary <string, object>(); config = ApplicationHelper.ReadXML("Config/TraillingStopSystem.xml"); float.TryParse(config.First(x => x.Key == ApplicationHelper.TrailingStopPrice).Value.ToString(), out TrailingStopPrice); int.TryParse(config.First(x => x.Key == ApplicationHelper.ContractQuantity).Value.ToString(), out ContractQuantity); //Set config value to property this.TrailingStopPrice = TrailingStopPrice; this.ContractQuantity = ContractQuantity; this.BuyrOrderStatus = ApplicationHelper.EMPTY; this.TrailingOrderStatus = ApplicationHelper.EMPTY; }
public ActionResult SopVsSipDetails(string branchCode, double date, string day = "7") { var user = m_dbContext.Users.Single(u => u.UserName == User.Identity.Name); if (null != user && !string.IsNullOrEmpty(user.BranchCode) && user.BranchCode != branchCode) { if (!User.IsInRole("VersusHQ")) { return(new HttpStatusCodeResult(403, "You are not allow to view the data")); } } var reportDate = DateTime.FromOADate(date); ViewBag.Branches = m_enttContext.GetBranchInfo(branchCode).Select(w => new SelectListItem { Text = w.Name, Value = w.Code }); ViewBag.ReportDays = ApplicationHelper.GetReportDays().Select(w => new SelectListItem { Text = w.Value, Value = w.Key.ToString() }); var reportViewer = ReportEngine.Create(); var dataset = m_enttContext.GetSopVsSipDetailsReportDataSet(reportDate.Date, int.Parse(day), branchCode); reportViewer.LocalReport.ReportPath = Request.MapPath(Request.ApplicationPath) + @"Reports\Versus\SopVsSipDetails.rdlc"; var parameters = new List <ReportParameter> { new ReportParameter("reportDate", reportDate.ToShortDateString()), new ReportParameter("day", day), new ReportParameter("branchCode", branchCode) }; reportViewer.LocalReport.EnableHyperlinks = true; reportViewer.LocalReport.SetParameters(parameters); reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", dataset.Tables[0])); ViewBag.TotalRows = dataset.Tables[0].Rows.Count; ViewBag.ReportViewer = reportViewer; var model = new PrefixReportViewModel { ReportDate = reportDate, ReportDay = day, SelectedBranch = branchCode }; return(View(model)); }
static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); /* * Database scripts * https://docs.microsoft.com/en-us/dotnet/framework/windows-workflow-foundation/how-to-enable-sql-persistence-for-workflows-and-workflow-services * C:\Windows\Microsoft.NET\Framework\v4.0.30319\SQL\en * SqlWorkflowInstanceStoreSchema.sql * SqlWorkflowInstanceStoreLogic.sql */ //Store connection string PersistanceHelper.Store = new SqlWorkflowInstanceStore(@"Data Source=LAFDEV3\SQL2014;Initial Catalog=Corey-WfPersistenceStore;Integrated Security=True;Async=true") { InstanceCompletionAction = InstanceCompletionAction.DeleteNothing, RunnableInstancesDetectionPeriod = new TimeSpan(0, 0, 5), InstanceLockedExceptionAction = InstanceLockedExceptionAction.AggressiveRetry, }; //Reload any instances that persisted since you last ran the application. PersistanceHelper.ReconstituteRunnableInstances(); ExampleActivity activity = new ExampleActivity(); //Defines the application completely so it can be resumed. ApplicationHelper app = new ApplicationHelper( activity, activity.GetIdentity(), new Core.Models.DataEventArgs() { EventDate = DateTime.Now, SourceApiName = "Program-Application", SourceFriendlyName = "Program Application", SourceTransactionId = Guid.NewGuid().ToString(), SourceType = new Core.Models.TypeWrapper(typeof(ExampleActivity)) }); app.Run(); //Wait here so the application can run in the background Console.ReadLine(); }
private dynamic GetAccessToken(NameValueCollection parameters) { string un = parameters["un"]; string unkey = parameters["unkey"]; WxAccountRepository cr = new WxAccountRepository(); var user = cr.FindByExpression(x => x.UserName == un).FirstOrDefault(); if (user == null) { return(ConstHelper.ERROR_100007); } string cryptKey = CryptHelper.MD5(un + user.Token); if (!Equals(unkey, cryptKey)) { return(ConstHelper.ERROR_100007); } string KEY_ACCESS_TOKEN = user.UserName + "ACCESSTOKEN"; if (!ApplicationHelper.Exists(KEY_ACCESS_TOKEN)) { return(RequestNewToken(user, KEY_ACCESS_TOKEN)); } else { AccessTokenCacheEntity accesstoken = ApplicationHelper.GetValue(KEY_ACCESS_TOKEN) as AccessTokenCacheEntity; TimeSpan ts = DateTime.Now - accesstoken.RequstTime; // 提前5秒过期 if (ts.TotalSeconds < (user.ExpiresIn ?? 0) - 5) { AccessTokenEntity entity = new AccessTokenEntity(); entity.access_token = accesstoken.AccessToken; entity.expires_in = user.ExpiresIn ?? 0; return(entity); } else { return(RequestNewToken(user, KEY_ACCESS_TOKEN)); } } }
public void Post(PathValues pathValues) { document = new PdfDocument(); try { logger.Trace($"start processing file:{pathValues.Path} at {DateTime.Now.ToString("yyyy/MM/dd-hh:mm:ss")}"); var fileName = Path.GetFileName(pathValues.Path); helper = new ApplicationHelper(); verizonReader = new VerizonReader(document, pathValues.Path); FileDto file = new FileDto(); HeaderDto header = new HeaderDto(); List <DetailDto> details = new List <DetailDto>(); var preBuildText = helper.Prebuild(document, pathValues.Path); if (preBuildText.Any()) { header = verizonReader.GetHeaderValues(preBuildText); file = verizonReader.GetFileValues(fileName); var detailList = helper.ReadDetails(document, pathValues); details = verizonReader.GetDetailValues(detailList, document, pathValues.Path); } verizonReader.PlainTextConstructor(file, header, details, pathValues.Path, pathValues.OutputPath, pathValues.ProcessedFilesPath, pathValues.FailedFiles); logger.Trace($"finished processing file:{pathValues.Path} at {DateTime.Now.ToString("yyyy/MM/dd-hh:mm:ss")}"); } catch (Exception ex) { document.Close(); var fileName = Path.GetFileName(pathValues.Path); if (ex.Message == Constants.ErrorMessage1 || ex.Message == Constants.ErrorMessage2 || ex.Message == Constants.ErrorMessage3) { System.IO.File.Move(pathValues.Path, $@"{pathValues.CorruptedFiles}\{fileName}", true); logger.Error($"{ex.Message} in file {pathValues.Path} \\n\\n {ex.StackTrace}"); } else { System.IO.File.Move(pathValues.Path, $@"{pathValues.FailedFiles}\{fileName}", true); logger.Error($"{ex.Message} in file {pathValues.Path} \\n\\n {ex.StackTrace}"); } } }
private bool ValdiateNif(Empresas model) { try { if (!string.IsNullOrEmpty(model.fkPais) && !string.IsNullOrEmpty(model.nif)) { var appService = new ApplicationHelper(Context); var fNifValidatorService = new FNifValidatorService(appService.CheckPaisEuropeoService(model.fkPais)); var validator = fNifValidatorService.GetValidator(model.fkPais); var tiposnifs = appService.GetListTiposNif(_db); var hayQueVerificar = tiposnifs.SingleOrDefault(f => f.Valor == model.fktipoidentificacion_nif)?.VerificaValor; if (hayQueVerificar.HasValue && hayQueVerificar.Value) { var cadenaNif = model.nif; if (!validator.Validate(ref cadenaNif)) { return(false); } model.nif = cadenaNif; } if (!string.IsNullOrEmpty(model.nifcifadministrador)) { var cadenaNif = model.nifcifadministrador; if (!validator.Validate(ref cadenaNif)) { return(false); } model.nifcifadministrador = cadenaNif; } model.nif = model.nif.ToUpper(); } } catch (Exception ex) { throw new ValidationException(ex.Message); } return(true); }
public IResult <Hashtag> GetHashtag(string hashtag) { try { var uri = string.Format(InstagramGraphApiConstants.EXPLORE_TAG_DATA_INIT, hashtag); var request = HttpHelper.GetDefaultRequest(uri); request.Headers["Cookie"] = _user.UserCookie; var response = HttpHelper.GetDefaultResponse(request); var html = response.ReadAsString(); var json = ApplicationHelper.ExtractJsonFromHtml(html); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <Hashtag>(response, json)); } var objRetorno = JsonConvert.DeserializeObject <TagData>(json); _user.UserRhxGis = objRetorno.RhxGis; var hashtagRetorno = objRetorno.EntryData.TagPage[0].Graphql.Hashtag; Hashtag Hashtag = new Hashtag(); Hashtag.Name = hashtagRetorno.Name; Hashtag.Id = hashtagRetorno.Id; Hashtag.MediaCount = hashtagRetorno.MediaCount; Hashtag.SearchResultSubtitle = hashtagRetorno.SearchResultSubtitle; Hashtag.AllowFollowing = hashtagRetorno.AllowFollowing; Hashtag.IsFollowing = hashtagRetorno.IsFollowing; Hashtag.IsTopMediaOnly = hashtagRetorno.IsTopMediaOnly; Hashtag.ProfilePicUrl = hashtagRetorno.ProfilePicUrl; Hashtag.EdgeHashtagToTopPosts = hashtagRetorno.EdgeHashtagToTopPosts; Hashtag.EdgeHashtagToMedia = GetEdgeHashtagToMedia(hashtagRetorno); return(Result.Success(Hashtag)); } catch (Exception ex) { return(Result.Fail <Hashtag>(ex.Message)); } }
private static void OnIsChildWindowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var window = d as Window; if (window == null) { return; } if ((bool)e.NewValue) { window.ShowInTaskbar = false; window.Owner = ApplicationHelper.GetCurrentActivatedWindow(); } else { window.Owner = null; window.ShowInTaskbar = true; } }
private async void BtnGo_Click(object sender, EventArgs e) { var(b, message) = ValidateFields(); if (!b) { MessageBox.Show(message, ApplicationHelper.GetApplicationTitle(), MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } var downloadConfig = await GetDownloadConfig(); _thread = new WorkerThread(this, downloadConfig, txtSaveToDir.Text); panel1.Enabled = false; panel4.Enabled = false; btnGo.Enabled = false; btnCancel.Enabled = true; _thread.Start(); }
public object Get(string id) { // Cut off the notion of uuid from beginning of request VDirId vdirId = new VDirId(id); Site site = SiteHelper.GetSite(vdirId.SiteId); // Get the parent application using data encoded in uuid Application app = ApplicationHelper.GetApplication(vdirId.AppPath, site); // Get the target vdir from the id data VirtualDirectory vdir = VDirHelper.GetVDir(vdirId.Path, app); if (vdir == null) { return(NotFound()); } return(VDirHelper.ToJsonModel(vdir, app, site, Context.Request.GetFields())); }
/// <summary> /// Write workbook to excel file /// </summary> /// <param name="workbook">workbook</param> /// <param name="filePath">file path</param> public static void WriteToFile([NotNull] this IWorkbook workbook, string filePath) { var dir = Path.GetDirectoryName(filePath); if (null == dir) { filePath = ApplicationHelper.MapPath(filePath); } else { if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } } using (var fileStream = File.Create(filePath)) { workbook.Write(fileStream); } }
/// <summary> /// Setup application list. /// </summary> private void SetupAppList() { DataSet ds = ApplicationHelper.LoadApplications(); DataSet filteredDataSet = ApplicationHelper.FilterApplications(ds, CurrentUser, true); if ((filteredDataSet != null) && !DataHelper.DataSourceIsEmpty(filteredDataSet)) { // Create grouped data source GroupedDataSource gds = new GroupedDataSource(filteredDataSet, "ElementParentID", "ElementLevel"); appListUniview.DataSource = gds; appListUniview.ReloadData(true); } SiteInfo si = SiteContext.CurrentSite; if ((si != null) && (!si.SiteIsOffline)) { SetupLiveSiteLink(); } }
private void ToolStripMenuItem_ConfigureChangeDataLocationBarcodeBuddy_Click(object sender, EventArgs e) { using (FolderBrowserDialog dialog = new FolderBrowserDialog()) { dialog.RootFolder = Environment.SpecialFolder.Desktop; dialog.SelectedPath = this.UserSettings.BarcodeBuddyDataLocation; if (dialog.ShowDialog() == DialogResult.OK) { if (MessageBox.Show(this.ResourceManager.GetString("STRING_GrocyDesktopWillRestartToApplyTheChangedSettingsContinue.Text"), this.ResourceManager.GetString("STRING_ChangeDataLocation.Text"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { IOHelper.CopyFolder(this.UserSettings.BarcodeBuddyDataLocation, dialog.SelectedPath); Directory.Delete(this.UserSettings.BarcodeBuddyDataLocation, true); this.UserSettings.BarcodeBuddyDataLocation = dialog.SelectedPath; this.UserSettings.Save(); ApplicationHelper.RestartApp(); } } } }
public static void TogglePinApp(this IntPtr hWnd) { var appId = ApplicationHelper.GetAppId(hWnd); if (appId == null) { return; } if (VirtualDesktop.IsPinnedApplication(appId)) { VirtualDesktop.UnpinApplication(appId); RaisePinnedEvent(hWnd, PinOperations.UnpinApp); } else { VirtualDesktop.PinApplication(appId); RaisePinnedEvent(hWnd, PinOperations.PinApp); } }
/// <summary> /// Gets the content of a specified file for the app. /// </summary> /// <param name="org">Unique identifier of the organisation responsible for the app.</param> /// <param name="app">Application identifier which is unique within an organisation.</param> /// <param name="fileEditorMode">The mode for which files should be fetched.</param> /// <param name="fileName">The name of the file to fetch.</param> /// <returns>The content of the file.</returns> public ActionResult GetServiceFile(string org, string app, FileEditorMode fileEditorMode, string fileName) { if (!ApplicationHelper.IsValidFilename(fileName)) { return(BadRequest()); } string file = string.Empty; switch (fileEditorMode) { case FileEditorMode.Implementation: file = _repository.GetImplementationFile(org, app, fileName); break; case FileEditorMode.Calculation: file = _repository.GetImplementationFile(org, app, "Calculation/" + fileName); break; case FileEditorMode.Validation: file = _repository.GetImplementationFile(org, app, "Validation/" + fileName); break; case FileEditorMode.Dynamics: file = _repository.GetResourceFile(org, app, "Dynamics/" + fileName); break; case FileEditorMode.All: file = _repository.GetConfiguration(org, app, fileName); break; case FileEditorMode.Root: file = _repository.GetFileByRelativePath(org, app, fileName); break; default: break; } return(Content(file, "text/plain", Encoding.UTF8)); }
public IResult <ShortcodeMediaLikes> GetMediaLikes(string shortcode, string endCursor = null, int limitPerPage = 24) { try { string uri = string.Empty; string variables = string.Empty; if (endCursor == null) { uri = string.Format(InstagramCustomApiConstants.MEDIA_LIKES_INIT, shortcode, limitPerPage); variables = string.Format("{0}:{{\"shortcode\":\"{1}\",\"include_reel\":true,\"first\":{2} }}", _user.UserRhxGis, shortcode, limitPerPage); } else { uri = string.Format(InstagramCustomApiConstants.MEDIA_LIKES_URL, shortcode, limitPerPage, endCursor); variables = string.Format("{0}:{{\"shortcode\":\"{1}\",\"include_reel\":true,\"first\":{2},\"after\":\"{3}\"}}", _user.UserRhxGis, shortcode, limitPerPage, endCursor); } var signature = ApplicationHelper.CreateMD5(variables); var request = HttpHelper.GetDefaultRequest(uri); request.Headers["X-Instagram-GIS"] = signature; request.Headers["Cookie"] = _user.UserCookie; var response = HttpHelper.GetDefaultResponse(request); var json = response.ReadAsString(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <ShortcodeMediaLikes>(response, json)); } var objRetorno = JsonConvert.DeserializeObject <ShortcodeMediaLikesData>(json); return(Result.Success(objRetorno.Data)); } catch (Exception ex) { return(Result.Fail <ShortcodeMediaLikes>(ex.Message)); } }
public IResult <Comment> GetLikesFromComment(string comment_id, string endCursor = null, int limitPerPage = 48) { try { string uri = string.Empty; string variable = string.Empty; if (String.IsNullOrEmpty(endCursor)) { uri = string.Format(InstagramGraphApiConstants.LIKES_FROM_COMMENT_INIT, comment_id, limitPerPage); variable = string.Format("{{\"comment_id\":\"{0}\",\"first\":{1}}}", comment_id, limitPerPage); } else { uri = string.Format(InstagramGraphApiConstants.LIKES_FROM_COMMENT_URL, comment_id, limitPerPage, endCursor); variable = string.Format("{{\"comment_id\":\"{0}\",\"first\":{1},\"after\":\"{2}\"}}", comment_id, limitPerPage, endCursor); } var signature = ApplicationHelper.CreateMD5(variable); var request = HttpHelper.GetDefaultRequest(uri); request.Headers["X-Instagram-GIS"] = signature; request.Headers["Cookie"] = _user.UserCookie; var response = HttpHelper.GetDefaultResponse(request); var json = response.ReadAsString(); if (response.StatusCode != HttpStatusCode.OK) { return(Result.UnExpectedResponse <Comment>(response, json)); } var objRetorno = JsonConvert.DeserializeObject <CommentData>(json); return(Result.Success <Comment>(objRetorno.Data.Comment)); } catch (Exception ex) { return(Result.Fail <Comment>(ex.Message)); } }