public static bool HasPendingChanges(Lib.Data.Drug drug) { if( drug == null || !drug.ID.HasValue ) return false; return HasPendingChanges(drug.ID); }
/// <summary> /// Based on the current date, calculates the next time a certification will need /// to be renewed. /// </summary> /// <param name="drug">The Drug to look-up. Only the Drug.ID is needed.</param> /// <param name="base_date">The DateTime to base the calculate off of.</param> /// <returns>DateTime reflecting the base_date plus the Drugs renewal period.</returns> public static DateTime CalculateRenewalDate(Lib.Data.Drug drug, DateTime base_date) { // MJL 2013-11-05 // TODO: Implement the method return (base_date + GetRenewalPeriod(drug)); }
public frmPointCommandHistory(Lib.Manager Manager, Outstation O, Point P) { InitializeComponent(); _manager = Manager; _o = O; _p = P; }
public void ContextMenuOpening(Lib.Control Control) { Control.GetContextMenuItem<ToolStripTextBox>("Minimum Text Box").Text = Control.Settings["minimum"]; Control.GetContextMenuItem<ToolStripTextBox>("Maximum Text Box").Text = Control.Settings["maximum"]; Control.GetContextMenuItem<ToolStripTextBox>("Increment Text Box").Text = Control.Settings["increment"]; Control.GetContextMenuItem<ToolStripTextBox>("Decimal Places Text Box").Text = Control.Settings["decimal_places"]; Control.GetContextMenuItem<ToolStripTextBox>("Set Command Text Box").Text = Control.Settings["set_command"]; }
/// <summary> /// Run the code example. /// </summary> /// <param name="user">The DFP user object running the code example.</param> public override void Run(Lib.DfpUser user) { // Get the ContentMetadataKeyHierarchy service. ContentMetadataKeyHierarchyService contentMetadataKeyHierarchyService = (ContentMetadataKeyHierarchyService) user.GetService( DfpService.v201405.ContentMetadataKeyHierarchyService); // Set the ID of the content metadata key hierarchy to update. long contentMetadataKeyHierarchyId = long.Parse(_T("INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE")); // Set the ID of the custom targeting key to be added as a hierarchy level long customTargetingKeyId = long.Parse(_T("INSERT_CUSTOM_TARGETING_KEY_ID_HERE")); // Create a statement to get content metadata key hierarchies. StatementBuilder statementBuilder = new StatementBuilder() .Where("WHERE id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", contentMetadataKeyHierarchyId); try { ContentMetadataKeyHierarchyPage page = contentMetadataKeyHierarchyService .getContentMetadataKeyHierarchiesByStatement(statementBuilder.ToStatement()); ContentMetadataKeyHierarchy contentMetadataKeyHierarchy = page.results[0]; // Update the content metadata key hierarchy by adding a hierarchy level. ContentMetadataKeyHierarchyLevel[] hierarchyLevels = contentMetadataKeyHierarchy .hierarchyLevels; ContentMetadataKeyHierarchyLevel hierarchyLevel = new ContentMetadataKeyHierarchyLevel(); hierarchyLevel.customTargetingKeyId = customTargetingKeyId; hierarchyLevel.hierarchyLevel = hierarchyLevels.Length + 1; List<ContentMetadataKeyHierarchyLevel> updatedHieratchyLevels = new List<ContentMetadataKeyHierarchyLevel>(); updatedHieratchyLevels.AddRange(hierarchyLevels); updatedHieratchyLevels.Add(hierarchyLevel); contentMetadataKeyHierarchy.hierarchyLevels = updatedHieratchyLevels.ToArray(); // Update the content hierarchy on the server. ContentMetadataKeyHierarchy[] contentMetadataKeyHierarchies = contentMetadataKeyHierarchyService.updateContentMetadataKeyHierarchies( new ContentMetadataKeyHierarchy[] {contentMetadataKeyHierarchy}); foreach (ContentMetadataKeyHierarchy updatedContentMetadataKeyHierarchy in contentMetadataKeyHierarchies) { Console.WriteLine("Content metadata key hierarchy with ID \"{0}\", name " + "\"{1}\" was updated.", updatedContentMetadataKeyHierarchy.id, updatedContentMetadataKeyHierarchy.name); } } catch (Exception ex) { Console.WriteLine("Failed to update content metadata key hierarchies. Exception " + "says \"{0}\"", ex.Message); } }
public void Create(Lib.Control Control) { var label = new Label(); label.AutoSize = true; Control.Controls.Add(label); Control.Settings.Add("get_command", string.Empty); }
public string GetEOCData(Lib.Data.Drug d) { StringBuilder eocData = new StringBuilder(); foreach(Eoc eoc in _complianceSvc.GetByDrug(d.ID ?? 0)) { eocData.Append(String.Format("data-{0}=\"1\" ", eoc.Name)); } return eocData.ToString(); }
public ToolStripItem[] GetContextMenuItems(Lib.Control Control) { var getCommandMenuItem = new ToolStripMenuItem("Get Command"); var getCommandTextBox = new ToolStripTextBox("Get Command Text Box"); getCommandMenuItem.DropDownItems.Add(getCommandTextBox); getCommandTextBox.TextChanged += new EventHandler(GetCommandToolStripTextBox_TextChanged); getCommandTextBox.Tag = Control; return new ToolStripItem[] { getCommandMenuItem }; }
public void UpdatePackageReference(Lib.PackageReference packageReference) { if (packageReference == null) { throw new ArgumentNullException("packageReference"); } this._packageReference = packageReference; this.Line = packageReference.StartLine; this.Column = packageReference.StartPos; }
public VulnerabilityTask(Lib.PackageReference packageReference, Lib.OSSIndex.Vulnerability vulnerability) { if (packageReference == null) { throw new ArgumentNullException("packageReference"); } if (vulnerability == null) { throw new ArgumentNullException("vulnerability"); } this._packageReference = packageReference; this._vulnerability = vulnerability; }
public int Login(LoginModel loginModel, out Lib.BResult result) { result = new BResult(); var user = _userProfileRepo.Get().Where(x => x.UserName.Equals(loginModel.UserName, StringComparison.CurrentCultureIgnoreCase)); if (user == null || user.Count() != 1) { result.AddError("error", "not found"); return -1; } else { return user.First().Id; } }
public static bool CanViewReport(Lib.Data.Report report) { if( string.IsNullOrWhiteSpace( report.ForRoles ) ) return Framework.Security.Manager.HasRole( "dev" ); var roles = report.ForRoles.Split( new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries ); foreach( var role in roles ) { if( Framework.Security.Manager.HasRole( role ) ) { return true; } } return false; }
/// <summary> /// Run the code example. /// </summary> /// <param name="user">The DFP user object running the code example.</param> public override void Run(Lib.DfpUser user) { // Get the ContentMetadataKeyHierarchy service. ContentMetadataKeyHierarchyService contentMetadataKeyHierarchyService = (ContentMetadataKeyHierarchyService) user.GetService( DfpService.v201403.ContentMetadataKeyHierarchyService); // Set the IDs of the custom targeting keys for the hierarchy. long customTargetingKeyId1 = long.Parse(_T("INSERT_LEVEL_ONE_CUSTOM_TARGETING_KEY_ID_HERE")); long customTargetingKeyId2 = long.Parse(_T("INSERT_LEVEL_TWO_CUSTOM_TARGETING_KEY_ID_HERE")); List<ContentMetadataKeyHierarchyLevel> hierarchyLevels = new List<ContentMetadataKeyHierarchyLevel>(); ContentMetadataKeyHierarchyLevel hierarchyLevel1 = new ContentMetadataKeyHierarchyLevel(); hierarchyLevel1.customTargetingKeyId = customTargetingKeyId1; hierarchyLevel1.hierarchyLevel = 1; hierarchyLevels.Add(hierarchyLevel1); ContentMetadataKeyHierarchyLevel hierarchyLevel2 = new ContentMetadataKeyHierarchyLevel(); hierarchyLevel2.customTargetingKeyId = customTargetingKeyId2; hierarchyLevel2.hierarchyLevel = 2; hierarchyLevels.Add(hierarchyLevel2); ContentMetadataKeyHierarchy contentMetadataKeyHierarchy = new ContentMetadataKeyHierarchy(); contentMetadataKeyHierarchy.name = "Content hierarchy #" + new Random().Next(int.MaxValue); contentMetadataKeyHierarchy.hierarchyLevels = hierarchyLevels.ToArray(); try { // Create the content metadata key hierarchy on the server. ContentMetadataKeyHierarchy[] contentMetadataKeyHierarchies = contentMetadataKeyHierarchyService.createContentMetadataKeyHierarchies( new ContentMetadataKeyHierarchy[] {contentMetadataKeyHierarchy}); foreach (ContentMetadataKeyHierarchy createdContentMetadataKeyHierarchy in contentMetadataKeyHierarchies) { Console.WriteLine("A content metadata key hierarchy with ID \"{0}\", name " + "\"{1}\" and {2} levels was created.", createdContentMetadataKeyHierarchy.id, createdContentMetadataKeyHierarchy.name, createdContentMetadataKeyHierarchy.hierarchyLevels.Length); } } catch (Exception ex) { Console.WriteLine("Failed to create content metadata key hierarchies. Exception says " + "\"{0}\"", ex.Message); } }
public static bool IsCertified( Lib.Data.UserProfile up, Lib.Data.Eoc eoc, Lib.Data.Drug drug, ref DateTime date_certified ) { if( up == null || eoc == null ) return false; var ut = up.UserType; if( !eoc.HasUserType( ut ) ) return false; if( ut.Name == "prescriber" ) { var user_eocs = Lib.Data.UserEoc.FindByUserandDrug(up.ID.Value, drug.ID.Value); foreach( var ue in user_eocs ) { if( ue.EocID == eoc.ID.Value ) { date_certified = ue.DateCompleted; return true; } } } else if( ut.Name == "provider" ) { var pu = Lib.Systems.Security.GetCurrentProviderUser(); if( pu == null || pu.PrimaryFacilityID == null ) return false; var facility_eocs = Lib.Data.FacilityEoc.FindByFacilityandDrug( pu.PrimaryFacilityID.Value, drug.ID.Value ); foreach( var fe in facility_eocs ) { if( fe.EocID == eoc.ID.Value ) { date_certified = fe.DateCompleted; return true; } } } else return false; return false; }
/// <summary> /// Run the code example. /// </summary> /// <param name="user">The DFP user object running the code example.</param> public override void Run(Lib.DfpUser user) { // Get the ContentMetadataKeyHierarchy service. ContentMetadataKeyHierarchyService contentMetadataKeyHierarchyService = (ContentMetadataKeyHierarchyService) user.GetService( DfpService.v201408.ContentMetadataKeyHierarchyService); // Set the ID of the content metadata key hierarchy to delete. long contentMetadataKeyHierarchyId = long.Parse(_T("INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE")); // Create a statement to select a content metadata key hierarchy. StatementBuilder statementBuilder = new StatementBuilder() .Where("WHERE id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", contentMetadataKeyHierarchyId); try { // Get content metadata key hierarchies by statement. ContentMetadataKeyHierarchyPage page = contentMetadataKeyHierarchyService .getContentMetadataKeyHierarchiesByStatement(statementBuilder.ToStatement()); ContentMetadataKeyHierarchy contentMetadataKeyHierarchy = page.results[0]; Console.WriteLine("Content metadata key hierarchy with ID \"{0}\" will be deleted.", contentMetadataKeyHierarchy.id); statementBuilder.RemoveLimitAndOffset(); // Create action. Google.Api.Ads.Dfp.v201408.DeleteContentMetadataKeyHierarchies action = new Google.Api.Ads.Dfp.v201408.DeleteContentMetadataKeyHierarchies(); // Perform action. UpdateResult result = contentMetadataKeyHierarchyService .performContentMetadataKeyHierarchyAction(action, statementBuilder.ToStatement()); Console.WriteLine("Number of content metadata key hierarchies deleted: {0}", result.numChanges); } catch (Exception ex) { Console.WriteLine("Failed to delete content metadata key hierarchies. " + "Exception says \"{0}\"", ex.Message); } }
void Run (String[] args) { Lib = new Lib (); NodeToNamespace = new Dictionary<Node, Namespace> (); if (ParseArguments (args) != 0) { Environment.Exit (1); } Node root = LoadXml (InputFileName); if (FilterFile != null) Filters = Filter.Load (XDocument.Load (FilterFile), out default_filter_mode); CreateTypes (root); CreateMembers (); GenerateCode (); }
public void AddEvent(Lib.DataRecord dr) { var ds = GetDataSeriesInfo(dr.Series); if (ds == null) throw new Exception("Invalid data series id"); if (dr.DataMap != null && dr.DataMap.Count > 0) { if (ds.Fields.Count != dr.DataMap.Count) throw new Exception("Invalid number of fields in data map - expected " + ds.Fields.Count); var lst = ds.Fields.Select(x => { if (!dr.DataMap.ContainsKey(x.Name)) throw new Exception("Missing data field: " + x.Name); return Convert.ToInt32(dr.DataMap[x.Name]); }); this.AddEvent(dr.Series, dr.Ts, lst); } else { if (dr.Data == null || dr.Data.Length == 0) throw new Exception("Missing event data"); if (dr.Data.Length != ds.Fields.Count) throw new Exception("Invalid number of data fields - expected " + ds.Fields.Count); this.AddEvent(dr.Series, dr.Ts, dr.Data.Select(x => Convert.ToInt32(x))); } }
public UserProfileModel GetById(int id, out Lib.BResult result) { result = new BResult(); var userDal = _userProfileRepo.Find(id); if (userDal == null) { result.AddError("error", "not found in db"); return null; } var user = new UserProfileModel(userDal); if (user == null) { result.AddError("error", "error converting to bll"); return null; } else { return user; } }
public static void Compare(Table table, Lib.Models.TeamStats teamStats) { if (1 != table.RowCount) Assert.Fail("Expected one total team stats row for comparison but got {0}", table.RowCount); var row = table.Rows[0]; if (row.ContainsKey("ABs")) Assert.AreEqual(int.Parse(row["ABs"]), teamStats.TotalAtBats); if (row.ContainsKey("Runs")) Assert.AreEqual(int.Parse(row["Runs"]), teamStats.TotalRuns); if (row.ContainsKey("Hits")) Assert.AreEqual(int.Parse(row["Hits"]), teamStats.TotalHits); if (row.ContainsKey("Doubles")) Assert.AreEqual(int.Parse(row["Doubles"]), teamStats.TotalDoubles); if (row.ContainsKey("Triples")) Assert.AreEqual(int.Parse(row["Triples"]), teamStats.TotalTriples); if (row.ContainsKey("HomeRuns")) Assert.AreEqual(int.Parse(row["HomeRuns"]), teamStats.TotalHomeRuns); if (row.ContainsKey("RBIs")) Assert.AreEqual(int.Parse(row["RBIs"]), teamStats.TotalRunsBattedIn); if (row.ContainsKey("Walks")) Assert.AreEqual(int.Parse(row["Walks"]), teamStats.TotalWalks); if (row.ContainsKey("StrikeOuts")) Assert.AreEqual(int.Parse(row["StrikeOuts"]), teamStats.TotalStrikeOuts); if (row.ContainsKey("Average")) Assert.AreEqual(double.Parse(row["Average"]), teamStats.TotalAverage); if (row.ContainsKey("OnBasePercentage")) Assert.AreEqual(double.Parse(row["OnBasePercentage"]), teamStats.TotalOnBasePercentage); }
public void Create(Lib.Control Control) { var label = new Label(); var padding = new Padding(); var numericUpDown = new NumericUpDown(); padding.Top = 6; label.Padding = padding; label.AutoSize = true; Control.Controls.Add(label); numericUpDown.Tag = Control; numericUpDown.Size = new Size(100, 20); numericUpDown.ValueChanged += new EventHandler(NumericUpDown_ValueChanged); Control.Controls.Add(numericUpDown); Control.Settings.Add("minimum", "0"); Control.Settings.Add("maximum", "100"); Control.Settings.Add("increment", "1"); Control.Settings.Add("decimal_places", "0"); Control.Settings.Add("set_command", string.Empty); }
public ToolStripItem[] GetContextMenuItems(Lib.Control Control) { var minimumMenuItem = new ToolStripMenuItem("Minimum"); var minimumTextBox = new ToolStripTextBox("Minimum Text Box"); var maximumMenuItem = new ToolStripMenuItem("Maximum"); var maximumTextBox = new ToolStripTextBox("Maximum Text Box"); var incrementMenuItem = new ToolStripMenuItem("Increment"); var incrementTextBox = new ToolStripTextBox("Increment Text Box"); var decimalPlacesMenuItem = new ToolStripMenuItem("Decimal Places"); var decimalPlacesTextBox = new ToolStripTextBox("Decimal Places Text Box"); var setCommandMenuItem = new ToolStripMenuItem("Set Command"); var setCommandTextBox = new ToolStripTextBox("Set Command Text Box"); minimumMenuItem.DropDownItems.Add(minimumTextBox); minimumTextBox.TextChanged += new EventHandler(MinimumTextBox_TextChanged); minimumTextBox.Tag = Control; maximumMenuItem.DropDownItems.Add(maximumTextBox); maximumTextBox.TextChanged += new EventHandler(MaximumTextBox_TextChanged); maximumTextBox.Tag = Control; incrementMenuItem.DropDownItems.Add(incrementTextBox); incrementTextBox.TextChanged += new EventHandler(IncrementTextBox_TextChanged); incrementTextBox.Tag = Control; decimalPlacesMenuItem.DropDownItems.Add(decimalPlacesTextBox); decimalPlacesTextBox.TextChanged += new EventHandler(DecimalPlacesTextBox_TextChanged); decimalPlacesTextBox.Tag = Control; setCommandMenuItem.DropDownItems.Add(setCommandTextBox); setCommandTextBox.TextChanged += new EventHandler(SetCommandTextBox_TextChanged); setCommandTextBox.Tag = Control; return new ToolStripItem[] { minimumMenuItem, maximumMenuItem, incrementMenuItem, decimalPlacesMenuItem, setCommandMenuItem }; }
/// <summary> /// Run the code example. /// </summary> /// <param name="user">The DFP user object running the code example.</param> public override void Run(Lib.DfpUser user) { // Get the ContentMetadataKeyHierarchy service. ContentMetadataKeyHierarchyService contentMetadataKeyHierarchyService = (ContentMetadataKeyHierarchyService) user.GetService( DfpService.v201408.ContentMetadataKeyHierarchyService); // Create a statement to get all content metadata key hierarchies StatementBuilder statementBuilder = new StatementBuilder() .OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); try { int totalResultSetSize = 0; do { // Get content metadata key hierarchies by statement. ContentMetadataKeyHierarchyPage page = contentMetadataKeyHierarchyService .getContentMetadataKeyHierarchiesByStatement(statementBuilder.ToStatement()); if (page.results != null) { totalResultSetSize = page.totalResultSetSize; int i = page.startIndex; foreach (ContentMetadataKeyHierarchy contentMetadataKeyHierarchy in page.results) { Console.WriteLine("{0}) Content metadata key hierarchy with ID \"{1}\", " + "and name \"{2}\" was found.", i++, contentMetadataKeyHierarchy.id, contentMetadataKeyHierarchy.name); } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < totalResultSetSize); Console.WriteLine("Number of results found: {0}", totalResultSetSize); } catch (Exception ex) { Console.WriteLine("Failed to get content metadata key hierarchies. Exception " + "says \"{0}\"", ex.Message); } }
public frmPointSummary(Lib.Manager Manager) { InitializeComponent(); this._manager = Manager; }
protected void RenderQuestion(HtmlTextWriter writer, Lib.Data.DSQ.Question q) { if (q==null || !q.ID.HasValue) return; IMarkdownService markdownSvc = new MarkdownService(enableSyntaxHighlighting: true); IComplianceRepository complianceRepo = ObjectFactory.GetInstance<IComplianceRepository>(); IDsqRepository dsqRepo = ObjectFactory.GetInstance<IDsqRepository>(); string a = null; if (DrugID != null) { var answer = Lib.Data.DSQ.Answer.FindByDrug(DrugID.Value, q.ID.Value); if (answer != null && answer.ID.HasValue) a = answer.Value; } if (!q.ShouldShowQuestion(false, a)) return; var children = Lib.Data.DSQ.Question.FindByParent(q); bool has_children = false; if (children != null && children.Count > 0) has_children = true; if(q.HideFromView) { // if the answere was no, we don't care if it has any // children if(q.FieldType == "Yes/No" && a == "No") return; if( has_children ) { foreach( var cq in children ) RenderQuestion( writer, cq ); } return; } Eoc eocForQ = complianceRepo.GetEoc(DrugID.Value, q.ID.Value); bool for_eoc = false; if(eocForQ != null) { if(eocForQ.AppliesTo.Any(r => Framework.Security.Manager.HasRole(r))) { for_eoc = true; } } string cssClass = "clearfix form-row"; if (has_children) cssClass += " has-children"; if (q.ParentID.HasValue) { writer.AddAttribute("data-parent-id", q.ParentID.Value.ToString()); writer.AddAttribute("data-parent-checks", q.ParentChecks); cssClass += " has-parent"; } writer.AddAttribute("data-id", q.ID.Value.ToString()); writer.AddAttribute("class", cssClass); writer.RenderBeginTag("div"); writer.AddAttribute("class", "form-label"); writer.AddAttribute("for", "form-q-"+q.ID.Value.ToString()); writer.RenderBeginTag("label"); if( for_eoc ) { writer.AddAttribute( "class", "form-label-text" ); writer.RenderBeginTag( "span" ); } writer.WriteEncodedText(q.ViewText); if( for_eoc ) { writer.RenderEndTag(); writer.AddAttribute( "class", "form-label-required" ); writer.RenderBeginTag( "span" ); if( !string.IsNullOrEmpty( a ) ) writer.WriteEncodedText( a ); writer.RenderEndTag(); } writer.RenderEndTag(); writer.AddAttribute("class", "form-input"); writer.RenderBeginTag("div"); writer.AddAttribute("class", "form-info"); writer.AddAttribute("name", "q-" + q.ID.Value.ToString()); writer.RenderBeginTag("span"); switch (q.FieldType) { case "Checkbox List": RenderQuestion_CheckboxList(writer, q, a); break; case "Link List": case "EOC": RenderQuestion_LinkList(writer, q, a); break; case "TextArea": // MJL - This is not the most efficient solution. Saving the // converted text would be more efficient. This approach keeps // Markdown available for editing. writer.Write(markdownSvc.ToHtml(a)); break; default: if( !string.IsNullOrEmpty(a) ) writer.WriteEncodedText(a); break; } writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderEndTag(); bool eoc_applies = false; Lib.Data.Eoc eoc = null; if( for_eoc ) { /* eoc = new Lib.Data.Eoc( long.Parse(q.Answers) ); if( eoc != null ) { var profile = Systems.Security.GetCurrentProfile(); if( profile != null && eoc.HasUserType( profile.UserTypeID ) ) eoc_applies = true; } */ // code has been changed to only display as an eoc if the // eoc applies to the current user. eoc_applies = for_eoc; } if( has_children || eoc_applies ) { writer.AddAttribute("id", "form-q-" + q.ID.Value.ToString()+"-children"); writer.AddAttribute("class", "contains-children"); writer.RenderBeginTag("div"); /* var drugs = Lib.Systems.Lists.GetMyDrugList().GetItems<Lib.Data.Drug>(); bool has_drug = false; foreach( var d in drugs ) if( d.ID == Drug.ID ) has_drug = true; */ var userList = Lib.Systems.Lists.GetMyDrugList().GetItems(); bool has_drug = userList.Any(x => x.ItemID == Drug.ID); if( eoc_applies && has_drug ) { PrescriberEoc prescriberEoc = complianceRepo.Find(Systems.Security.GetCurrentProfile().ID ?? 0, Drug.ID ?? 0, eocForQ.Id); bool is_certified = prescriberEoc != null ? prescriberEoc.CompletedAt != null : false; DateTime? date_certified = prescriberEoc != null ? prescriberEoc.CompletedAt : null; writer.AddAttribute( "data-parent-id", q.ID.Value.ToString() ); writer.AddAttribute( "data-parent-checks", "Required|Optional" ); writer.AddAttribute( "data-id", q.ID.Value.ToString() + "-certify" ); writer.AddAttribute( "class", "clearfix form-row has-parent eoc-certify-row" + ((is_certified) ? " eoc-certified" : "") ); writer.RenderBeginTag( "div" ); { writer.AddAttribute( "class", "label-wrapper clearfix" ); writer.RenderBeginTag( "div" ); { writer.AddAttribute( "class", "form-label" ); writer.AddAttribute( "for", "form-q-" + q.ID.Value.ToString() ); writer.RenderBeginTag( "label" ); { writer.WriteEncodedText( "Yes, I acknowledge that I am aware of the " + q.ViewText + " requirement for this REMS medication" ); } writer.RenderEndTag(); } writer.RenderEndTag(); writer.AddAttribute( "class", "form-input" ); writer.RenderBeginTag( "div" ); { if( is_certified ) { writer.AddAttribute( "alt", "Certified" ); writer.AddAttribute( "class", "eoc-certified-icon" ); writer.AddAttribute( "src", "/images/Warning_Green_Check.png" ); writer.RenderBeginTag( "img" ); writer.RenderEndTag(); writer.RenderBeginTag( "span" ); { writer.WriteEncodedText( "Complete as of " + date_certified.Value.ToShortDateString() + " " + date_certified.Value.ToShortTimeString() ); } writer.RenderEndTag(); } else { writer.AddAttribute( "alt", "Not Certified" ); writer.AddAttribute( "class", "eoc-certified-icon" ); writer.AddAttribute( "src", "/images/Warning_Yellow_Exclimation.png" ); writer.RenderBeginTag( "img" ); writer.RenderEndTag(); writer.AddAttribute( "class", "button ajax-button" ); writer.AddAttribute( "href", "/api/App/Users/Certified?drug_id=" + Drug.ID.Value + "&eoc_name=" + eocForQ.Name ); writer.RenderBeginTag( "a" ); { writer.WriteEncodedText( "YES" ); } writer.RenderEndTag(); writer.RenderBeginTag( "span" ); { writer.WriteEncodedText( "Reviewed Requirements?" ); } writer.RenderEndTag(); } } writer.RenderEndTag(); } writer.RenderEndTag(); } if( has_children ) { foreach( var cq in children ) RenderQuestion( writer, cq ); } writer.RenderEndTag(); } }
///<summary> Render planner UI panel </summary> internal static void Render() { // if there is something in the editor if (EditorLogic.RootPart != null) { // start header GUILayout.BeginHorizontal(Styles.title_container); // body selector GUILayout.Label(new GUIContent(FlightGlobals.Bodies[body_index].name, "Target body"), leftmenu_style); if (Lib.IsClicked()) { body_index = (body_index + 1) % FlightGlobals.Bodies.Count; if (body_index == 0) { ++body_index; } update = true; } else if (Lib.IsClicked(1)) { body_index = (body_index - 1) % FlightGlobals.Bodies.Count; if (body_index == 0) { body_index = FlightGlobals.Bodies.Count - 1; } update = true; } // sunlight selector GUILayout.Label(new GUIContent(sunlight ? Icons.sun_white : Icons.sun_black, "In sunlight/shadow"), icon_style); if (Lib.IsClicked()) { sunlight = !sunlight; update = true; } // situation selector GUILayout.Label(new GUIContent(situations[situation_index], "Target situation"), rightmenu_style); if (Lib.IsClicked()) { situation_index = (situation_index + 1) % situations.Length; update = true; } else if (Lib.IsClicked(1)) { situation_index = (situation_index == 0 ? situations.Length : situation_index) - 1; update = true; } // end header GUILayout.EndHorizontal(); // render panel panel.Render(); } // if there is nothing in the editor else { // render quote GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.Label("<i>In preparing for space, I have always found that\nplans are useless but planning is indispensable.\nWernher von Kerman</i>", quote_style); GUILayout.EndHorizontal(); GUILayout.Space(Styles.ScaleFloat(10.0f)); } }
///<summary> Add radiation sub-panel, including tooltips </summary> private static void AddSubPanelRadiation(Panel p) { // get first radiation rule // - guaranteed to exist, as this panel is not rendered if it doesn't // - even without crew, it is safe to evaluate the modifiers that use it Rule rule = Profile.rules.Find(k => k.modifiers.Contains("radiation")); // detect if it use shielding bool use_shielding = rule.modifiers.Contains("shielding"); // calculate various radiation levels double[] levels = new[] { Math.Max(Radiation.Nominal, (env_analyzer.surface_rad + vessel_analyzer.emitted)), // surface Math.Max(Radiation.Nominal, (env_analyzer.magnetopause_rad + vessel_analyzer.emitted)), // inside magnetopause Math.Max(Radiation.Nominal, (env_analyzer.inner_rad + vessel_analyzer.emitted)), // inside inner belt Math.Max(Radiation.Nominal, (env_analyzer.outer_rad + vessel_analyzer.emitted)), // inside outer belt Math.Max(Radiation.Nominal, (env_analyzer.heliopause_rad + vessel_analyzer.emitted)), // interplanetary Math.Max(Radiation.Nominal, (env_analyzer.extern_rad + vessel_analyzer.emitted)), // interstellar Math.Max(Radiation.Nominal, (env_analyzer.storm_rad + vessel_analyzer.emitted)) // storm }; // evaluate modifiers (except radiation) List <string> modifiers_except_radiation = new List <string>(); foreach (string s in rule.modifiers) { if (s != "radiation") { modifiers_except_radiation.Add(s); } } double mod = Modifiers.Evaluate(env_analyzer, vessel_analyzer, resource_sim, modifiers_except_radiation); // calculate life expectancy at various radiation levels double[] estimates = new double[7]; for (int i = 0; i < 7; ++i) { estimates[i] = rule.fatal_threshold / (rule.degeneration * mod * levels[i]); } // generate tooltip RadiationModel mf = Radiation.Info(env_analyzer.body).model; string tooltip = Lib.BuildString ( "<align=left />", String.Format("{0,-20}\t<b>{1}</b>\n", "surface", Lib.HumanReadableDuration(estimates[0])), mf.has_pause ? String.Format("{0,-20}\t<b>{1}</b>\n", "magnetopause", Lib.HumanReadableDuration(estimates[1])) : "", mf.has_inner ? String.Format("{0,-20}\t<b>{1}</b>\n", "inner belt", Lib.HumanReadableDuration(estimates[2])) : "", mf.has_outer ? String.Format("{0,-20}\t<b>{1}</b>\n", "outer belt", Lib.HumanReadableDuration(estimates[3])) : "", String.Format("{0,-20}\t<b>{1}</b>\n", "interplanetary", Lib.HumanReadableDuration(estimates[4])), String.Format("{0,-20}\t<b>{1}</b>\n", "interstellar", Lib.HumanReadableDuration(estimates[5])), String.Format("{0,-20}\t<b>{1}</b>", "storm", Lib.HumanReadableDuration(estimates[6])) ); // render the panel p.AddSection("RADIATION", string.Empty, () => { p.Prev(ref special_index, panel_special.Count); update = true; }, () => { p.Next(ref special_index, panel_special.Count); update = true; }); p.AddContent("surface", Lib.HumanReadableRadiation(env_analyzer.surface_rad + vessel_analyzer.emitted), tooltip); p.AddContent("orbit", Lib.HumanReadableRadiation(env_analyzer.magnetopause_rad), tooltip); if (vessel_analyzer.emitted >= 0.0) { p.AddContent("emission", Lib.HumanReadableRadiation(vessel_analyzer.emitted), tooltip); } else { p.AddContent("active shielding", Lib.HumanReadableRadiation(-vessel_analyzer.emitted), tooltip); } p.AddContent("shielding", rule.modifiers.Contains("shielding") ? Habitat.Shielding_to_string(vessel_analyzer.shielding) : "n/a", tooltip); }
///<summary> Run simulators and update the planner UI sub-panels </summary> internal static void Update() { // get vessel crew manifest VesselCrewManifest manifest = KSP.UI.CrewAssignmentDialog.Instance.GetManifest(); if (manifest == null) { return; } // check for number of crew change if (vessel_analyzer.crew_count != manifest.CrewCount) { update = true; } // only update when we need to, repeat update a number of times to allow the simulators to catch up if (!(update || (update_counter++ < 3))) { return; } // clear the panel panel.Clear(); // if there is something in the editor if (EditorLogic.RootPart != null) { // get parts recursively List <Part> parts = Lib.GetPartsRecursively(EditorLogic.RootPart); // analyze using the settings from the panels user input env_analyzer.Analyze(FlightGlobals.Bodies[body_index], altitude_mults[situation_index], sunlight); vessel_analyzer.Analyze(parts, resource_sim, env_analyzer); resource_sim.Analyze(parts, env_analyzer, vessel_analyzer); // add ec panel AddSubPanelEC(panel); // add resource panel if (panel_resource.Count > 0) { AddSubPanelResource(panel, panel_resource[resource_index]); } // add special panel if (panel_special.Count > 0) { switch (panel_special[special_index]) { case "qol": AddSubPanelStress(panel); break; case "radiation": AddSubPanelRadiation(panel); break; case "reliability": AddSubPanelReliability(panel); break; } } // add environment panel switch (panel_environment[environment_index]) { case "habitat": AddSubPanelHabitat(panel); break; case "environment": AddSubPanelEnvironment(panel); break; } } update = false; }
public static void P_DamageFeedback(edict_t player) { gclient_t client; float side; float realcount, count, kick; float[] v = new float[] { 0, 0, 0 }; int r, l; float[] power_color = new[] { 0F, 1F, 0F }; float[] acolor = new[] { 1F, 1F, 1F }; float[] bcolor = new[] { 1F, 0F, 0F }; client = player.client; client.ps.stats[Defines.STAT_FLASHES] = 0; if (client.damage_blood != 0) { client.ps.stats[Defines.STAT_FLASHES] |= 1; } if (client.damage_armor != 0 && 0 == (player.flags & Defines.FL_GODMODE) && (client.invincible_framenum <= GameBase.level.framenum)) { client.ps.stats[Defines.STAT_FLASHES] |= 2; } count = (client.damage_blood + client.damage_armor + client.damage_parmor); if (count == 0) { return; } if ((client.anim_priority < Defines.ANIM_PAIN) & (player.s.modelindex == 255)) { client.anim_priority = Defines.ANIM_PAIN; if ((client.ps.pmove.pm_flags & pmove_t.PMF_DUCKED) != 0) { player.s.frame = M_Player.FRAME_crpain1 - 1; client.anim_end = M_Player.FRAME_crpain4; } else { xxxi = (xxxi + 1) % 3; switch (xxxi) { case 0: player.s.frame = M_Player.FRAME_pain101 - 1; client.anim_end = M_Player.FRAME_pain104; break; case 1: player.s.frame = M_Player.FRAME_pain201 - 1; client.anim_end = M_Player.FRAME_pain204; break; case 2: player.s.frame = M_Player.FRAME_pain301 - 1; client.anim_end = M_Player.FRAME_pain304; break; } } } realcount = count; if (count < 10) { count = 10; } if ((GameBase.level.time > player.pain_debounce_time) && 0 == (player.flags & Defines.FL_GODMODE) && (client.invincible_framenum <= GameBase.level.framenum)) { r = 1 + (Lib.Rand() & 1); player.pain_debounce_time = GameBase.level.time + 0.7F; if (player.health < 25) { l = 25; } else if (player.health < 50) { l = 50; } else if (player.health < 75) { l = 75; } else { l = 100; } GameBase.gi.Sound(player, Defines.CHAN_VOICE, GameBase.gi.Soundindex("*pain" + l + "_" + r + ".wav"), 1, Defines.ATTN_NORM, 0); } if (client.damage_alpha < 0) { client.damage_alpha = 0; } client.damage_alpha += count * 0.01F; if (client.damage_alpha < 0.2F) { client.damage_alpha = 0.2F; } if (client.damage_alpha > 0.6F) { client.damage_alpha = 0.6F; } Math3D.VectorClear(v); if (client.damage_parmor != 0) { Math3D.VectorMA(v, (float)client.damage_parmor / realcount, power_color, v); } if (client.damage_armor != 0) { Math3D.VectorMA(v, (float)client.damage_armor / realcount, acolor, v); } if (client.damage_blood != 0) { Math3D.VectorMA(v, (float)client.damage_blood / realcount, bcolor, v); } Math3D.VectorCopy(v, client.damage_blend); kick = Math.Abs(client.damage_knockback); if (kick != 0 && player.health > 0) { kick = kick * 100 / player.health; if (kick < count * 0.5) { kick = count * 0.5F; } if (kick > 50) { kick = 50; } Math3D.VectorSubtract(client.damage_from, player.s.origin, v); Math3D.VectorNormalize(v); side = Math3D.DotProduct(v, right); client.v_dmg_roll = kick * side * 0.3F; side = -Math3D.DotProduct(v, forward); client.v_dmg_pitch = kick * side * 0.3F; client.v_dmg_time = GameBase.level.time + Defines.DAMAGE_TIME; } client.damage_blood = 0; client.damage_armor = 0; client.damage_parmor = 0; client.damage_knockback = 0; }
public override bool Think(edict_t self) { edict_t ent; edict_t ignore; float[] point = new float[] { 0, 0, 0 }; float[] dir = new float[] { 0, 0, 0 }; float[] start = new float[] { 0, 0, 0 }; float[] end = new float[] { 0, 0, 0 }; int dmg; trace_t tr; if (GameBase.deathmatch.value != 0) { dmg = 5; } else { dmg = 10; } EdictIterator edit = null; while ((edit = GameBase.Findradius(edit, self.s.origin, 256)) != null) { ent = edit.o; if (ent == self) { continue; } if (ent == self.owner) { continue; } if (ent.takedamage == 0) { continue; } if (0 == (ent.svflags & Defines.SVF_MONSTER) && (null == ent.client) && (Lib.Strcmp(ent.classname, "misc_explobox") != 0)) { continue; } Math3D.VectorMA(ent.absmin, 0.5F, ent.size, point); Math3D.VectorSubtract(point, self.s.origin, dir); Math3D.VectorNormalize(dir); ignore = self; Math3D.VectorCopy(self.s.origin, start); Math3D.VectorMA(start, 2048, dir, end); while (true) { tr = GameBase.gi.Trace(start, null, null, end, ignore, Defines.CONTENTS_SOLID | Defines.CONTENTS_MONSTER | Defines.CONTENTS_DEADMONSTER); if (null == tr.ent) { break; } if ((tr.ent.takedamage != 0) && 0 == (tr.ent.flags & Defines.FL_IMMUNE_LASER) && (tr.ent != self.owner)) { GameCombat.T_Damage(tr.ent, self, self.owner, dir, tr.endpos, Globals.vec3_origin, dmg, 1, Defines.DAMAGE_ENERGY, Defines.MOD_BFG_LASER); } if (0 == (tr.ent.svflags & Defines.SVF_MONSTER) && (null == tr.ent.client)) { GameBase.gi.WriteByte(Defines.svc_temp_entity); GameBase.gi.WriteByte(Defines.TE_LASER_SPARKS); GameBase.gi.WriteByte(4); GameBase.gi.WritePosition(tr.endpos); GameBase.gi.WriteDir(tr.plane.normal); GameBase.gi.WriteByte(self.s.skinnum); GameBase.gi.Multicast(tr.endpos, Defines.MULTICAST_PVS); break; } ignore = tr.ent; Math3D.VectorCopy(tr.endpos, start); } GameBase.gi.WriteByte(Defines.svc_temp_entity); GameBase.gi.WriteByte(Defines.TE_BFG_LASER); GameBase.gi.WritePosition(self.s.origin); GameBase.gi.WritePosition(tr.endpos); GameBase.gi.Multicast(self.s.origin, Defines.MULTICAST_PHS); } self.nextthink = GameBase.level.time + Defines.FRAMETIME; return(true); }
public void Listen() { string username; string recv; bool fireCallback = true; active = true; try { Interlocked.Increment(ref Lib.connections); string clientip = userSocket.ClientEndpointId; Lib.log.Add(userSocket, null, "CONNECT (" + userSocket.ClientEndpointId + ") Online:" + Lib.connections); Commandprocessor cp = new Commandprocessor(); // Send the welcome screen to the user. userSocket.Send(Lib.Welcomescreen); userSocket.Send(Lib.Ansifboldyellow + "Developers: " + Lib.Ansifboldwhite + Lib.Creditsdev + "\r\n"); userSocket.Send(Lib.Ansifboldyellow + "Special Thanks: " + Lib.Ansifboldwhite + Lib.Creditsother + "\r\n\r\n" + Lib.Ansifwhite); // Authenticate this user. username = Lib.Authenticate(userSocket, cp); if (username == null) { // detected some socket error return; } if (username == null) { try { // If the user is already disconnected, this might fail so catch the exception userSocket.SendLine("Too many bad login attempts. Byte!"); Lib.Disco(userSocket, "too many bad logon attempts"); } catch { return; } return; } // Log this user as connected Actor theUser = Lib.GetByName(username); //theUser["connected"] = true; // Set the user's client socket theUser.UserSocket = this.userSocket; //theUser.Save(); while (enabled) { try { // if user disco, then socket is gone and we need to catch this exception recv = userSocket.GetResponse(); } catch { //Lib.PrintLine(DateTime.Now + " EXCEPTION in ClientListener (Waiting for client response): " + ex.Message + ex.StackTrace); // We should rather log these exceptions to the console // or to a log file return; } if (recv == null) { return; } cp.processcommand(userSocket, username, recv, false); } Lib.Disco(userSocket, "client listener switched off with the stoplistening method"); } catch (ThreadAbortException ex) { // Signal that we should just quit and not fire the // callback fireCallback = false; //Lib.PrintLine(DateTime.Now + " EXCEPTION in ClientListener (Thread aborted): " + ex.Message + ex.StackTrace); } finally { if (fireCallback) { // Fire the callback event IAsyncResult ar = clientDisconnectedEventHandler.BeginInvoke(this, null, null); } // We are no longer active active = false; } }
static void Main(string[] args) { Lib L = new Lib(); int ids = 0; int z; do { WriteLine("\nВведите: \n 1. Чтобы добавить студента \n 2. Чтобы изменить \n 3. Удалить \n 4. Вывести Ф.И.О. \n " + "5. Вывести информацию по ID \n 6. Возраст выбранного по ID студента\n 7. Студенты 18+, 18-\n 8. Поиск по фамилии\n 9. Фамилия и инициалы"); z = ToInt32(ReadLine()); WriteLine("\n"); if (z == 1) { //Добавить WriteLine("\nФ.И.О.: "); string fio = ReadLine(); WriteLine("Группа: "); int group = ToInt32(ReadLine()); WriteLine("Дата рождения дд.мм.гггг: "); string data = ReadLine(); L.addstud(ids, fio, group, data); ids++; } else if (z == 2) { //Изменить WriteLine("\nID студента: "); int idsT = ToInt32(ReadLine()); WriteLine("Ф.И.О.: "); string fio = ReadLine(); WriteLine("Группа: "); int group = ToInt32(ReadLine()); WriteLine("Дата рождения дд.мм.гггг: "); string data = ReadLine(); L.izmen(idsT, fio, group, data); } else if (z == 3) { //Удалить ids = ToInt32(ReadLine()); L.del(ids); } else if (z == 4) { L.show(); //Показать ФИО } else if (z == 5) { WriteLine("Введите ID студента"); int idss = ToInt32(ReadLine()); L.poiskID(idss); } else if (z == 6) { WriteLine("Введите ID студента"); int IDage = ToInt32(ReadLine()); L.age(IDage); } else if (z == 7) { WriteLine("Введите 's' инфа по <18лет\nВведите 'a' инфа по >18лет: "); string ss = ReadLine(); L.age18(ss); } else if (z == 8) { WriteLine("Введите фамилию студента: "); string sFIO = ReadLine(); L.searchFIO(sFIO); } else if (z == 9) { WriteLine("Введите ID студента: "); int IDstud = ToInt32(ReadLine()); L.inicfio(IDstud); } } while (z != 0); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_executionTimer = Stopwatch.StartNew(); m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script WindowsWASParseServerIndexScript.", m_taskId); try { ManagementScope cimvScope = null; ManagementScope defaultScope = null; // Check ManagementScope CIMV if (null == connection) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to WindowsWASParseServerIndexScript is null.", m_taskId); } else if (!connection.ContainsKey(@"cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else if (!connection.ContainsKey(@"default")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for Default namespace is not present in connection object.", m_taskId); } else { cimvScope = connection[@"cimv2"] as ManagementScope; defaultScope = connection[@"default"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed.", m_taskId); } else if (!defaultScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to Default namespace failed.", m_taskId); } } //Check Script attributes if (resultCode.Equals(ResultCodes.RC_SUCCESS)) { if (scriptParameters.ContainsKey("profilePath")) { m_profileHome = scriptParameters[@"profilePath"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter WAS Profile Path parameter.", m_taskId); } if (scriptParameters.ContainsKey("cellName")) { m_cell = scriptParameters[@"cellName"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter WAS Cell Name parameter.", m_taskId); } if (scriptParameters.ContainsKey("nodeName")) { m_node = scriptParameters[@"nodeName"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter WAS Node Name parameter.", m_taskId); } if (scriptParameters.ContainsKey("appsrv_Name")) { m_server = scriptParameters[@"appsrv_Name"]; } else { resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Missing parameter WAS Server Name parameter.", m_taskId); } } // Check Remote Process Temp Directory if (resultCode.Equals(ResultCodes.RC_SUCCESS)) { if (!connection.ContainsKey(@"TemporaryDirectory")) { connection[@"TemporaryDirectory"] = @"%TMP%"; } else { if (!connection[@"TemporaryDirectory"].Equals(@"%TMP%")) { if (!Lib.ValidateDirectory(m_taskId, connection[@"TemporaryDirectory"].ToString(), cimvScope)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Temporary directory {1} is not valid.", m_taskId, connection[@"TemporaryDirectory"].ToString()); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: User specified temp directory has been validated.", m_taskId); } } } } if (resultCode == ResultCodes.RC_SUCCESS) { // Gather Variables Xml path for the cell and node StringBuilder nVarPath = new StringBuilder(); nVarPath.Append(m_profileHome).Append(@"\config\cells\").Append(m_cell).Append(@"\nodes\").Append(m_node).Append(@"\variables.xml").Append(@"=nodeVarData"); BuildDataRow(s_nodeVarPath, nVarPath); // Get the resources file path StringBuilder rsrcPath = new StringBuilder(); rsrcPath.Append(m_profileHome).Append(@"\config\cells\").Append(m_cell).Append(@"\nodes\").Append(m_node).Append(@"\servers\").Append(m_server).Append(@"\resources.xml").Append(@"=rsrcFileData"); BuildDataRow(s_rsrcFilePath, rsrcPath); // Get the virtual hosts file path StringBuilder virtHostsPath = new StringBuilder(); virtHostsPath.Append(m_profileHome).Append(@"\config\cells\").Append(m_cell).Append(@"\virtualhosts.xml").Append(@"=virtHostsFileData"); BuildDataRow(s_virtHostsFilePath, virtHostsPath); // Parse ServerIndex file StringBuilder fileContent = new StringBuilder(); StringBuilder serverIndx = new StringBuilder(); serverIndx.Append(m_profileHome).Append(@"\config\cells\").Append(m_cell).Append(@"\nodes\").Append(m_node).Append(@"\serverindex.xml"); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Attempting to retrieve file {1}.", m_taskId, serverIndx.ToString()); if (Lib.ValidateFile(m_taskId, serverIndx.ToString(), cimvScope)) { using (IRemoteProcess rp = RemoteProcess.GetRemoteFile(m_taskId, cimvScope, serverIndx.ToString(), connection, tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) { // Launch the remote process. // This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Remote file retrieval operation completed with result code {1}.", m_taskId, resultCode.ToString()); fileContent.Append(rp.Stdout); } // Parse ServerIndex file content resultCode = parseServerIndxFile(fileContent.ToString(), m_server); } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: WAS Server Index file: {1} does not exist.", m_taskId, serverIndx.ToString()); resultCode = ResultCodes.RC_SUCCESS; } } } catch (Exception ex) { Lib.LogException(m_taskId, m_executionTimer, "Unhandled exception in WindowsWASParseServerIndexScript", ex); resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REMOTE_FILE; } CollectionScriptResults result = new CollectionScriptResults(resultCode, 0, null, null, null, false, m_dataRow.ToString()); Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script WindowsWASProfileFootprintScript2. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), result.ResultCode.ToString()); return(result); }
/// <summary> /// Parse WAS Server Index File. /// </summary> /// <param name="strFileContent">File Content</param> private ResultCodes parseServerIndxFile(string srvIndxContent, string server) { ResultCodes resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REMOTE_FILE; if (String.IsNullOrEmpty(srvIndxContent)) { return(resultCode); } Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Begin parsing WAS Server Index file.", m_taskId, server); try { XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(srvIndxContent); XmlNodeList nodes = xDoc.GetElementsByTagName("serverEntries"); StringBuilder portData = new StringBuilder(); foreach (XmlNode node in nodes) { string sName = node.Attributes["serverName"].Value; string sType = node.Attributes["serverType"].Value; if (string.Equals(server, sName)) { StringBuilder st = new StringBuilder(); st.Append(sType); BuildDataRow(s_serverType, st); XmlNodeList cNodes = node.ChildNodes; foreach (XmlNode child in cNodes) { if (string.Equals(child.Name, "specialEndpoints")) { StringBuilder pValue = new StringBuilder(); string pName = child.Attributes["endPointName"].Value; XmlNodeList epNodes = child.ChildNodes; foreach (XmlNode ep in epNodes) { if (string.Equals(ep.Name, "endPoint")) { string pNum = ep.Attributes["port"].Value; StringBuilder port = new StringBuilder(); port.Append(pNum); pValue.Append(@"PortName=").Append(pName).Append(@"<BDNA,1>").Append(@"PortNumber=").Append(pNum); /*if (string.Equals(pName, "WC_defaulthost")) { * BuildDataRow(s_port, port); * } */ if (portData.Length > 0) { portData.Append(BdnaDelimiters.DELIMITER_TAG); } portData.Append(pValue.ToString()); } } } } if (portData.Length > 0) { BuildDataRow(s_portsUsed, portData); } } } resultCode = ResultCodes.RC_SUCCESS; } catch (XmlException xex) { Lib.LogException(m_taskId, m_executionTimer, "Unhandled exception in WindowsWASParseServerIndexScript", xex); } return(resultCode); }
public IHttpActionResult Save() { Dictionary <string, object> RetData = new Dictionary <string, object>(); try { string Folder = ""; string slno = ""; imageTools tools = new imageTools(); Boolean isImageFile = false; Boolean isPdfFile = false; DataTable Dt_Record = new DataTable(); DataTable Dt_Records = new DataTable(); string uploadError = ""; Dictionary <string, object> SearchData = new Dictionary <string, object>(); Dictionary <string, string> Files2Remove = new Dictionary <string, string>(); var model = HttpContext.Current.Request.Form["record"]; pim_docm record = JsonConvert.DeserializeObject <pim_docm>(model); var columnList = HttpContext.Current.Request.Form["records"]; tablesd [] records = JsonConvert.DeserializeObject <tablesd[]>(columnList); string ServerImageURL = Lib.GetSeverImageURL(record._globalvariables.comp_code); string ServerReportPath = Lib.GetReportPath(record._globalvariables.comp_code); string ServerImagePath = Lib.GetImagePath(record._globalvariables.comp_code); using (DocService obj = new DocService()) { Dt_Record = obj.getDataTableRecord(record.doc_pkid); RetData = obj.Save(record, records, ServerImageURL); slno = RetData["slno"].ToString(); } // first save to report/temp folder System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files; string REPID = System.Guid.NewGuid().ToString().ToUpper(); ServerReportPath = Path.Combine(ServerReportPath, System.DateTime.Now.ToString("yyyy-MM-dd"), REPID); string smallname = ""; for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++) { isImageFile = false; isPdfFile = false; if (record.doc_file_name.ToUpper() == hfc[iCnt].FileName.ToUpper()) { if (hfc[iCnt].ContentType.ToString().ToUpper().StartsWith("IMAGE")) { isImageFile = true; smallname = "ts.jpg"; } if (Path.GetExtension(hfc[iCnt].FileName).ToUpper() == ".PDF") { isPdfFile = true; smallname = "ts.jpg"; } } SaveFile(ServerReportPath, smallname, hfc[iCnt], isImageFile, isPdfFile, record._globalvariables.comp_code); } if (smallname != "") { using (DocService obj = new DocService()) { obj.UpdateDocFileName(record, "doc_thumbnail", smallname); RetData["thumbnail"] = smallname; } } //then copy to original folder string sError = ""; if (record.doc_file_name.ToString().Trim().Length > 0) { Folder = Lib.getPath(ServerImagePath, record._globalvariables.comp_code, record.doc_table_name, record.doc_slno.ToString(), true); sError = Lib.CopyFile(Path.Combine(ServerReportPath, record.doc_file_name), Path.Combine(Folder, record.doc_file_name)); if (sError != "") { uploadError += "\n" + sError; using (DocService obj = new DocService()) { obj.UpdateDocFileName(record, "doc_file_name"); obj.UpdateDocFileName(record, "doc_thumbnail", ""); } } if (smallname != "") { sError = Lib.CopyFile(Path.Combine(ServerReportPath, smallname), Path.Combine(Folder, smallname)); } } foreach (tablesd mRow in records) { if (mRow.tabd_col_type == "FILE") { Folder = Lib.getPath(ServerImagePath, record._globalvariables.comp_code, record.doc_table_name, record.doc_slno.ToString(), true); sError = Lib.CopyFile(Path.Combine(ServerReportPath, mRow.tabd_col_value), Path.Combine(Folder, mRow.tabd_col_value)); if (sError != "") { uploadError += "\n" + sError; using (DocService obj = new DocService()) { obj.UpdateDocFileName(record, "COL_" + mRow.tabd_col_name); } } } } RetData.Add("uploaderror", uploadError); return(Ok(RetData)); } catch (Exception Ex) { return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Ex.Message.ToString()))); } }
void worker_DoWork(object sender, DoWorkEventArgs e) { Process[] processes = Process.GetProcessesByName("mmria-server"); foreach (Process process in processes) { process.Kill(); } processes = Process.GetProcessesByName("Menu"); foreach (Process process in processes) { process.Kill(); } processes = Process.GetProcessesByName("MakeView"); foreach (Process process in processes) { process.Kill(); } processes = Process.GetProcessesByName("Enter"); foreach (Process process in processes) { process.Kill(); } processes = Process.GetProcessesByName("Analysis"); foreach (Process process in processes) { process.Kill(); } processes = Process.GetProcessesByName("AnalysisDashboard"); foreach (Process process in processes) { process.Kill(); } //DownloadUpdates(); //DownloadDescription(); Lib lib = new Lib(); string file_name = System.Configuration.ConfigurationManager.AppSettings["selected_release"]; string ftp_user_id = System.Configuration.ConfigurationManager.AppSettings["ftp_user_id"]; string ftp_password = System.Configuration.ConfigurationManager.AppSettings["ftp_password"]; string[] file_list = System.Configuration.ConfigurationManager.AppSettings["release_text"].Split('\n'); string download_directory = EnsureTrailingSlash(System.Configuration.ConfigurationManager.AppSettings["download_directory"]); string root_directory = EnsureTrailingSlash(file_name.Substring(0, file_name.LastIndexOf('.'))); string ftp_site = System.Configuration.ConfigurationManager.AppSettings["ftp_site"] + "s/" + root_directory; for (int i = 0; i < file_list.Length; i++) { string[] pair = file_list[i].Split(':'); if (!string.IsNullOrWhiteSpace(pair[0]) && pair.Length == 2) { string download_file_name = pair[0].Trim(); string download_file_hash = pair[1].Trim(); string source = ftp_site + pair[0]; string destination = download_directory + root_directory + download_file_name; destination = destination.Replace("\\", "/"); source = source.Replace("\\", "/"); string target_directory = destination.Substring(0, destination.LastIndexOf('/')); if (!System.IO.Directory.Exists(target_directory)) { System.IO.Directory.CreateDirectory(target_directory); } int try_download_count = 0; string validation_compare = ""; bool download_not_attempted = true; do { lib.DownloadFile(ftp_user_id, ftp_password, source, destination); validation_compare = lib.GetHash(destination); try_download_count = try_download_count + 1; if (!System.IO.File.Exists(destination) && try_download_count > 1) { download_not_attempted = false; } if (validation_compare.Equals(download_file_hash, StringComparison.OrdinalIgnoreCase)) { download_not_attempted = false; } else if (try_download_count > 1) { download_not_attempted = false; } }while(download_not_attempted); double pct = (100.0 * i) / file_list.Length; int pctint = (int)Math.Truncate(pct); background_worker.ReportProgress(pctint, download_file_name); } } }
public abstract void Serialize(ref Lib.NewFastSerializer.SerializationWriter mySerializationWriter);
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { int rowCount = grvData.RowCount; int colCount = grvData.Columns.Count; ProductCheckForceModel model = new ProductCheckForceModel(); for (int i = 0; i < rowCount; i++) { try { progressBar1.Invoke((Action)(() => { progressBar1.Value = i + 1; })); txtRate.Invoke((Action)(() => { txtRate.Text = string.Format("{0}/{1}", i + 1, rowCount); })); // update CheckForce if (string.IsNullOrEmpty(grvData.GetRowCellValue(i, "F1").ToString().Trim()) || string.IsNullOrEmpty(grvData.GetRowCellValue(i, "F11").ToString().Trim())) { continue; } Expression expression = new Expression("ProductCode", Lib.ToString(grvData.GetRowCellValue(i, "F1"))); ArrayList lst = ProductBO.Instance.FindByExpression(expression); if (lst.Count <= 0) { continue; } string sql = string.Format("Select ID from ProductCheckForce Where ProductCode = '{0}' And ProductStepCode = '{1}'", Lib.ToString(grvData.GetRowCellValue(i, "F1")), Lib.ToString(grvData.GetRowCellValue(i, "F12"))); SqlDataReader reader = SqlHelper.ExecuteReader(DBUtils.GetDBConnectionString(), CommandType.Text, sql); if (reader.Read()) { model = ProductCheckForceBO.Instance.FindByPK(long.Parse(reader[0].ToString())) as ProductCheckForceModel; string[] CheckForce = Lib.ToString(grvData.GetRowCellValue(i, "F4")).Split('~'); model.CheckForceMin = TextUtils.ToDecimal(CheckForce[0]); model.CheckForceMax = TextUtils.ToDecimal(CheckForce[1]); model.GunNumber = Lib.ToInt(grvData.GetRowCellValue(i, "F5")); model.JobNumber = Lib.ToInt(grvData.GetRowCellValue(i, "F6")); model.QtyBuLong = Lib.ToInt(grvData.GetRowCellValue(i, "F7")); model.ShootNumber = Lib.ToInt(grvData.GetRowCellValue(i, "F8")); model.QtyOcBanGa = Lib.ToInt(grvData.GetRowCellValue(i, "F9")); model.QtyOcBanThat = Lib.ToInt(grvData.GetRowCellValue(i, "F10")); model.SetForce = Lib.ToDecimal(grvData.GetRowCellValue(i, "F11")); ProductCheckForceBO.Instance.Update(model); } else { model.ProductCode = Lib.ToString(grvData.GetRowCellValue(i, "F1")); string[] CheckForce = Lib.ToString(grvData.GetRowCellValue(i, "F4")).Split('~'); model.CheckForceMin = TextUtils.ToDecimal(CheckForce[0]); model.CheckForceMax = TextUtils.ToDecimal(CheckForce[1]); model.GunNumber = Lib.ToInt(grvData.GetRowCellValue(i, "F5")); model.JobNumber = Lib.ToInt(grvData.GetRowCellValue(i, "F6")); model.QtyBuLong = Lib.ToInt(grvData.GetRowCellValue(i, "F7")); model.ShootNumber = Lib.ToInt(grvData.GetRowCellValue(i, "F8")); model.QtyOcBanGa = Lib.ToInt(grvData.GetRowCellValue(i, "F9")); model.QtyOcBanThat = Lib.ToInt(grvData.GetRowCellValue(i, "F10")); model.SetForce = Lib.ToDecimal(grvData.GetRowCellValue(i, "F11")); model.ProductStepCode = Lib.ToString(grvData.GetRowCellValue(i, "F12")); ProductCheckForceBO.Instance.Insert(model); } } catch (Exception ex) { MessageBox.Show(i.ToString() + Environment.NewLine + ex.ToString()); } } }
public static void TestPerpend(int i, string line) { StringTokenizer tk = new StringTokenizer(line); float[] dir = new float[] { 0, 0, 0 }; float[] dst = new float[] { 0, 0, 0 }; float[] newdst = new float[] { 0, 0, 0 }; dir[0] = float.Parse(tk.NextToken()); dir[1] = float.Parse(tk.NextToken()); dir[2] = float.Parse(tk.NextToken()); tk.NextToken(); dst[0] = float.Parse(tk.NextToken()); dst[1] = float.Parse(tk.NextToken()); dst[2] = float.Parse(tk.NextToken()); Math3D.PerpendicularVector(newdst, dir); System.Diagnostics.Debug.WriteLine("" + i + ":" + Lib.Vtofs(dst) + " : " + Lib.Vtofs(newdst)); }
protected void btn_Click(object sender, EventArgs e) { try { var btn = sender as DevExpress.Web.ASPxEditors.ASPxButton; if (btn == null) { return; } if (btn.ID == this.btnNewDS.ID) { MySession.DSDefine_CurEditing = null; // Clear Selected field this.lbxFieldSelected.Items.Clear(); MySession.DSDefine_SelFieldInfo.Clear(); this.lbxMetricFieldSelected.Items.Clear(); MySession.DSDefine_SelSumInfo.Clear(); // Clear filtered field this.FilterControlSet.Clear(); this.ctrlCollect.Controls.Clear(); // Clear Input this.txtDisplayNameDS.Text = ""; this.cboDatasource.Text = ""; this.txtDisplayName0.Text = ""; this.txtDisplayName.Text = ""; this.cboFuncs.Text = ""; this.cboOrderBy1.Text = ""; this.lblSavingMsg.Text = ""; // Update Display to clientside... this.upp_SelectClause.Update(); this.upp_Filter.Update(); this.upp_SavingMsg.Update(); // Focus this.txtDisplayName.Focus(); } else if (btn.ID == this.btnIn_1.ID) { var item = this.lbxField.SelectedItem; if (item == null) { return; } var tblName = Lib.NTE(item.GetValue("TblName_Virtual")); var colName = Lib.NTE(item.GetValue("ColName")); var colAlias = Lib.NTE(item.GetValue("ColAliasVI")); var colDataType = Lib.NTE(item.GetValue("DataType")); var info = new InqFieldInfoMDX(tblName, colName, colAlias, colDataType); var sel_InqFieldInfo = MySession.DSDefine_SelFieldInfo; if (sel_InqFieldInfo.Exists(p => p.KeyField == info.KeyField)) { return; } sel_InqFieldInfo.Add(info); Helpers.SetDataSource(this.lbxFieldSelected, sel_InqFieldInfo, "KeyField", "ColAliasVI"); } else if (btn.ID == this.btnIn_2.ID) { var item = this.lbxMetricField.SelectedItem; if (item == null) { return; } var tblName = Lib.NTE(item.GetValue("TblName_Virtual")); var colName = Lib.NTE(item.GetValue("ColName")); var colAlias = Lib.NTE(item.GetValue("ColAliasVI")); var colDataType = Lib.NTE(item.GetValue("DataType")); var fieldInfo = new InqFieldInfoMDX(tblName, colName, colAlias, colDataType); var info = new InqSummaryInfoMDX(fieldInfo, "SUM", colAlias); var sel_InqSummaryInfo = MySession.DSDefine_SelSumInfo; if (sel_InqSummaryInfo.Exists(p => p.Field.KeyField == info.Field.KeyField)) { return; } sel_InqSummaryInfo.Add(info); Helpers.SetDataSource(this.lbxMetricFieldSelected, sel_InqSummaryInfo, "Field.KeyField", "FieldAlias"); } else if (btn.ID == this.btnOut_1.ID) { var item = lbxFieldSelected.SelectedItem; lbxFieldSelected.Items.Remove(item); MySession.DSDefine_SelFieldInfo.RemoveAll(p => p.KeyField == Lib.NTE(item.GetValue("KeyField"))); } else if (btn.ID == this.btnOut_2.ID) { var item = lbxMetricFieldSelected.SelectedItem; lbxMetricFieldSelected.Items.Remove(item); MySession.DSDefine_SelSumInfo.RemoveAll(p => p.Field.KeyField == Lib.NTE(item.GetValue("Field.KeyField"))); } } #if DEBUG catch (Exception ex) { throw ex; } #else catch { } #endif }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { Stopwatch executionTimer = Stopwatch.StartNew(); string taskIdString = taskId.ToString(); StringBuilder dataRow = new StringBuilder(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script RemoveWindowsProfileScript.", taskIdString); try { if (null == connection) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to RemoveWindowsProfileScript is null.", taskIdString); } else if (!connection.ContainsKey(@"cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", taskIdString); } else { ManagementScope cimvScope = connection[@"cimv2"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed", taskIdString); } else { string userName = connection[@"userName"] as string; Debug.Assert(null != userName); int domainSeparatorPosition = userName.IndexOf('\\'); if (-1 != domainSeparatorPosition) { userName = userName.Substring(domainSeparatorPosition + 1); } string profileDirectory = @"c:\Documents and Settings\" + userName; uint wmiMethodResultCode = 0; resultCode = Lib.DeleteDirectory(taskIdString, profileDirectory, cimvScope, out wmiMethodResultCode); } } } catch (Exception ex) { Lib.LogException(taskIdString, executionTimer, "Unhandled exception in RemoveWindowsProfileScript", ex); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script RemoveWindowsProfileScript. Elapsed time {1}. Result code {2}.", taskIdString, executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString())); }
public override Task <CrashReply> Crash(CrashRequest req, ServerCallContext _) { Lib.Exit("Crashed By PuppetMaster!"); return(Task.FromResult(new CrashReply())); }
/// <summary> /// Execute command /// (Note that file path must be absolute path) /// </summary> /// <param name="filePath">File Path</param> /// <param name="collectedData">Collected Result.</param> /// <returns></returns> private ResultCodes ExecuteCommand(string userCommandLine, out string collectedData) { ResultCodes resultCode = ResultCodes.RC_SUCCESS; collectedData = string.Empty; if (!m_connection.ContainsKey(@"TemporaryDirectory")) { m_connection[@"TemporaryDirectory"] = @"%TMP%"; } else { if (!m_connection[@"TemporaryDirectory"].Equals(@"%TMP%")) { if (!Lib.ValidateDirectory(m_taskId, m_connection[@"TemporaryDirectory"].ToString(), m_cimvScope)) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Temporary directory {1} is not valid.", m_taskId, m_connection[@"TemporaryDirectory"].ToString()); resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING; //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST } else { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Temporary directory {1} has been validated.", m_taskId, m_connection[@"TemporaryDirectory"].ToString()); } } } if (resultCode == ResultCodes.RC_SUCCESS) { string strTempDir = m_connection["TemporaryDirectory"].ToString().Trim(); if (strTempDir.EndsWith(@"\")) { strTempDir = strTempDir.Substring(0, strTempDir.Length - 1); } string strBatchFileContent = buildBatchFile(userCommandLine); StringBuilder stdoutData = new StringBuilder(); using (IRemoteProcess rp = RemoteProcess.ExecuteBatchFile (m_taskId, m_cimvScope, strBatchFileContent, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher)) { //This method will block until the entire remote process operation completes. resultCode = rp.Launch(); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Command execution completed with result code {1}.", m_taskId, resultCode.ToString()); if (rp != null && rp.Stdout != null && resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Command execution completed with result <{1}>.", m_taskId, rp.Stdout.ToString()); collectedData = rp.Stdout.ToString(); //if (output.IndexOf(s_endTag) != -1) { // collectedData = output.Substring(0, output.Length - s_endTag.Length - 2); //} else { // resultCode = ResultCodes.RC_PROCESS_EXEC_FAILED; // Lib.Logger.TraceEvent(TraceEventType.Error, // 0, // "Task Id {0}: Remote execution error.\nSTDOUT.STDERR:\n{1}", // m_taskId, // rp.Stdout.ToString()); //} } else { resultCode = ResultCodes.RC_PROCESS_EXEC_FAILED; } } } return(resultCode); }
///<summary> Add reliability sub-panel, including tooltips </summary> private static void AddSubPanelReliability(Panel p) { // evaluate redundancy metric // - 0: no redundancy // - 0.5: all groups have 2 elements // - 1.0: all groups have 3 or more elements double redundancy_metric = 0.0; foreach (KeyValuePair <string, int> pair in vessel_analyzer.redundancy) { switch (pair.Value) { case 1: break; case 2: redundancy_metric += 0.5 / vessel_analyzer.redundancy.Count; break; default: redundancy_metric += 1.0 / vessel_analyzer.redundancy.Count; break; } } // traduce the redundancy metric to string string redundancy_str = string.Empty; if (redundancy_metric <= 0.1) { redundancy_str = "none"; } else if (redundancy_metric <= 0.33) { redundancy_str = "poor"; } else if (redundancy_metric <= 0.66) { redundancy_str = "okay"; } else { redundancy_str = "great"; } // generate redundancy tooltip string redundancy_tooltip = string.Empty; if (vessel_analyzer.redundancy.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (KeyValuePair <string, int> pair in vessel_analyzer.redundancy) { if (sb.Length > 0) { sb.Append("\n"); } sb.Append("<b>"); switch (pair.Value) { case 1: sb.Append("<color=red>"); break; case 2: sb.Append("<color=yellow>"); break; default: sb.Append("<color=green>"); break; } sb.Append(pair.Value.ToString()); sb.Append("</color></b>\t"); sb.Append(pair.Key); } redundancy_tooltip = Lib.BuildString("<align=left />", sb.ToString()); } // generate repair string and tooltip string repair_str = "none"; string repair_tooltip = string.Empty; if (vessel_analyzer.crew_engineer) { repair_str = "engineer"; repair_tooltip = "The engineer on board should\nbe able to handle all repairs"; } else if (vessel_analyzer.crew_capacity == 0) { repair_str = "safemode"; repair_tooltip = "We have a chance of repairing\nsome of the malfunctions remotely"; } // render panel p.AddSection("RELIABILITY", string.Empty, () => { p.Prev(ref special_index, panel_special.Count); update = true; }, () => { p.Next(ref special_index, panel_special.Count); update = true; }); p.AddContent("malfunctions", Lib.HumanReadableAmount(vessel_analyzer.failure_year, "/y"), "average case estimate\nfor the whole vessel"); p.AddContent("high quality", Lib.HumanReadablePerc(vessel_analyzer.high_quality), "percentage of high quality components"); p.AddContent("redundancy", redundancy_str, redundancy_tooltip); p.AddContent("repair", repair_str, repair_tooltip); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { m_taskId = taskId.ToString(); m_cleId = cleId; m_elementId = elementId; m_databaseTimestamp = databaseTimestamp; m_localTimestamp = localTimestamp; m_attributes = attributes; m_scriptParameters = scriptParameters; m_tftpPath = tftpPath; m_tftpPath_login = tftpPath_login; m_tftpPath_password = tftpPath_password; m_tftpDispatcher = tftpDispatcher; m_connection = connection; m_executionTimer = Stopwatch.StartNew(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script WinFilePropertiesScript.", m_taskId); try { // Check ManagementScope CIMV if (connection == null) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to RSOPPropertiesScriptis null.", m_taskId); } else if (!connection.ContainsKey("cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else { m_cimvScope = connection[@"cimv2"] as ManagementScope; if (!m_cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed", m_taskId); } } if (resultCode == ResultCodes.RC_SUCCESS) { string collectedData = string.Empty; resultCode = ExecuteCommand(GPO_COMMAND_R, out collectedData); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Command GPRESULT /R executed with result <{1}>", m_taskId, collectedData); Match matchInvalidArg1 = null, matchInvalidArg2 = null, matchInvalidCmd = null; if (!string.IsNullOrEmpty(collectedData)) { matchInvalidArg1 = s_invalidArgumentRegex.Match(collectedData); matchInvalidArg2 = s_invalidArgument2Regex.Match(collectedData); matchInvalidCmd = s_invalidCommandRegex.Match(collectedData); if (matchInvalidArg1.Success || matchInvalidArg2.Success || matchInvalidCmd.Success) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Command GPRESULT /R failed <{1}>", m_taskId, collectedData); collectedData = string.Empty; resultCode = ExecuteCommand(GPO_COMMAND, out collectedData); Lib.Logger.TraceEvent(TraceEventType.Verbose, 0, "Task Id {0}: Command GPRESULT executed with result <{1}>", m_taskId, collectedData); } if (!string.IsNullOrEmpty(collectedData)) { matchInvalidArg1 = s_invalidArgumentRegex.Match(collectedData); matchInvalidArg2 = s_invalidArgument2Regex.Match(collectedData); matchInvalidCmd = s_invalidCommandRegex.Match(collectedData); if (matchInvalidArg1.Success || matchInvalidArg2.Success || matchInvalidCmd.Success) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Command GPRESULT /R failed <{1}>", m_taskId, collectedData); collectedData = string.Empty; } else { string header = string.Empty, computerSettings = string.Empty, userSettings = string.Empty; if (collectedData.Contains(COMPUTER_SETTINGS)) { int headerIndex = collectedData.IndexOf(COMPUTER_SETTINGS); int userSettingIndex = collectedData.IndexOf(USER_SETTINGS); header = collectedData.Substring(0, headerIndex); computerSettings = collectedData.Substring(0, userSettingIndex); userSettings = header + collectedData.Substring(userSettingIndex, collectedData.Length - userSettingIndex); } else if (collectedData.Contains(USER_GROUP_POLICY)) { int headerIndex = collectedData.IndexOf(USER_GROUP_POLICY); int computerSettingIndex = collectedData.IndexOf(COMPUTER_GROUP_POLICY); int userSettingIndex = collectedData.IndexOf(USER_GROUP_POLICY); header = collectedData.Substring(0, userSettingIndex); computerSettings = header + collectedData.Substring(computerSettingIndex); userSettings = collectedData.Substring(0, computerSettingIndex); } if (string.IsNullOrEmpty(computerSettings) && !string.IsNullOrEmpty(collectedData)) { computerSettings = collectedData; } BuildDataRow(@"rsopComputerSettings", computerSettings); BuildDataRow(@"rsopUserSettings", userSettings); } } } } } catch (Exception ex) { if (resultCode == ResultCodes.RC_SUCCESS) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in WinFilePropertiesScript. Elapsed time {1}.\nResult code changed to RC_PROCESSING_EXCEPTION.\n{2}", m_taskId, m_executionTimer.Elapsed.ToString(), ex); resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR; } else { Lib.LogException(m_taskId, m_executionTimer, "Unhandled exception in WinFilePropertiesScript", ex); } BuildDataRow(@"fileProperties", @"NotFound"); resultCode = ResultCodes.RC_SUCCESS; } Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script WinFilePropertiesScript. Elapsed time {1}. Result code {2}.", m_taskId, m_executionTimer.Elapsed.ToString(), resultCode.ToString()); return(new CollectionScriptResults (resultCode, 0, null, null, null, false, m_dataRow.ToString())); }
///<summary> Add environment sub-panel, including tooltips </summary> private static void AddSubPanelEnvironment(Panel p) { string flux_tooltip = Lib.BuildString ( "<align=left />" + String.Format("<b>{0,-14}\t{1,-15}\t{2}</b>\n", "Source", "Flux", "Temp"), String.Format("{0,-14}\t{1,-15}\t{2}\n", "solar", env_analyzer.solar_flux > 0.0 ? Lib.HumanReadableFlux(env_analyzer.solar_flux) : "none", Lib.HumanReadableTemp(Sim.BlackBodyTemperature(env_analyzer.solar_flux))), String.Format("{0,-14}\t{1,-15}\t{2}\n", "albedo", env_analyzer.albedo_flux > 0.0 ? Lib.HumanReadableFlux(env_analyzer.albedo_flux) : "none", Lib.HumanReadableTemp(Sim.BlackBodyTemperature(env_analyzer.albedo_flux))), String.Format("{0,-14}\t{1,-15}\t{2}\n", "body", env_analyzer.body_flux > 0.0 ? Lib.HumanReadableFlux(env_analyzer.body_flux) : "none", Lib.HumanReadableTemp(Sim.BlackBodyTemperature(env_analyzer.body_flux))), String.Format("{0,-14}\t{1,-15}\t{2}\n", "background", Lib.HumanReadableFlux(Sim.BackgroundFlux()), Lib.HumanReadableTemp(Sim.BlackBodyTemperature(Sim.BackgroundFlux()))), String.Format("{0,-14}\t\t{1,-15}\t{2}", "total", Lib.HumanReadableFlux(env_analyzer.total_flux), Lib.HumanReadableTemp(Sim.BlackBodyTemperature(env_analyzer.total_flux))) ); string atmosphere_tooltip = Lib.BuildString ( "<align=left />", String.Format("{0,-14}\t<b>{1}</b>\n", "breathable", Sim.Breathable(env_analyzer.body) ? "yes" : "no"), String.Format("{0,-14}\t<b>{1}</b>\n", "pressure", Lib.HumanReadablePressure(env_analyzer.body.atmospherePressureSeaLevel)), String.Format("{0,-14}\t<b>{1}</b>\n", "light absorption", Lib.HumanReadablePerc(1.0 - env_analyzer.atmo_factor)), String.Format("{0,-14}\t<b>{1}</b>", "gamma absorption", Lib.HumanReadablePerc(1.0 - Sim.GammaTransparency(env_analyzer.body, 0.0))) ); string shadowtime_str = Lib.HumanReadableDuration(env_analyzer.shadow_period) + " (" + (env_analyzer.shadow_time * 100.0).ToString("F0") + "%)"; p.AddSection("ENVIRONMENT", string.Empty, () => { p.Prev(ref environment_index, panel_environment.Count); update = true; }, () => { p.Next(ref environment_index, panel_environment.Count); update = true; }); p.AddContent("temperature", Lib.HumanReadableTemp(env_analyzer.temperature), env_analyzer.body.atmosphere && env_analyzer.landed ? "atmospheric" : flux_tooltip); p.AddContent("difference", Lib.HumanReadableTemp(env_analyzer.temp_diff), "difference between external and survival temperature"); p.AddContent("atmosphere", env_analyzer.body.atmosphere ? "yes" : "no", atmosphere_tooltip); p.AddContent("shadow time", shadowtime_str, "the time in shadow\nduring the orbit"); }
/// <summary> /// Perform collection task specific processing. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="cleId">Database Id of owning Collection Engine.</param> /// <param name="elementId">Database Id of element being collected.</param> /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param> /// <param name="localTimestamp">Local task dispatch timestamp.</param> /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param> /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param> /// <param name="connection">Connection script results (null if this script does not /// require a remote host connection).</param> /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param> /// /// <returns>Collection results.</returns> public CollectionScriptResults ExecuteTask( long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { Stopwatch executionTimer = Stopwatch.StartNew(); m_taskId = taskId.ToString(); StringBuilder dataRow = new StringBuilder(); ResultCodes resultCode = ResultCodes.RC_SUCCESS; Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Collection script MSOutlookExpressStaticScript.", m_taskId); try { ManagementScope cimvScope = null; ManagementScope defaultScope = null; if (null == connection) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection object passed to MSOutlookExpressStaticScript is null.", m_taskId); } else if (!connection.ContainsKey(@"cimv2")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for CIMV namespace is not present in connection object.", m_taskId); } else if (!connection.ContainsKey(@"default")) { resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Management scope for Default namespace is not present in connection object.", m_taskId); } else { cimvScope = connection[@"cimv2"] as ManagementScope; defaultScope = connection[@"default"] as ManagementScope; if (!cimvScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to CIMV namespace failed.", m_taskId); } else if (!defaultScope.IsConnected) { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connection to Default namespace failed.", m_taskId); } else { IDictionary <string, string> queryResults = new Dictionary <string, string>(); using (ManagementClass wmiRegistry = new ManagementClass(defaultScope, new ManagementPath(@"StdRegProv"), null)) { resultCode = GetInstallationDirectory(wmiRegistry); } if (!String.IsNullOrEmpty(m_strInstallDirectory)) { if (ResultCodes.RC_SUCCESS == resultCode) { resultCode = GetExeVersionAndInstallDate(cimvScope); if (ResultCodes.RC_SUCCESS == resultCode) { dataRow.Append(elementId) .Append(',') .Append(attributes[@"installedOfficeDetails"]) .Append(',') .Append(scriptParameters[@"CollectorId"]) .Append(',') .Append(taskId) .Append(',') .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds) .Append(',') .Append(@"installedOfficeDetails") .Append(',') .Append(BdnaDelimiters.BEGIN_TAG) .Append("name=\"") .Append(m_strName) .Append('"') .Append(BdnaDelimiters.DELIMITER2_TAG) .Append("version=\"") .Append(m_strVersion) .Append('"') .Append(BdnaDelimiters.DELIMITER2_TAG) .Append("installDirectory=\"") .Append(m_strInstallDirectory) .Append('"') .Append(BdnaDelimiters.DELIMITER2_TAG) .Append("installDate=\"") .Append(m_strInstallDate) .Append('"') .Append(BdnaDelimiters.DELIMITER2_TAG) .Append("lastAccessedDate=\"") .Append(m_strLastAccessedDate) .Append('"') .Append(BdnaDelimiters.END_TAG); } // Registry entries may exist for Windows Mail even if it // is not installed--see bug #16177. The registry can have // a valid InstallRoot but no WINMAIL.EXE file is in the // directory. We still should return RC_SUCCESS. resultCode = ResultCodes.RC_SUCCESS; } } } } } catch (ManagementException me) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Insufficient privilege to access outlook express file property.\nMessage: {1}", m_taskId, me.Message); if (me.InnerException != null) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Inner Exception Message: {1}.", m_taskId, me.InnerException.Message); } resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_ACCESS_FILE_PROPERTY; } catch (COMException ce) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Not enough privilege to access run WMI query.\nMessage: {1}.", m_taskId, ce.Message); if (ce.InnerException != null) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Inner Exception Message: {1}.", m_taskId, ce.InnerException.Message); } resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_RUN_WMI_QUERY; } catch (Exception ex) { Lib.LogException(m_taskId, executionTimer, "Unhandled exception in MSOutlookExpressStaticScript", ex); resultCode = ResultCodes.RC_PROCESSING_EXCEPTION; } CollectionScriptResults result = new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString()); Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Collection script MSOutlookExpressStaticScript. Elapsed time {1}. Result code {2}.", m_taskId, executionTimer.Elapsed.ToString(), result.ResultCode.ToString()); return(result); }
protected void RenderSection(HtmlTextWriter writer, Lib.Data.DSQ.Section s) { // load the section settings. some older drugs may not have // a settings object in the database. SectionSettings settings = SectionSettings.Get(s.ID ?? 0, DrugID ?? 0) ?? new SectionSettings { SectionId = s.ID ?? 0, DrugId = DrugID ?? 0, IsEnabled = true }; // if the section is disabled, just return and ignore it. if(!settings.IsEnabled) return; var user = Framework.Security.Manager.GetUser(); if (user != null) { var profile = Lib.Data.UserProfile.FindByUser(user); if (profile != null && profile.UserTypeID == Lib.Data.UserType.FindByName("prescriber").ID && s.Name == "Pharmacy Requirements") return; } // Header writer.RenderBeginTag("header"); writer.RenderBeginTag("h2"); writer.WriteEncodedText(s.Name); writer.RenderEndTag(); writer.RenderEndTag(); // Body writer.AddAttribute("class", "clearfix"); writer.RenderBeginTag("section"); writer.AddAttribute("class", "form"); writer.RenderBeginTag("div"); if (s.ID.Value == 1) { var control = Page.LoadControl(this.GeneralInfoControlPath); control.RenderControl(writer); } else if (DrugID.HasValue) { foreach (var q in Lib.Data.DSQ.Question.FindBySection(s, false)) RenderQuestion(writer, q); } else { writer.AddStyleAttribute("text-align", "center"); writer.AddStyleAttribute("padding", "1em"); writer.RenderBeginTag("div"); writer.WriteEncodedText("Please save the drug before continuing."); writer.RenderEndTag(); } writer.RenderEndTag(); writer.RenderEndTag(); }
public override void Process() { SendEvent(UpdateEventType.StatusText, "Opening connection..."); SendEvent(UpdateEventType.ProgressBar, 10); //TODO read the com port setting from the configuration CecAdapter[] adapters = Lib.FindAdapters(string.Empty); if (adapters.Length == 0) { DialogResult result = MessageBox.Show("Could not detect to any CEC adapter. Please check your configuration. Do you want to try again?", "Pulse-Eight USB-CEC Adapter", MessageBoxButtons.YesNo); if (result == DialogResult.No) { Application.Exit(); } else { adapters = Lib.FindAdapters(string.Empty); } } while (!Lib.Open(adapters[0].ComPort, 10000)) { DialogResult result = MessageBox.Show("Could not connect to any CEC adapter. Please check your configuration. Do you want to try again?", "Pulse-Eight USB-CEC Adapter", MessageBoxButtons.YesNo); if (result == DialogResult.No) { Application.Exit(); } } SendEvent(UpdateEventType.ProgressBar, 20); SendEvent(UpdateEventType.StatusText, "Sending power on commands..."); Lib.PowerOnDevices(CecLogicalAddress.Broadcast); SendEvent(UpdateEventType.StatusText, "Detecting TV vendor..."); SendEvent(UpdateEventType.ProgressBar, 30); SendEvent(UpdateEventType.TVVendorId, (int)Lib.GetDeviceVendorId(CecLogicalAddress.Tv)); SendEvent(UpdateEventType.StatusText, "Detecting menu language..."); SendEvent(UpdateEventType.ProgressBar, 40); SendEvent(UpdateEventType.MenuLanguage, Lib.GetDeviceMenuLanguage(CecLogicalAddress.Tv)); SendEvent(UpdateEventType.ProgressBar, 50); SendEvent(UpdateEventType.StatusText, "Detecting AVR devices..."); bool hasAVRDevice = Lib.IsActiveDevice(CecLogicalAddress.AudioSystem); SendEvent(UpdateEventType.HasAVRDevice, hasAVRDevice); if (hasAVRDevice) { SendEvent(UpdateEventType.ProgressBar, 60); SendEvent(UpdateEventType.StatusText, "Detecting AVR vendor..."); SendEvent(UpdateEventType.AVRVendorId, (int)Lib.GetDeviceVendorId(CecLogicalAddress.AudioSystem)); } if (!Lib.GetDevicePowerStatus(CecLogicalAddress.Tv).Equals(CecPowerStatus.On)) { SendEvent(UpdateEventType.ProgressBar, 70); SendEvent(UpdateEventType.StatusText, "Activating the source..."); Lib.SetActiveSource(CecDeviceType.Reserved); } SendEvent(UpdateEventType.ProgressBar, 80); SendEvent(UpdateEventType.StatusText, "Reading device configuration..."); Lib.GetCurrentConfiguration(Config); SendEvent(Config); SendEvent(UpdateEventType.ProgressBar, 90); SendEvent(UpdateEventType.StatusText, "Polling active devices"); SendEvent(UpdateEventType.PollDevices); SendEvent(UpdateEventType.ProgressBar, 100); SendEvent(UpdateEventType.StatusText, "Ready."); }
public static void TestRotate(int i, string line) { StringTokenizer tk = new StringTokenizer(line); float[] dir = new float[] { 0, 0, 0 }; float[] point = new float[] { 0, 0, 0 }; float[] dst = new float[] { 0, 0, 0 }; float[] newdst = new float[] { 0, 0, 0 }; float degrees = 0; dir[0] = float.Parse(tk.NextToken()); dir[1] = float.Parse(tk.NextToken()); dir[2] = float.Parse(tk.NextToken()); tk.NextToken(); point[0] = float.Parse(tk.NextToken()); point[1] = float.Parse(tk.NextToken()); point[2] = float.Parse(tk.NextToken()); tk.NextToken(); degrees = float.Parse(tk.NextToken()); tk.NextToken(); dst[0] = float.Parse(tk.NextToken()); dst[1] = float.Parse(tk.NextToken()); dst[2] = float.Parse(tk.NextToken()); Math3D.RotatePointAroundVector(newdst, dir, point, degrees); System.Diagnostics.Debug.WriteLine("" + i + ":" + Lib.Vtofs(dst) + " : " + Lib.Vtofs(newdst)); }
public abstract void Deserialize(ref Lib.NewFastSerializer.SerializationReader mySerializationReader);
static int Main() { // Some typical code { Microsoft.FSharp.Core.FSharpOption <int> x = Microsoft.FSharp.Core.FSharpOption <int> .Some(3); System.Console.WriteLine("{0}", x.Value); Microsoft.FSharp.Collections.FSharpList <int> x2 = Microsoft.FSharp.Collections.FSharpList <int> .Cons(3, Microsoft.FSharp.Collections.FSharpList <int> .Empty); System.Console.WriteLine("{0}", x2.Head); } { FSharpList <int> x = FSharpList <int> .Cons(3, (FSharpList <int> .Empty)); Console.WriteLine("x - IsCons = {0}", x != null); Console.WriteLine("x - IsNil = {0}", x == null); Console.WriteLine("x.Head = {0}", x.Head); Console.WriteLine("x.Tail = {0}", x.Tail); Console.WriteLine("x.Tail - IsNil = {0}", x.Tail); switch (x.Tag) { case FSharpList <int> .Tags.Cons: Console.WriteLine("Cons({0},{1})", x.Head, x.Tail); break; case FSharpList <int> .Tags.Empty: Console.WriteLine("[]"); break; } } { FSharpList <int> x = FSharpList <int> .Cons(3, (FSharpList <int> .Empty)); foreach (int i in x) { Console.WriteLine("i = {0}", i); } } { FSharpList <int> myList = ListModule.OfArray(new int[] { 4, 5, 6 }); ListModule.Iterate (FuncConvert.ToFSharpFunc((Action <int>) delegate(int i) { Console.WriteLine("i = {0}", i); }), myList); ListModule.Iterate <int> ((Converter <int, Unit>) delegate(int i) { Console.WriteLine("i = {0} (2nd technique)", i); return(null); }, myList); FSharpList <string> myList2 = ListModule.Map (FuncConvert.ToFSharpFunc((Converter <int, string>) delegate(int i) { return(i.ToString() + i.ToString()); }), myList); ListModule.Iterate (FuncConvert.ToFSharpFunc((Action <string>) delegate(string s) { Console.WriteLine("i after duplication = {0}", s); }), myList2); myList2 = ListModule.Map <int, string> ((Converter <int, string>) delegate(int i) { return(i.ToString() + i.ToString()); }, myList); ListModule.Iterate <string> (FuncConvert.ToFSharpFunc((Action <string>) delegate(string s) { Console.WriteLine("i after duplication (2nd technique) = {0}", s); }), myList2); // No Func overloads are available for FuncConvert.ToFSharpFunc // myList2 = // ListModule.Map<int,string> // (FuncConvert.ToFSharpFunc((Func<int,string>) delegate(int i) { return i.ToString() + i.ToString(); }), // myList); ListModule.Iterate <string>(FuncConvert.ToFSharpFunc <string>(s => { Console.WriteLine("s = {0}", s); }), myList2); //Note: This call becomes ambiguous if Func overloads of FuncConvert.ToFSharpFunc are added myList2 = ListModule.Map <string, string>(FuncConvert.ToFSharpFunc <string, string>(i => i.ToString() + i.ToString()), myList2); } // Construct a value of each type from the library Lib.Recd1 r1 = new Lib.Recd1(3); Lib.Recd2 r2 = new Lib.Recd2(3, "a"); Lib.RevRecd2 rr2 = new Lib.RevRecd2("a", 3); Lib.Recd3 <string> r3 = new Lib.Recd3 <string>(4, "c", null); r3.recd3field3 = r3; Lib.One d10a = Lib.One.One; Lib.Int d11a = Lib.Int.NewInt(3); Lib.IntPair ip = Lib.IntPair.NewIntPair(3, 4); Console.WriteLine("{0}", ip.Item1); Console.WriteLine("{0}", ip.Item2); Lib.IntPear ip2 = Lib.IntPear.NewIntPear(3, 4); Console.WriteLine("{0}", ip2.Fst); Console.WriteLine("{0}", ip2.Snd); Lib.Bool b = Lib.Bool.True; Console.WriteLine("{0}", Lib.Bool.True); Console.WriteLine("{0}", Lib.Bool.False); //Console.WriteLine("{0}", Lib.Bool.IsTrue(b)); //Console.WriteLine("{0}", Lib.Bool.IsFalse(b)); switch (b.Tag) { case Lib.Bool.Tags.True: Console.WriteLine("True"); break; case Lib.Bool.Tags.False: Console.WriteLine("False"); break; } Lib.OptionalInt oint = Lib.OptionalInt.NewSOME(3); Console.WriteLine("oint - IsSOME = {0}", oint != null); Console.WriteLine("oint - IsNONE = {0}", oint == null); Console.WriteLine("{0}", (oint as Lib.OptionalInt.SOME).Item); switch (oint.Tag) { case Lib.OptionalInt.Tags.SOME: var c = oint as Lib.OptionalInt.SOME; Console.WriteLine("SOME({0})", c.Item); break; case Lib.OptionalInt.Tags.NONE: Console.WriteLine("NONE"); break; } Lib.IntOption iopt = Lib.IntOption.Nothing; Console.WriteLine("iopt - IsSomething = {0}", iopt != null); Console.WriteLine("iopt - IsNothing = {0}", iopt == null); switch (iopt.Tag) { case Lib.IntOption.Tags.Something: Console.WriteLine("Something({0})", (iopt as Lib.IntOption.Something).Item); break; case Lib.IntOption.Tags.Nothing: Console.WriteLine("Nothing"); break; } Lib.GenericUnion <int, string> gu1 = Lib.GenericUnion <int, string> .Nothing; Lib.GenericUnion <int, string> gu2 = Lib.GenericUnion <int, string> .NewSomething(3, "4"); Lib.GenericUnion <int, string> gu3 = Lib.GenericUnion <int, string> .NewSomethingElse(3); Lib.GenericUnion <int, string> gu4 = Lib.GenericUnion <int, string> .NewSomethingElseAgain(4); //Console.WriteLine("{0}", (gu1 as Lib.GenericUnion<int,string>.Cases.Nothing)); Console.WriteLine("{0}", (gu2 as Lib.GenericUnion <int, string> .Something).Item1); Console.WriteLine("{0}", (gu3 as Lib.GenericUnion <int, string> .SomethingElse).Item); Console.WriteLine("{0}", (gu4 as Lib.GenericUnion <int, string> .SomethingElseAgain).Item); switch (gu1.Tag) { case Lib.GenericUnion <int, string> .Tags.Nothing: Console.WriteLine("OK"); break; case Lib.GenericUnion <int, string> .Tags.Something: case Lib.GenericUnion <int, string> .Tags.SomethingElse: case Lib.GenericUnion <int, string> .Tags.SomethingElseAgain: Console.WriteLine("NOT OK"); throw (new System.Exception("ERROR - INCORRECT CASE TAG")); } switch (gu2.Tag) { case Lib.GenericUnion <int, string> .Tags.Something: Console.WriteLine("OK"); break; case Lib.GenericUnion <int, string> .Tags.Nothing: case Lib.GenericUnion <int, string> .Tags.SomethingElse: case Lib.GenericUnion <int, string> .Tags.SomethingElseAgain: Console.WriteLine("NOT OK"); throw (new System.Exception("ERROR - INCORRECT CASE TAG")); } Lib.BigUnion bu1 = Lib.BigUnion.NewA1(3); Lib.BigUnion bu2 = Lib.BigUnion.NewA2(3); Lib.BigUnion bu3 = Lib.BigUnion.NewA3(3); Lib.BigUnion bu4 = Lib.BigUnion.NewA4(3); Lib.BigUnion bu5 = Lib.BigUnion.NewA5(3); Lib.BigUnion bu6 = Lib.BigUnion.NewA6(3); Lib.BigUnion bu7 = Lib.BigUnion.NewA7(3); Lib.BigUnion bu8 = Lib.BigUnion.NewA8(3); Lib.BigUnion bu9 = Lib.BigUnion.NewA9(3); switch (bu1.Tag) { case Lib.BigUnion.Tags.A1: Console.WriteLine("OK"); break; case Lib.BigUnion.Tags.A2: case Lib.BigUnion.Tags.A3: case Lib.BigUnion.Tags.A4: case Lib.BigUnion.Tags.A5: case Lib.BigUnion.Tags.A6: case Lib.BigUnion.Tags.A7: case Lib.BigUnion.Tags.A8: case Lib.BigUnion.Tags.A9: Console.WriteLine("NOT OK"); throw (new System.Exception("ERROR - INCORRECT CASE TAG")); } Lib.BigEnum be1 = Lib.BigEnum.E1; Lib.BigEnum be2 = Lib.BigEnum.E2; Lib.BigEnum be3 = Lib.BigEnum.E3; Lib.BigEnum be4 = Lib.BigEnum.E4; Lib.BigEnum be5 = Lib.BigEnum.E5; Lib.BigEnum be6 = Lib.BigEnum.E6; Lib.BigEnum be7 = Lib.BigEnum.E7; Lib.BigEnum be8 = Lib.BigEnum.E8; Lib.BigEnum be9 = Lib.BigEnum.E9; switch (be1.Tag) { case Lib.BigEnum.Tags.E1: Console.WriteLine("OK"); break; case Lib.BigEnum.Tags.E2: case Lib.BigEnum.Tags.E3: case Lib.BigEnum.Tags.E4: case Lib.BigEnum.Tags.E5: case Lib.BigEnum.Tags.E6: case Lib.BigEnum.Tags.E7: case Lib.BigEnum.Tags.E8: case Lib.BigEnum.Tags.E9: Console.WriteLine("NOT OK"); throw (new System.Exception("ERROR - INCORRECT CASE TAG")); } Lib.Index d211a = Lib.Index.NewIndex_A(3); Lib.Bool d200b = Lib.Bool.False; Lib.OptionalInt d210b = Lib.OptionalInt.NONE; Lib.IntOption d201b = Lib.IntOption.NewSomething(3); Lib.Index d211b = Lib.Index.NewIndex_B(4); /* * * type discr2_0_0 = True | False * type discr2_0_1 = Nothing | Something of int * type discr2_1_0 = SOME of int | NONE * type discr2_1_1 = Index_A of int | Index_B of int * * type discr3_0_0_0 = Discr3_0_0_0_A | Discr3_0_0_0_B | Discr3_0_0_0_C * type discr3_0_1_0 = Discr3_0_1_0_A | Discr3_0_1_0_B of int | Discr3_0_0_0_C * type discr3_1_0_0 = Discr3_1_0_0_A of int | Discr3_1_0_0_B | Discr3_0_0_0_C * type discr3_1_1_0 = Discr3_1_1_0_A of int | Discr3_1_1_0_B of int | Discr3_0_0_0_C * type discr3_0_0_1 = Discr3_0_0_0_A | Discr3_0_0_0_B | Discr3_0_0_0_C of string * type discr3_0_1_1 = Discr3_0_1_0_A | Discr3_0_1_0_B of int | Discr3_0_0_0_C of string * type discr3_1_0_1 = Discr3_1_0_0_A of int | Discr3_1_0_0_B | Discr3_0_0_0_C of string * type discr3_1_1_1 = Discr3_1_1_0_A of int | Discr3_1_1_0_B of int | Discr3_0_0_0_C of string */ // Toplevel functions * int f_1 = Lib.f_1(1); int f_1_1 = Lib.f_1_1(1, 2); int f_1_1_1 = Lib.f_1_1_1(1, 2, 3); int f_1_1_1_1 = Lib.f_1_1_1_1(1, 2, 3, 4); int f_1_1_1_1_1 = Lib.f_1_1_1_1_1(1, 2, 3, 4, 5); #if DELEGATES int f_1_effect_1 = Lib.f_1_effect_1(1)(2); #else int f_1_effect_1 = Lib.f_1_effect_1(1).Invoke(2); #endif //let f_2 x y = x+y //let f_3 x y z = x+y+z //let f_4 x1 x2 x3 x4 = x1+x2+x3+x4 //let f_5 x1 x2 x3 x4 x5 = x1+x2+x3+x4+x5 // Function returning a function //let f_1_1 x = let x = ref 1 in fun y -> !x+y+1 // Tuple value //let tup2 = (2,3) //let tup3 = (2,3,4) //let tup4 = (2,3,4,5) System.Console.WriteLine("Test Passed."); return(0); }
public static bool IsCertified( Lib.Data.UserProfile up, string eoc_name, long drug_id, ref DateTime date_certified ) { return IsCertified(up, Lib.Data.Eoc.FindByName(eoc_name), new Lib.Data.Drug(drug_id), ref date_certified); }
public abstract void Serialize(Lib.NewFastSerializer.SerializationWriter writer, object value);
protected static void DrawPluginVersion() { EditorGUILayout.LabelField("Plugin Version: " + Lib.GetPluginVersion()); }
public abstract object Deserialize(Lib.NewFastSerializer.SerializationReader reader, Type type);
public void StopServiceTest() { Lib t = new Lib(); Assert.ThrowsException <Exception>(() => t.StopService()); }
public static void Fire_lead(edict_t self, float[] start, float[] aimdir, int damage, int kick, int te_impact, int hspread, int vspread, int mod) { trace_t tr; float[] dir = new float[] { 0, 0, 0 }; float[] forward = new float[] { 0, 0, 0 }, right = new float[] { 0, 0, 0 }, up = new float[] { 0, 0, 0 }; float[] end = new float[] { 0, 0, 0 }; float r; float u; float[] water_start = new float[] { 0, 0, 0 }; bool water = false; int content_mask = Defines.MASK_SHOT | Defines.MASK_WATER; tr = GameBase.gi.Trace(self.s.origin, null, null, start, self, Defines.MASK_SHOT); if (!(tr.fraction < 1)) { Math3D.Vectoangles(aimdir, dir); Math3D.AngleVectors(dir, forward, right, up); r = Lib.Crandom() * hspread; u = Lib.Crandom() * vspread; Math3D.VectorMA(start, 8192, forward, end); Math3D.VectorMA(end, r, right, end); Math3D.VectorMA(end, u, up, end); if ((GameBase.gi.pointcontents.Pointcontents(start) & Defines.MASK_WATER) != 0) { water = true; Math3D.VectorCopy(start, water_start); content_mask &= ~Defines.MASK_WATER; } tr = GameBase.gi.Trace(start, null, null, end, self, content_mask); if ((tr.contents & Defines.MASK_WATER) != 0) { int color; water = true; Math3D.VectorCopy(tr.endpos, water_start); if (!Math3D.VectorEquals(start, tr.endpos)) { if ((tr.contents & Defines.CONTENTS_WATER) != 0) { if (Lib.Strcmp(tr.surface.name, "*brwater") == 0) { color = Defines.SPLASH_BROWN_WATER; } else { color = Defines.SPLASH_BLUE_WATER; } } else if ((tr.contents & Defines.CONTENTS_SLIME) != 0) { color = Defines.SPLASH_SLIME; } else if ((tr.contents & Defines.CONTENTS_LAVA) != 0) { color = Defines.SPLASH_LAVA; } else { color = Defines.SPLASH_UNKNOWN; } if (color != Defines.SPLASH_UNKNOWN) { GameBase.gi.WriteByte(Defines.svc_temp_entity); GameBase.gi.WriteByte(Defines.TE_SPLASH); GameBase.gi.WriteByte(8); GameBase.gi.WritePosition(tr.endpos); GameBase.gi.WriteDir(tr.plane.normal); GameBase.gi.WriteByte(color); GameBase.gi.Multicast(tr.endpos, Defines.MULTICAST_PVS); } Math3D.VectorSubtract(end, start, dir); Math3D.Vectoangles(dir, dir); Math3D.AngleVectors(dir, forward, right, up); r = Lib.Crandom() * hspread * 2; u = Lib.Crandom() * vspread * 2; Math3D.VectorMA(water_start, 8192, forward, end); Math3D.VectorMA(end, r, right, end); Math3D.VectorMA(end, u, up, end); } tr = GameBase.gi.Trace(water_start, null, null, end, self, Defines.MASK_SHOT); } } if (!((tr.surface != null) && 0 != (tr.surface.flags & Defines.SURF_SKY))) { if (tr.fraction < 1) { if (tr.ent.takedamage != 0) { GameCombat.T_Damage(tr.ent, self, self, aimdir, tr.endpos, tr.plane.normal, damage, kick, Defines.DAMAGE_BULLET, mod); } else { if (!"sky".Equals(tr.surface.name)) { GameBase.gi.WriteByte(Defines.svc_temp_entity); GameBase.gi.WriteByte(te_impact); GameBase.gi.WritePosition(tr.endpos); GameBase.gi.WriteDir(tr.plane.normal); GameBase.gi.Multicast(tr.endpos, Defines.MULTICAST_PVS); if (self.client != null) { PlayerWeapon.PlayerNoise(self, tr.endpos, Defines.PNOISE_IMPACT); } } } } } if (water) { float[] pos = new float[] { 0, 0, 0 }; Math3D.VectorSubtract(tr.endpos, water_start, dir); Math3D.VectorNormalize(dir); Math3D.VectorMA(tr.endpos, -2, dir, pos); if ((GameBase.gi.pointcontents.Pointcontents(pos) & Defines.MASK_WATER) != 0) { Math3D.VectorCopy(pos, tr.endpos); } else { tr = GameBase.gi.Trace(pos, null, null, water_start, tr.ent, Defines.MASK_WATER); } Math3D.VectorAdd(water_start, tr.endpos, pos); Math3D.VectorScale(pos, 0.5F, pos); GameBase.gi.WriteByte(Defines.svc_temp_entity); GameBase.gi.WriteByte(Defines.TE_BUBBLETRAIL); GameBase.gi.WritePosition(water_start); GameBase.gi.WritePosition(tr.endpos); GameBase.gi.Multicast(pos, Defines.MULTICAST_PVS); } }
public static void P_WorldEffects() { bool breather; bool envirosuit; int waterlevel, old_waterlevel; if (current_player.movetype == Defines.MOVETYPE_NOCLIP) { current_player.air_finished = GameBase.level.time + 12; return; } waterlevel = current_player.waterlevel; old_waterlevel = current_client.old_waterlevel; current_client.old_waterlevel = waterlevel; breather = current_client.breather_framenum > GameBase.level.framenum; envirosuit = current_client.enviro_framenum > GameBase.level.framenum; if (old_waterlevel == 0 && waterlevel != 0) { PlayerWeapon.PlayerNoise(current_player, current_player.s.origin, Defines.PNOISE_SELF); if ((current_player.watertype & Defines.CONTENTS_LAVA) != 0) { GameBase.gi.Sound(current_player, Defines.CHAN_BODY, GameBase.gi.Soundindex("player/lava_in.wav"), 1, Defines.ATTN_NORM, 0); } else if ((current_player.watertype & Defines.CONTENTS_SLIME) != 0) { GameBase.gi.Sound(current_player, Defines.CHAN_BODY, GameBase.gi.Soundindex("player/watr_in.wav"), 1, Defines.ATTN_NORM, 0); } else if ((current_player.watertype & Defines.CONTENTS_WATER) != 0) { GameBase.gi.Sound(current_player, Defines.CHAN_BODY, GameBase.gi.Soundindex("player/watr_in.wav"), 1, Defines.ATTN_NORM, 0); } current_player.flags |= Defines.FL_INWATER; current_player.damage_debounce_time = GameBase.level.time - 1; } if (old_waterlevel != 0 && waterlevel == 0) { PlayerWeapon.PlayerNoise(current_player, current_player.s.origin, Defines.PNOISE_SELF); GameBase.gi.Sound(current_player, Defines.CHAN_BODY, GameBase.gi.Soundindex("player/watr_out.wav"), 1, Defines.ATTN_NORM, 0); current_player.flags &= ~Defines.FL_INWATER; } if (old_waterlevel != 3 && waterlevel == 3) { GameBase.gi.Sound(current_player, Defines.CHAN_BODY, GameBase.gi.Soundindex("player/watr_un.wav"), 1, Defines.ATTN_NORM, 0); } if (old_waterlevel == 3 && waterlevel != 3) { if (current_player.air_finished < GameBase.level.time) { GameBase.gi.Sound(current_player, Defines.CHAN_VOICE, GameBase.gi.Soundindex("player/gasp1.wav"), 1, Defines.ATTN_NORM, 0); PlayerWeapon.PlayerNoise(current_player, current_player.s.origin, Defines.PNOISE_SELF); } else if (current_player.air_finished < GameBase.level.time + 11) { GameBase.gi.Sound(current_player, Defines.CHAN_VOICE, GameBase.gi.Soundindex("player/gasp2.wav"), 1, Defines.ATTN_NORM, 0); } } if (waterlevel == 3) { if (breather || envirosuit) { current_player.air_finished = GameBase.level.time + 10; if (((int)(current_client.breather_framenum - GameBase.level.framenum) % 25) == 0) { if (current_client.breather_sound == 0) { GameBase.gi.Sound(current_player, Defines.CHAN_AUTO, GameBase.gi.Soundindex("player/u_breath1.wav"), 1, Defines.ATTN_NORM, 0); } else { GameBase.gi.Sound(current_player, Defines.CHAN_AUTO, GameBase.gi.Soundindex("player/u_breath2.wav"), 1, Defines.ATTN_NORM, 0); } current_client.breather_sound ^= 1; PlayerWeapon.PlayerNoise(current_player, current_player.s.origin, Defines.PNOISE_SELF); } } if (current_player.air_finished < GameBase.level.time) { if (current_player.client.next_drown_time < GameBase.level.time && current_player.health > 0) { current_player.client.next_drown_time = GameBase.level.time + 1; current_player.dmg += 2; if (current_player.dmg > 15) { current_player.dmg = 15; } if (current_player.health <= current_player.dmg) { GameBase.gi.Sound(current_player, Defines.CHAN_VOICE, GameBase.gi.Soundindex("player/drown1.wav"), 1, Defines.ATTN_NORM, 0); } else if ((Lib.Rand() & 1) != 0) { GameBase.gi.Sound(current_player, Defines.CHAN_VOICE, GameBase.gi.Soundindex("*gurp1.wav"), 1, Defines.ATTN_NORM, 0); } else { GameBase.gi.Sound(current_player, Defines.CHAN_VOICE, GameBase.gi.Soundindex("*gurp2.wav"), 1, Defines.ATTN_NORM, 0); } current_player.pain_debounce_time = GameBase.level.time; GameCombat.T_Damage(current_player, GameBase.g_edicts[0], GameBase.g_edicts[0], Globals.vec3_origin, current_player.s.origin, Globals.vec3_origin, current_player.dmg, 0, Defines.DAMAGE_NO_ARMOR, Defines.MOD_WATER); } } } else { current_player.air_finished = GameBase.level.time + 12; current_player.dmg = 2; } if (waterlevel != 0 && 0 != (current_player.watertype & (Defines.CONTENTS_LAVA | Defines.CONTENTS_SLIME))) { if ((current_player.watertype & Defines.CONTENTS_LAVA) != 0) { if (current_player.health > 0 && current_player.pain_debounce_time <= GameBase.level.time && current_client.invincible_framenum < GameBase.level.framenum) { if ((Lib.Rand() & 1) != 0) { GameBase.gi.Sound(current_player, Defines.CHAN_VOICE, GameBase.gi.Soundindex("player/burn1.wav"), 1, Defines.ATTN_NORM, 0); } else { GameBase.gi.Sound(current_player, Defines.CHAN_VOICE, GameBase.gi.Soundindex("player/burn2.wav"), 1, Defines.ATTN_NORM, 0); } current_player.pain_debounce_time = GameBase.level.time + 1; } if (envirosuit) { GameCombat.T_Damage(current_player, GameBase.g_edicts[0], GameBase.g_edicts[0], Globals.vec3_origin, current_player.s.origin, Globals.vec3_origin, 1 * waterlevel, 0, 0, Defines.MOD_LAVA); } else { GameCombat.T_Damage(current_player, GameBase.g_edicts[0], GameBase.g_edicts[0], Globals.vec3_origin, current_player.s.origin, Globals.vec3_origin, 3 * waterlevel, 0, 0, Defines.MOD_LAVA); } } if ((current_player.watertype & Defines.CONTENTS_SLIME) != 0) { if (!envirosuit) { GameCombat.T_Damage(current_player, GameBase.g_edicts[0], GameBase.g_edicts[0], Globals.vec3_origin, current_player.s.origin, Globals.vec3_origin, 1 * waterlevel, 0, 0, Defines.MOD_SLIME); } } } }
public override FileItem LinkFiles(LinkEnvironment LinkEnvironment, bool bBuildImportLibraryOnly, List <Action> Actions) { FileItem OutputFile; // Make the final javascript file Action LinkAction = new Action(ActionType.Link); LinkAction.CommandDescription = "Link"; // LinkAction.bPrintDebugInfo = true; // ResponseFile lines. List <string> ReponseLines = new List <string>(); LinkAction.bCanExecuteRemotely = false; LinkAction.WorkingDirectory = UnrealBuildTool.EngineSourceDirectory; LinkAction.CommandPath = HTML5SDKInfo.Python(); LinkAction.CommandArguments = HTML5SDKInfo.EmscriptenCompiler(); // bool bIsBuildingLibrary = LinkEnvironment.bIsBuildingLibrary || bBuildImportLibraryOnly; // ReponseLines.Add( // bIsBuildingLibrary ? // GetLibArguments(LinkEnvironment) : // GetLinkArguments(LinkEnvironment) // ); ReponseLines.Add(GetLinkArguments(LinkEnvironment)); // Add the input files to a response file, and pass the response file on the command-line. foreach (FileItem InputFile in LinkEnvironment.InputFiles) { //System.Console.WriteLine("File {0} ", InputFile.AbsolutePath); ReponseLines.Add(string.Format(" \"{0}\"", InputFile.AbsolutePath)); LinkAction.PrerequisiteItems.Add(InputFile); } if (!LinkEnvironment.bIsBuildingLibrary) { // Make sure ThirdParty libs are at the end. List <string> ThirdParty = (from Lib in LinkEnvironment.AdditionalLibraries where Lib.Contains("ThirdParty") select Lib).ToList(); LinkEnvironment.AdditionalLibraries.RemoveAll(Element => Element.Contains("ThirdParty")); LinkEnvironment.AdditionalLibraries.AddRange(ThirdParty); foreach (string InputFile in LinkEnvironment.AdditionalLibraries) { FileItem Item = FileItem.GetItemByPath(InputFile); if (Item.AbsolutePath.Contains(".lib")) { continue; } if (Item.ToString().EndsWith(".js")) { ReponseLines.Add(string.Format(" --js-library \"{0}\"", Item.AbsolutePath)); } // WARNING: With --pre-js and --post-js, the order in which these directives are passed to // the compiler is very critical, because that dictates the order in which they are appended. // // Set environment variable [ EMCC_DEBUG=1 ] to see the linker order used in packaging. // See GetSharedArguments_Global() above to set this environment variable else if (Item.ToString().EndsWith(".jspre")) { ReponseLines.Add(string.Format(" --pre-js \"{0}\"", Item.AbsolutePath)); } else if (Item.ToString().EndsWith(".jspost")) { ReponseLines.Add(string.Format(" --post-js \"{0}\"", Item.AbsolutePath)); } else { ReponseLines.Add(string.Format(" \"{0}\"", Item.AbsolutePath)); } LinkAction.PrerequisiteItems.Add(Item); } } // make the file we will create OutputFile = FileItem.GetItemByFileReference(LinkEnvironment.OutputFilePath); LinkAction.ProducedItems.Add(OutputFile); ReponseLines.Add(string.Format(" -o \"{0}\"", OutputFile.AbsolutePath)); FileItem OutputLink = FileItem.GetItemByPath(LinkEnvironment.OutputFilePath.FullName.Replace(".js", libExt).Replace(".html", libExt)); LinkAction.ProducedItems.Add(OutputLink); if (!useLLVMwasmBackend) { ReponseLines.Add(string.Format(" --save-bc \"{0}\"", OutputLink.AbsolutePath)); } LinkAction.StatusDescription = Path.GetFileName(OutputFile.AbsolutePath); FileReference ResponseFileName = GetResponseFileName(LinkEnvironment, OutputFile); FileItem ResponseFileItem = FileItem.CreateIntermediateTextFile(ResponseFileName, ReponseLines); LinkAction.CommandArguments += string.Format(" @\"{0}\"", ResponseFileName); LinkAction.PrerequisiteItems.Add(ResponseFileItem); Actions.Add(LinkAction); return(OutputFile); }
public virtual void FixedUpdate() { if (reactorModule != null && Lib.IsFlight()) { if (Features.Radiation && emitter != null) { if (!ReactorHasStarted && !reactorModule.Enabled && EmitterRunning) { // Disable radiation source, because reactor has not started yet emitter.running = false; EmitterRunning = false; } if (!ReactorHasStarted && reactorModule.Enabled) { // Reactor has started - enable radiation source ReactorHasStarted = true; emitter.running = true; emitter.radiation = EmitterMaxRadiation; } if (LastReactorState != reactorModule.Enabled) { LastReactorState = reactorModule.Enabled; if (reactorModule.Enabled) { // Reactor has started again - set radiation source emission to maximum emitter.radiation = EmitterMaxRadiation; ReactorStoppedTimestamp = 0d; } else { // Reactor has stopped - save timestamp, when it happened ReactorStoppedTimestamp = Planetarium.GetUniversalTime(); } } if (!reactorModule.Enabled && ReactorHasStarted && ReactorStoppedTimestamp > 0 && MinEmissionPercent < 100) { // Radiation decay double MinRadiation = EmitterMaxRadiation * MinEmissionPercent / 100; if (EmissionDecayRate <= 0) { emitter.radiation = MinRadiation; ReactorStoppedTimestamp = 0d; } else { double secondsPassed = Planetarium.GetUniversalTime() - ReactorStoppedTimestamp; if (secondsPassed > 0) { double NewRadiation = EmitterMaxRadiation * (100 - secondsPassed / EmissionDecayRate) / 100; if (NewRadiation <= MinRadiation) { NewRadiation = MinRadiation; ReactorStoppedTimestamp = 0d; } emitter.radiation = NewRadiation; } } } } // Update MaxThrottle according to reactor CoreIntegrity MaxThrottle = reactorModule.CoreIntegrity / 100f; if (MinThrottle > MaxThrottle) { MinThrottle = MaxThrottle; } } }