private void ReportPdhError(uint res, bool bTerminate) { string msg; uint formatRes = CommonUtilities.FormatMessageFromModule(res, "pdh.dll", out msg); if (formatRes != 0) { msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res); } Exception exc = new Exception(msg); if (bTerminate) { ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); } else { WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); } }
protected void ValidateService() { string serviceName; ServiceSettings settings = CommonUtilities.GetDefaultSettings(CommonUtilities.TryGetServiceRootPath(CurrentPath()), ServiceName, null, null, null, null, CurrentSubscription.SubscriptionId, out serviceName); if (string.IsNullOrEmpty(serviceName)) { throw new Exception(string.Format(Resources.ServiceExtensionCannotFindServiceName, ServiceName)); } else { ServiceName = serviceName; if (ComputeClient.HostedServices.CheckNameAvailability(ServiceName).IsAvailable) { throw new Exception(string.Format(Resources.ServiceExtensionCannotFindServiceName, ServiceName)); } } ExtensionManager = new ExtensionManager(this, ServiceName); }
private static Dictionary <string, int> GetTablesInOrder(DataContext dataContext, string schema) { Log.Logger.Information("Grabbing the tables and dependencies..."); string depSql = @"select DISTINCT OBJECT_NAME(t.object_id) as tablename, object_name(sic.referenced_object_id) as references_table from sys.schemas s inner join sys.tables t on s.schema_id = t.schema_id and s.name = '{0}' and t.type = 'U' left join sys.foreign_keys si on t.object_id = si.parent_object_id left join sys.foreign_key_columns sic on si.object_id = sic.constraint_object_id order by tablename"; Dictionary <string, List <string> > table_with_dependencies = new Dictionary <string, List <string> >(); using (IDataReader idr = dataContext.ExecuteReader(string.Format(depSql, schema))) { string table_n = null; List <string> dependencies = null; while (idr.Read()) { string t_name = idr.GetStringSafe(0); string d_name = idr.GetStringSafe(1); if (table_n == null || table_n != t_name) { dependencies = new List <string>(); table_with_dependencies.Add(t_name, dependencies); table_n = t_name; } if (d_name != null) { dependencies.Add(d_name); } } } // Order the tables Log.Logger.Information("Ordering the {0} table dependencies...", table_with_dependencies.Count); Dictionary <string, int> sorted_tables_with_dependencies = CommonUtilities.TopSort(table_with_dependencies, true); return(sorted_tables_with_dependencies); }
/// <summary> /// Executes the script. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="splitCharacter">How to split the file into chunks.</param> /// <param name="scriptReplacements">Optional token/replacement values.</param> public virtual void ExecuteScript(string fileName, string splitCharacter, Dictionary <string, string> scriptReplacements = null) { FileInfo fi = new FileInfo(fileName); using (StreamReader sr = new StreamReader(fi.Open(FileMode.Open, FileAccess.Read))) { if (!string.IsNullOrWhiteSpace(splitCharacter)) { string script = sr.ReadToEnd(); // look for script replacements if (scriptReplacements != null) { script = CommonUtilities.ReplaceTokensInContent(script, scriptReplacements); } string[] chunks = Regex.Split(script, splitCharacter, RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase); foreach (string text in chunks) { try { if (string.IsNullOrWhiteSpace(text)) { continue; } ExecuteNonQuery(text); } catch (Exception ex) { throw new NotSupportedException("Failed running script " + fileName + ". ERROR: " + ex.Message + "\n\nSCRIPT: " + text + "\nLENGTH: " + text.Length, ex); } } } else { ExecuteNonQuery(sr.ReadToEnd()); } } }
public ActionResult CopyIndicators(IEnumerable <string> jdata, string selectedProfileUrlkey, string selectedProfileName, int selectedDomainId, string selectedDomainName, int selectedAreaTypeId) { var model = new CopyIndicatorsModel { UrlKey = selectedProfileUrlkey, Profile = GetProfile(selectedProfileUrlkey, selectedDomainId, selectedAreaTypeId), DomainName = selectedDomainName, DomainId = selectedDomainId, ProfileName = selectedProfileName, AreaTypeId = selectedAreaTypeId, IndicatorsThatCantBeTransferred = null, }; var listOfProfiles = GetOrderedListOfProfilesForCurrentUser(model); var domains = new ProfileMembers(); var defaultProfile = listOfProfiles.FirstOrDefault(x => x.Selected) ?? listOfProfiles.FirstOrDefault(); defaultProfile.Selected = true; model.ListOfDomains = CommonUtilities.GetOrderedListOfDomainsWithGroupId(domains, defaultProfile, selectedDomainId); model.GroupId = Convert.ToInt32(model.ListOfDomains.FirstOrDefault(x => x.Selected).Value); var userPermissions = CommonUtilities.GetUserGroupPermissionsByUserId(_reader.GetUserByUserName(_userName).Id); model.UserGroupPermissions = userPermissions.FirstOrDefault(x => x.ProfileId == _reader.GetProfileDetails(model.UrlKey).Id); var indicatorSpecifiers = IndicatorSpecifierParser.Parse(jdata.ToArray()); model.IndicatorsToTransfer = GetSpecifiedIndicatorNames(indicatorSpecifiers, model.Profile.IndicatorNames); if (Request.IsAjaxRequest()) { return(PartialView("_CopySelectedIndicators", model)); } return(View("ProfilesAndIndicators")); }
/// <summary> /// Wait for a page to loaded on the screen /// </summary> private void AjaxCallToFinish() { string documentReadyState = ""; string documentReadyStateStripped = ""; long maxTimeToWait = CommonUtilities.GetCurrentTimeMillis() + CommonUtilities.GLOBAL_TIMEOUT_TIME_IN_MSEC; while (!documentReadyStateStripped.Equals("complete") && maxTimeToWait > CommonUtilities.GetCurrentTimeMillis()) { try { SAFEBBALog.Debug(CommonUtilities.GetClassAndMethodName()); String scriptToExecute = "return document.readyState"; documentReadyState = (string)driver.ExecuteScript(scriptToExecute); documentReadyStateStripped = documentReadyState.Trim().ToLower(); } catch { SAFEBBALog.Debug(CommonUtilities.GetClassAndMethodName(), "JAVASCRIPT NOT READY YET"); Thread.Sleep(500); } } }
private static IHealthChecksBuilder AddDatabaseCheck(this IHealthChecksBuilder builder, IConfiguration configuration) { var dbServerType = CommonUtilities.GetDatabaseServerTypeFromConfiguration(configuration); var connectionString = CommonUtilities.GetConnectionString(configuration); switch (dbServerType) { case zAppDev.DotNet.Framework.Data.DatabaseManagers.DatabaseServerType.SQLite: return(builder.AddSqlite(connectionString)); case zAppDev.DotNet.Framework.Data.DatabaseManagers.DatabaseServerType.MSSQL: return(builder.AddSqlServer(connectionString)); case zAppDev.DotNet.Framework.Data.DatabaseManagers.DatabaseServerType.MariaDB: return(builder.AddMySql(connectionString)); default: break; } return(builder); }
public LoggedInUserModel Authenticate(string userName, string password, string jwtSecretKey) { var userDetails = this.context.User.FirstOrDefault(x => x.Username == userName); if (userDetails == null) { return(null); } var passwordHash = CommonUtilities.GenerateHashPassword(password, userDetails.PasswordSalt); if (userDetails.PasswordHash != passwordHash) { return(null); } var tokenHandler = new JwtSecurityTokenHandler(); var symmetricSecurityKey = Encoding.ASCII.GetBytes(jwtSecretKey); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, userDetails.Username), }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricSecurityKey), SecurityAlgorithms.HmacSha256) }; var token = tokenHandler.CreateToken(tokenDescriptor); return(new LoggedInUserModel() { // UserId = userDetails.Id, Username = userDetails.Username, Token = tokenHandler.WriteToken(token), UserAvatarLink = userDetails.UserAvatar }); }
/// <summary> /// Get an element from the set. /// </summary> /// <returns>An element if non-empty.</returns> public Option <T> Element() { var model = this.Solver.Satisfiable(this.Set); if (!model.HasValue) { return(Option.None <T>()); } var assignment = new Dictionary <object, object>(); foreach (var kv in this.ArbitraryMapping) { var value = this.Solver.Get(model.Value, kv.Value); assignment[kv.Key] = value; } var interpreterEnv = new ExpressionEvaluatorEnvironment(assignment); var result = CommonUtilities.ConvertSymbolicResultToCSharp <T>(this.ZenExpression.Accept(new ExpressionEvaluator(false), interpreterEnv)); return(Option.Some(result)); }
/// <summary> /// Draws the component /// </summary> /// <param name="gameState"></param> public void Draw(IGameState gameState) { // draw content when there is character to edit foreach (IGraphicObject obj in _objects) { obj.Draw(_sbatch); } if (gameState.EditingCharacter != null) { UpdateAlternateState(gameState.EditingCharacter.IsOfPersonality); foreach (IGraphicObject obj in _buttons) { obj.Draw(_sbatch); } CommonUtilities.DrawFont( gameState.EditingCharacter.Name + "'s stats:", FontEnum.Font20, CommonUtilities.GetPositionFromInt(GraphicDimension.EditingTitle), Color.Black, _sbatch); } // draw greyed overlay if unable to edit if (!gameState.Editable) { _overlay.Draw(_sbatch); CommonUtilities.DrawFont( "This function is not available now.", FontEnum.Font20, CommonUtilities.GetPositionFromInt(GraphicDimension.EditingTitle), Color.Black, _sbatch); CommonUtilities.DrawFont( "Please try again later.", FontEnum.Font20, CommonUtilities.GetPositionFromInt(GraphicDimension.EditingTitle1), Color.Black, _sbatch); } }
static void Main(string[] args) { // Reload Registry Hive Trick CommonUtilities.ExecuteCommand("REG SAVE HKLM\\SYSTEM " + CommonUtilities.EscapePath(Environment.GetEnvironmentVariable("TEMP") + "\\SYSTEM.hiv"), true); CommonUtilities.ExecuteCommand("REG RESTORE HKLM\\SYSTEM " + CommonUtilities.EscapePath(Environment.GetEnvironmentVariable("TEMP") + "\\SYSTEM.hiv"), true); CommonUtilities.FileDelete(Environment.GetEnvironmentVariable("TEMP") + "\\SYSTEM.hiv"); // Rename and Delete WPA Key using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM", true)) { if (key != null) { // TODO : Powershell Bundled Vista+ ??? CommonUtilities.ExecuteCommand(@"POWERSHELL -command rename-item HKLM:\SYSTEM\WPA -NewName WPA_Delete", true); key.DeleteSubKeyTree("WPA_DELETE"); key.CreateSubKey("WPA"); // Create Default Values CommonUtilities.ExecuteCommand("REG ADD HKLM\\SYSTEM\\WPA\\478C035F-04BC-48C7-B324-2462D786DAD7-5P-9 /t REG_BINARY /ve /d 20c0c44b5d68c7085f442818128270ea642e5b5dba2d8885a7831a85c3d1ece262b36911a0d5bdb5e55106656d12578af73f942ffe1562ba665b18ce8969bbf74ff8ceacf3c424de22cf36560c8633b92173d5f38abbe0fbe3f408ca314725a94d599a4587daea29aa207b5cefbfcf2361b7a9beeaacc754513fdce82c16828d", true); CommonUtilities.ExecuteCommand("REG ADD HKLM\\SYSTEM\\WPA\\478C035F-04BC-48C7-B324-2462D786DAD7-5P-9 /t REG_BINARY /v Time /d e318ad15241c695f751c6b19fe1ba41cebfb91bf29367de3146d79a76ace067c", true); CommonUtilities.ExecuteCommand("REG ADD HKLM\\SYSTEM\\WPA\\478C035F-04BC-48C7-B324-2462D786DAD7-5P-9 /t REG_DWORD /v Type /d 2111353691", true); CommonUtilities.ExecuteCommand("REG ADD HKLM\\SYSTEM\\WPA\\8DEC0AF1-0341-4b93-85CD-72606C2DF94C-7P-1 /t REG_BINARY /ve /d 6979d03b99a73c736882ceadf1a96320c15405927dc0b721f83cad674fb340496d75f608189d84dcd18fdaff8ea3866a3f37edc3d1eb5c0647e97bb7bea79f5dd05a66062fabb480d137cd3623563962e200b1bd42531cc3e6e4c1ffff693a208e9937f7a4d48b7463e68faf0df08811", true); CommonUtilities.ExecuteCommand("REG ADD HKLM\\SYSTEM\\WPA\\8DEC0AF1-0341-4b93-85CD-72606C2DF94C-7P-2 /t REG_BINARY /ve /d 79e3ad3e68302e43bc97f4aceb98f3e328155f42df9684935abbc4f3c1652637a70f81fdf5f469d8586bf1d1a8ff96af9ead400b1c9d5621f4b4c57ad44fc2b129ca20a19a64bcfc481c52738b876b64", true); CommonUtilities.ExecuteCommand("REG ADD HKLM\\SYSTEM\\WPA\\8DEC0AF1-0341-4b93-85CD-72606C2DF94C-7P-3 /t REG_BINARY /ve /d 65a7778c965816a2df869e044edf4671f2ac716502d74d5b30c531c1469dc758dc25c2b480393d6fb7336d3d915668a7f05ff3847468228168833bed8947b4bc", true); } } // Set WPA Key Permissions using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\\WPA", true)) { if (key != null) { RegistrySecurity acl = new RegistrySecurity(); acl.SetAccessRuleProtection(true, false); acl.SetAccessRule(new RegistryAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), RegistryRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); key.SetAccessControl(acl); } } }
protected override string GetValueInApiModule(ApiModule apiModule, string key) { try { if (apiModule?.Headers != null && apiModule.Headers.Length > 0) { var l = Deserialize <List <List <KeyValuePair <string, string> > > >(apiModule.Headers); foreach (var keyvaluepairList in l) { var k = keyvaluepairList.First().Value; if (k == key) { return(CommonUtilities.RemoveExtraDoubleQuotes(keyvaluepairList.Last().Value)); } } } } catch (Exception) { // ignored } return(string.Empty); }
private void OpenScript(Object sender, ExecutedRoutedEventArgs e) { var ofd = new OpenFileDialog(); ofd.RestoreDirectory = true; ofd.Filter = "PScript Files|*.s"; if (ofd.ShowDialog().Value) { String filePath = ofd.FileName; using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { using (var sr = new StreamReader(fs)) { String text = CommonUtilities.NormalizeText(sr); var doc = new TextDocument(text); editor.Document = doc; editor.Focus(); } } } e.Handled = true; }
private static void GenerateReport(UnitTestResultCollection unitTestResultCollection, TestSummary testSummaryCollection, string fileName, bool isIncludeOutput) { var file = new System.IO.FileInfo(fileName); if (file.Exists) { file.Delete(); } using (var p = new Document()) { //set the workbook properties and add a default sheet in it PdfWriter.GetInstance(p, new FileStream(fileName, FileMode.Create)); SetWorkbookProperties(p); ////Create a sheet p.Open(); p.AddTitle(unitTestResultCollection.CollectionName.ToString() + " - Test Report"); p.Add(new Paragraph(unitTestResultCollection.CollectionName + " - Trx2Any Report")); BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false); var times = new iTextSharp.text.Font(bfTimes, 8, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.RED); p.Add(new Paragraph("This is a report generated by trx2any", times)); //ExcelWorksheet ws = CreateSheet(p, unitTestResultCollection.CollectionName); DataTable dt = CommonUtilities.CreateDataTable(unitTestResultCollection, isIncludeOutput); //Create Summary Table CreateSummaryHeaders(p, testSummaryCollection); CreateHeader(p, dt); //CreateData(ws, ref rowIndex, dt); //ws.Column(dt.Columns.Count).Width = 100; //p.Save(); p.Close(); } }
public void CreateTaskPropertiesShouldCreateCorrectObject() { EvaluationRequest request = new EvaluationRequest { ProjectId = Guid.NewGuid(), PlanId = Guid.NewGuid(), HostUrl = "hostUrl1", JobId = Guid.NewGuid(), HubName = "Build", TimelineId = Guid.NewGuid(), AuthToken = "authToken1" }; var taskProperties = CommonUtilities.CreateTaskProperties(request); Assert.AreEqual(request.ProjectId, taskProperties.ProjectId, "Project id should match"); Assert.AreEqual(request.PlanId, taskProperties.PlanId, "Plan id should match"); Assert.AreEqual(request.JobId, taskProperties.JobId, "Job id should match"); Assert.AreEqual(request.HubName, taskProperties.HubName, "Hub name should match"); Assert.AreEqual(request.AuthToken, taskProperties.AuthToken, "Auth token should match"); Assert.AreEqual(request.HostUrl, taskProperties.PlanUrl, "Plan url should match"); Assert.AreEqual(request.TimelineId, taskProperties.TimelineId, "Timeline id should match"); }
public static void DeleteAllFiles(SQLLib sql, string MachineID) { SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM FileTransfers WHERE MachineID=@m", new SQLParam("@m", MachineID)); while (dr.Read()) { string Filename = Settings.Default.DataPath + Convert.ToString(dr["ServerFile"]); if (File.Exists(Filename) == true) { try { CommonUtilities.SpecialDeleteFile(Filename); } catch { } } } dr.Close(); sql.ExecSQL("DELETE FROM FileTransfers WHERE MachineID=@m", new SQLParam("@m", MachineID)); }
public void FillScopeCollectionTest() { TECSubScope scope1 = new TECSubScope(); TECSubScope scope2 = new TECSubScope(); TECSubScope scope3 = new TECSubScope(); List <ITECScope> first = new List <ITECScope>() { scope1, scope2 }; List <ITECScope> second = new List <ITECScope>() { scope2, scope3 }; CommonUtilities.FillScopeCollection(first, second); Assert.IsTrue(first.Contains(scope3)); Assert.AreEqual(1, first.Where(x => x == scope2).Count()); }
public IEnumerable <BackupSetInfo> GetBackupSetInfo() { List <BackupSetInfo> result = new List <BackupSetInfo>(); foreach (Restore restore in RestorePlan.RestoreOperations) { BackupSet backupSet = restore.BackupSet; String bkSetComponent; String bkSetType; CommonUtilities.GetBackupSetTypeAndComponent(backupSet.BackupSetType, out bkSetType, out bkSetComponent); if (this.Server.Version.Major > 8 && backupSet.IsCopyOnly) { bkSetType += " (Copy Only)"; } result.Add(new BackupSetInfo { BackupComponent = bkSetComponent, BackupType = bkSetType }); } return(result); }
private void Create_SubAI_Grid() { StringBuilder sb = new StringBuilder(); foreach (DataAccess.AssessmentItem item in ListSubAI) { sb.Append("<tr>"); sb.Append("<th scope='row'>"); sb.Append(item.Order.ToString()); sb.Append("</th>"); sb.Append("<td>"); sb.Append(CommonUtilities.EditGridText(item.Text)); sb.Append("</td>"); sb.Append("<td>"); sb.Append(CommonUtilities.EditGridText(item.HelpText)); sb.Append("</td>"); sb.Append("<td>"); sb.Append(@"<a href=javascript:DeleteAIItem('" + CommonUtilities.GlobalEncrypt(item.AssessmentItemID.ToString(), BSWSession.SessionKey) + "'); class='fa fa-remove' style='color:red;' ></a>"); sb.Append("</td>"); sb.Append("</tr>"); } grdSubAI.InnerHtml = sb.ToString(); }
public ActionResult CreateFinding(RigOapChecklistQuestionFinding model) { return(TryCatchCollectionDisplayPartialView <RigOapChecklistQuestionFinding>("GenericlistFindingPartial", "RigFindingsErrorsKey", () => { var findings = GetQuestionFindings(RigChecklist, model.RigOapChecklistQuestionId); if ((findings != null) && !findings.Any(f => f.Id == Guid.Empty && f.FindingDate == model.FindingDate && f.FindingTypeId == model.FindingTypeId && f.FindingSubTypeId == model.FindingSubTypeId)) { var client = GetClient <OapChecklistFindingClient>(); var response = client.AddFindingAsync(model).Result; if ((response != null) && response.Result.Errors.Any()) { CommonUtilities.DisplayGridErrors(response.Result.Errors, GridConstants.RigFindingsErrorsKey, ViewData); } else { RigChecklist = GetClient <RigOapChecklistClient>().GetCompleteChecklistAsync(RigChecklist.Id).Result.Result.Data; } } return GetQuestionFindings(RigChecklist.Questions); })); }
public void SaveLocalizableValue(string configJSON, string valuesJSON) { LocalizableStringConfig config = (LocalizableStringConfig)Json.Deserialize(configJSON, typeof(LocalizableStringConfig)); LocalizableValueConfig[] values = (LocalizableValueConfig[])Json.Deserialize(valuesJSON, typeof(LocalizableValueConfig[])); if (config == null) { return; } var result = new LocalizableString(); foreach (var lValue in values) { result.SetCultureValue(CultureInfo.GetCultureInfo(lValue.key), lValue.value); } var schema = UserConnection.EntitySchemaManager.GetInstanceByName(config.entityName); var entity = schema.CreateEntity(UserConnection); if (entity.FetchFromDB(config.recordId)) { CommonUtilities.SaveLocalizableValue(entity, result, config.columnName); } }
public override void ExecuteCmdlet() { AzureTool.Validate(); string rootPath = CommonUtilities.GetServiceRootPath(CurrentPath()); string packagePath; CloudServiceProject service = new CloudServiceProject(rootPath, null); if (!Local.IsPresent) { service.CreatePackage(DevEnv.Cloud); packagePath = Path.Combine(rootPath, Resources.CloudPackageFileName); } else { service.CreatePackage(DevEnv.Local); packagePath = Path.Combine(rootPath, Resources.LocalPackageFileName); } WriteVerbose(string.Format(Resources.PackageCreated, packagePath)); SafeWriteOutputPSObject(typeof(PSObject).FullName, Parameters.PackagePath, packagePath); }
public async Task <ActionResult> PressConferenceOrder(Wx_PressConferenceOrderViewModel model) { if (ModelState.IsValid) { var existuser = payDB.WxPressConferenceUser.SingleOrDefault(m => m.Open_Id == model.Open_Id); if (existuser != null) { Random random = new Random(); WxPressConferenceOrder order = new WxPressConferenceOrder(); order.Open_Id = model.Open_Id; order.ImgUrl = model.ImgUrl; order.Amount = model.Amount * 10000; order.Name = model.Name; order.OrderType = 1; order.Status = 0; order.ApplyTime = DateTime.Now; order.OrderNo = "PR" + CommonUtilities.generateTimeStamp() + random.Next(1000, 9999); payDB.WxPressConferenceOrder.Add(order); await payDB.SaveChangesAsync(); return(RedirectToAction("PressConferenceHome", new { openid = model.Open_Id })); } else { return(Content("PressConferenceError")); } } else { ModelState.AddModelError("", "发生错误"); var existuser = payDB.WxPressConferenceUser.SingleOrDefault(m => m.Open_Id == model.Open_Id); ViewBag.headimgurl = existuser.HeadImgUrl; ViewBag.company = existuser.CompanyName; ViewBag.openid = existuser.Open_Id; return(View(model)); } }
public JsonResult SetFixMoney(string _openId, string body, int amount) { //随机数字,并且生成Prepay string appid = WeChatUtilities.getConfigValue(WeChatUtilities.APP_ID); string mch_id = WeChatUtilities.getConfigValue(WeChatUtilities.MCH_ID); //先确认,之后做随机数 string nonce_str = CommonUtilities.generateNonce(); string out_trade_no = "WXJSAPI_" + DateTime.Now.Ticks; try { Wx_OrderResult result = createUnifiedOrder(_openId, body, out_trade_no, amount, WeChatUtilities.TRADE_TYPE_JSAPI, ""); if (result.Result == "SUCCESS") { WxPayOrder order = new WxPayOrder() { Body = body, Time_Start = DateTime.Now, Mch_Id = mch_id, Open_Id = _openId, Trade_No = out_trade_no, Total_Fee = amount, Prepay_Id = result.PrepayId, Trade_Status = WeChatUtilities.TRADE_STATUS_CREATE, Trade_Type = WeChatUtilities.TRADE_TYPE_JSAPI }; offlineDB.WxPayOrder.Add(order); offlineDB.SaveChanges(); return(Json(new { result = "SUCCESS", prepay_id = result.PrepayId, amount }, JsonRequestBehavior.AllowGet)); } return(Json(new { result = "FAIL", msg = result.Message }, JsonRequestBehavior.AllowGet)); } catch (Exception e) { return(Json(new { result = "FAIL", msg = e.ToString() }, JsonRequestBehavior.AllowGet)); } }
public string CreateScriptFile(string friendlyName, bool generateDown = false) { // Create the directory if it doesn't exist if (!Directory.Exists(_migrationScriptLocation)) { Directory.CreateDirectory(_migrationScriptLocation); Log.Logger.Debug("Created Directory " + _migrationScriptLocation); } // Generate a filename for the up and down DateTime timeForDelta = CurrentTimestamp; string version = timeForDelta.ToString("yyyyMMddHHmmss"); string dateTimeString = timeForDelta.ToString("MM/dd/yyyy"); string text = FormattedFileName(friendlyName, MAX_COMMENT_LENGTH).Replace(" ", "_").ToLower(); string creatorString = Environment.UserName; // Create the UP script string fileNameUp = string.Format(DELTA_FILE_FORMAT, version, text, "up"); string physicalFileNameUp = Path.Combine(_migrationScriptLocation, fileNameUp); string templateUp = CommonUtilities.GetEmbeddedResourceContent("template.up").Replace(DATE_TIME_TOKEN, dateTimeString).Replace(CREATOR_TOKEN, creatorString); WriteTextToFile(physicalFileNameUp, templateUp); Log.Logger.Information("Created up script file " + physicalFileNameUp); if (generateDown) { // Create the DOWN script string fileNameDown = string.Format(DELTA_FILE_FORMAT, version, text, "down"); string physicalFileNameDown = Path.Combine(_migrationScriptLocation, fileNameDown); string templateDown = CommonUtilities.GetEmbeddedResourceContent("template.down").Replace(DATE_TIME_TOKEN, dateTimeString).Replace(CREATOR_TOKEN, creatorString); WriteTextToFile(physicalFileNameDown, templateDown); Log.Logger.Information("Created down script file " + physicalFileNameDown); } // Return the filename we created return(Path.GetFileNameWithoutExtension(physicalFileNameUp)); }
private void Create_Choice_Grid() { StringBuilder sb = new StringBuilder(); List <DataAccess.AssessmentItemXChoice> listAdded = new List <DataAccess.AssessmentItemXChoice>(); foreach (DataAccess.AssessmentItemXChoice item in ListChoice) { DataAccess.AssessmentItemXChoice added_obj = listAdded.Find(o => o.Value == item.Value && o.ScoreValue == item.ScoreValue); List <DataAccess.AssessmentItemXChoice> listFound = ListChoice.FindAll(o => o.Value == item.Value && o.ScoreValue == item.ScoreValue); if (added_obj != null && listFound != null && listFound.Count > 1) { continue; } sb.Append("<tr>"); sb.Append("<th scope='row'>"); sb.Append(item.Order.ToString()); sb.Append("</th>"); sb.Append("<td>"); sb.Append(CommonUtilities.EditGridText(item.Value)); sb.Append("</td>"); sb.Append("<td>"); sb.Append(item.ScoreValue.ToString()); sb.Append("</td>"); sb.Append("<td>"); sb.Append(item.IsDefault.ToString()); sb.Append("</td>"); sb.Append("<td>"); sb.Append(@"<a href=javascript:DeleteItem('" + CommonUtilities.GlobalEncrypt(item.ID.ToString(), BSWSession.SessionKey) + "'); class='fa fa-remove' style='color:red;' ></a>"); sb.Append("</td>"); sb.Append("</tr>"); listAdded.Add(item); } grdChoiceBody.InnerHtml = sb.ToString(); }
public RESTStatus CancelUpload(SQLLib sql, object dummy, NetworkConnectionInfo ni) { if (ni.Upload == null) { return(RESTStatus.Success); } if (ni.Upload.Data != null) { ni.Upload.Data.Close(); ni.Upload.Data.Dispose(); if (ni.Upload.TempFilename != "") { try { CommonUtilities.SpecialDeleteFile(Settings.Default.DataPath + ni.Upload.TempFilename); } catch { } } } ni.Upload = null; return(RESTStatus.Success); }
/// <summary> /// Gets headers from WSE XTestStep /// </summary> /// <param name="xTestStep">WSE XTestStep</param> /// <param name="tql">tql to get Header XTestStepValue from WSE XTestStep</param> /// <returns>All headers as a dictionary</returns> public Dictionary <string, string> Parse(XTestStep xTestStep, string tql) { var headersDict = new Dictionary <string, string>(); try { List <TCObject> headers = xTestStep.Search(tql); foreach (TCObject header in headers) { XTestStepValue headerAttribute = (XTestStepValue)header; if (string.IsNullOrEmpty(headerAttribute.Value)) { continue; } headersDict.Add(headerAttribute.Name, CommonUtilities.RemoveExtraDoubleQuotes(headerAttribute.Value)); } } catch (Exception) { // do nothing as this could happen possibly, just move on with the other attributes } return(headersDict); }
protected override void ApplyScaffoldingChanges(CloudRuntimePackage package) { string rootPath = CommonUtilities.GetServiceRootPath(FilePath); if (CloudServiceProject.Components.StartupTaskExists(RoleName, Resources.CacheStartupCommand)) { CloudServiceProject.Components.SetStartupTaskVariable( RoleName, Resources.CacheRuntimeUrl, package.PackageUri.ToString(), Resources.CacheStartupCommand); } else { Variable emulated = new Variable { name = Resources.EmulatedKey, RoleInstanceValue = new RoleInstanceValueElement { xpath = "/RoleEnvironment/Deployment/@emulated" } }; Variable cacheRuntimeUrl = new Variable { name = Resources.CacheRuntimeUrl, value = package.PackageUri.ToString() }; CloudServiceProject.Components.AddStartupTask( RoleName, Resources.CacheStartupCommand, ExecutionContext.elevated, emulated, cacheRuntimeUrl); } }
public override User FindById(int id) { try { Log.DebugFormat(LogMessage.FetchByIdBegin, GetName(), id); User user = Context.Users.FirstOrDefault(u => u.Id == id); if (user == null) { Log.WarnFormat(LogMessage.FetchByIdNotFound, GetName(), id); throw new EntityNotFoundException("کاربر مورد نظر در سیستم ثبت نگردیده است"); } Log.DebugFormat(LogMessage.FetchByIdFinished, GetName(), id); return(user); } catch (Exception ex) { if (!CommonUtilities.IsUserInterfaceException(ex)) { Log.Error(String.Format(LogMessage.FetchByIdError, GetName(), id), ex); throw new UserInterfaceException("خطا در دریافت اطلاعات کاربر از سیستم بر اساس شناسه"); } throw; } }
/// <summary> /// Method to get Html for Affiliate links /// </summary> /// <param name="tributeType">Tribute Type</param> public void AffiliateLinks(string tributeType) { CommonUtilities objUtil = new CommonUtilities(); //divAddSense.InnerHtml = objUtil.AffiliateLinks(tributeType); }
/// <summary> /// This function will get the values (User Id and Tribute Detail) from the session /// </summary> private void GetValuesFromSession() { try { StateManager objStateManager = StateManager.Instance; //to get logged in user name from session as user is logged in user objSessionValue = (SessionValue)objStateManager.Get("objSessionvalue", StateManager.State.Session); //LHK:for empty div above body if (TributeCustomHeader.Visible) { if (objSessionValue == null) ytHeader.Visible = false; } //LHK: till here objTribute = (Tributes)objStateManager.Get("TributeSession", StateManager.State.Session); if (objTribute != null) { if (objTribute.TributeId <= 0 && Session["PhotoAlbumTributeSession"] != null) { objTribute = Session["PhotoAlbumTributeSession"] as Tributes; } } else if (Session["PhotoAlbumTributeSession"] != null) { objTribute = Session["PhotoAlbumTributeSession"] as Tributes; } if (Request.QueryString["fbmode"] != null) { if (Request.QueryString["fbmode"] == "facebook") { _tributeId = int.Parse(Request.QueryString["TributeId"].ToString()); _tributeType = Request.QueryString["TributeType"].ToString(); _tributeTypeName = Request.QueryString["TributeType"].ToString().ToLower().Replace("new baby", "newbaby"); _tributeName = Request.QueryString["TributeName"].ToString(); _tributeUrl = Request.QueryString["TributeUrl"].ToString(); } else Response.Redirect(Redirect.RedirectToPage(Redirect.PageList.Inner2LoginPage.ToString()), false); } else if ((Request.QueryString["videoType"] != null) && (Request.QueryString["videoId"] != null)) { int videoId = int.Parse(Request.QueryString["videoId"].ToString()); TributesPortal.BusinessLogic.VideoManager videoManager = new TributesPortal.BusinessLogic.VideoManager(); Videos videos = videoManager.GetVideoTributeDetails(videoId); if (!(string.IsNullOrEmpty(objTribute.TypeDescription))) { objTribute.TributeName = videos.TributeName; _tributeName = objTribute.TributeName; _isActive = videos.IsTributeActive; _tributeType = objTribute.TypeDescription; _tributeTypeName = objTribute.TypeDescription.ToLower().Replace("new baby", "newbaby"); _tributeUrl = Request.QueryString["TributeUrl"].ToString(); } } else if (!Equals(objTribute, null)) { if (objTribute.TributeId > 0) { _tributeId = objTribute.TributeId; _tributeType = objTribute.TypeDescription; _tributeTypeName = objTribute.TypeDescription.ToLower().Replace("new baby", "newbaby"); _tributeName = objTribute.TributeName; _createdDate = objTribute.CreatedDate; _tributeUrl = objTribute.TributeUrl; _isActive = objTribute.IsActive; } if (Session["tributeEndDate"] != null) _endDate = (DateTime)Session["tributeEndDate"]; } else { Response.Redirect(Redirect.RedirectToPage(Redirect.PageList.Inner2LoginPage.ToString()), false); } if (Session["TributeCreatedDate"] != null && (Convert.ToDateTime(Session["TributeCreatedDate"])) < Convert.ToDateTime(WebConfig.Launch_Day) && DateTime.Today <= Convert.ToDateTime(WebConfig.Launch_Day).AddDays(180)) { CommonUtilities utility = new CommonUtilities(); if (objSessionValue != null && objSessionValue.UserId > 0) { if (!utility.ReadCookie(objSessionValue.UserId)) { utility.CreateCookie(objSessionValue.UserId); } } else if (objSessionValue == null) { if (!utility.ReadCookie(0)) { utility.CreateCookie(-1); } } } if (!Equals(objSessionValue, null)) { _userId = objSessionValue.UserId; _userName = objSessionValue.UserName; _firstName = objSessionValue.FirstName; _lastName = objSessionValue.LastName; _emailID = objSessionValue.UserEmail; } else { if (_isActive.Equals(false)) { SetExpiry(); } } //else page number is 1 if (Request.QueryString["PageNo"] != null) currentPage = int.Parse(Request.QueryString["PageNo"].ToString()); else currentPage = 1; //to set values to hidden variables for facebook hdnTributeId.Value = _tributeId.ToString(); hdnTributeName.Value = _tributeName; hdnTributeType.Value = _tributeType; hdnTributeUrl.Value = _tributeUrl; if (Session["TributeSession"] == null) CreateTributeSession(); //to create the tribute session values if user comest o this page from link or from favorites list. if (_packageId != 1) { if (_isActive.Equals(false)) { SetExpiry(); if (_endDate != null && _endDate < DateTime.Today) { TimeSpan diff = DateTime.Now.Subtract(DateTime.Parse(_endDate.ToString())); } } } } catch (Exception ex) { throw ex; } }
/// <summary> /// set the correct paging values and display next/previous buttons accordingly /// </summary> /// <param name="_TotalCount"></param> private void SetPaging(int _TotalCount) { //COMDIFFRES: (Paging implementation has been changed, hence the function definition)this function definition is different from .com version int pageCount = 0; int pagesize = int.Parse(WebConfig.PagingSize_guestBook); if (_TotalCount % pagesize == 0) { pageCount = _TotalCount / pagesize; } else { pageCount = (_TotalCount / pagesize) + 1; } CommonUtilities objUtilities = new CommonUtilities(); // Added by Ashu on Oct 3, 2011 for rewrite URL var sApplicationType = ConfigurationManager.AppSettings["ApplicationType"].ToString(); if (sApplicationType.ToLower() == "yourmoments") paging.InnerHtml = objUtilities.DrawPaging(pagenumber, pageCount, "moments.aspx"); else paging.InnerHtml = objUtilities.DrawPaging(pagenumber, pageCount, "tributes.aspx"); }