public void NtpWorks() { NTP ntp = new NTP(); var tm = ntp.GetTimeFromHost("time.windows.com"); Assert.Equal(tm.Year, 2017); }
public void method_0(string url) { if (!string.IsNullOrEmpty(url)) { try { DateTime networkTime = NTP.GetNetworkTime(url); NTPTime.SYSTEMTIME sYSTEMTIME = new NTPTime.SYSTEMTIME() { wHour = (short)networkTime.Hour, wMinute = (short)networkTime.Minute, wSecond = (short)networkTime.Second, wMilliseconds = (short)networkTime.Millisecond, wDay = (short)networkTime.Day, wMonth = (short)networkTime.Month, wYear = (short)networkTime.Year, wDayOfWeek = (short)networkTime.DayOfWeek }; IntPtr token = WindowsIdentity.GetCurrent().Token; (new WindowsIdentity(token)).Impersonate(); NTPTime.SetSystemTime(ref sYSTEMTIME); NTPTime.SetLocalTime(ref sYSTEMTIME); DateTime now = DateTime.Now; } catch (Exception exception) { string message = exception.Message; } } }
static void SendTime() { using (UdpClient sender = new UdpClient()) { for (; ;) { //Get time from the NTP server byte[] buffer = Encoding.ASCII.GetBytes(NTP.GetNetworkTime().ToString()); sender.Send(buffer, buffer.Length, remoteAddress, remotePort); } } }
/// <summary> /// Add values to the NodeType Properties of a Node. /// </summary> /// <param name="Node">The Node whose properties are being filled in.</param> /// <param name="CurrentIndex">The current index in the ProductSize array in a CswC3Product object. This is ONLY needed for Size Nodes.</param> public void addNodeTypeProps(CswNbtNode Node, int CurrentIndex = 0) { CswNbtMetaDataNodeType NodeType = _CswNbtResources.MetaData.getNodeType(Node.NodeTypeId); foreach (CswNbtMetaDataNodeTypeProp NTP in NodeType.getNodeTypeProps()) { if (null != Node.Properties[NTP] && _Mappings.ContainsKey(NTP.PropName)) { C3Mapping C3Mapping = _Mappings[NTP.PropName]; switch (Node.Properties[NTP].getFieldTypeValue()) { case CswEnumNbtFieldType.MOL: if (false == string.IsNullOrEmpty(C3Mapping.C3ProductPropertyValue)) { string propAttr = new CswPropIdAttr(Node, NTP).ToString(); string molData = C3Mapping.C3ProductPropertyValue; CswNbtSdBlobData SdBlobData = new CswNbtSdBlobData(_CswNbtResources); MolecularGraph Mol = MoleculeBuilder.CreateMolFromString(molData); if (false == Mol.ContainsInvalidAtom()) { string Href; string FormattedMolString; string errorMsg; SdBlobData.saveMol(molData, propAttr, out Href, out FormattedMolString, out errorMsg, Node: Node); } else { _CswNbtResources.logMessage("Failed to save the MOL file for product with ProductId " + _ProductToImport.ProductId + " during the C3 import process because it contained an invalid atom."); } } break; default: CswNbtSubField SubField = NTP.getFieldTypeRule().SubFields[(CswEnumNbtPropColumn)C3Mapping.NBTSubFieldPropColName]; if (null != SubField) { Node.Properties[NTP].SetSubFieldValue(SubField, C3Mapping.C3ProductPropertyValue); } break; } } //if( null != Node.Properties[NTP] && _Mappings.ContainsKey( NTP.PropName ) ) } //foreach( CswNbtMetaDataNodeTypeProp NTP in NodeType.getNodeTypeProps() ) } //addNodeTypeProps()
public override void update() { CswNbtMetaDataObjectClass BiologicalOC = _CswNbtSchemaModTrnsctn.MetaData.getObjectClass( CswEnumNbtObjectClass.BiologicalClass ); CswNbtMetaDataObjectClass SupplyOC = _CswNbtSchemaModTrnsctn.MetaData.getObjectClass( CswEnumNbtObjectClass.NonChemicalClass ); foreach( CswNbtMetaDataObjectClass MaterialOC in new[] {BiologicalOC, SupplyOC} ) { CswNbtMetaDataObjectClassProp OpenExpireOCP = MaterialOC.getObjectClassProp( CswNbtPropertySetMaterial.PropertyName.OpenExpireInterval ); CswNbtMetaDataObjectClassProp ExpirationIntervalOCP = MaterialOC.getObjectClassProp( CswNbtPropertySetMaterial.PropertyName.ExpirationInterval ); foreach( CswNbtMetaDataObjectClassProp OCP in new[] {OpenExpireOCP, ExpirationIntervalOCP} ) { foreach( CswNbtMetaDataNodeTypeProp NTP in OCP.getNodeTypeProps() ) { CswNbtMetaDataNodeType NT = NTP.getNodeType(); NTP.updateLayout( CswEnumNbtLayoutType.Edit, true, NT.getFirstNodeTypeTab().TabId ); } } } } // update()
public override void update() { #region Create DSD NodeType CswNbtMetaDataNodeType DSD_NT = _CswNbtSchemaModTrnsctn.MetaData.makeNewNodeType( CswEnumNbtObjectClass.DSDPhraseClass, "DSD Phrase", "System" ); DSD_NT.setNameTemplateText( CswNbtMetaData.MakeTemplateEntry( CswNbtPropertySetPhrase.PropertyName.Code ) ); foreach( CswNbtMetaDataNodeTypeProp NTP in DSD_NT.getNodeTypeProps() ) { if( CswNbtPropertySetPhrase.PropertyName.English != NTP.PropName && CswNbtPropertySetPhrase.PropertyName.Code != NTP.PropName && CswNbtObjClassDSDPhrase.PropertyName.Category != NTP.PropName ) { NTP.removeFromAllLayouts(); } } #endregion #region Create SD Phrases #region Risk Phrases Dictionary<string, string> RiskPhrases = new Dictionary<string, string>() { {"R0", "no code"}, {"R1", "Explosive when dry."}, {"R10", "Flammable."}, {"R11", "Highly flammable."}, {"R12", "Extremely flammable."}, {"R14", "Reacts violently with water."}, {"R14/15", "Reacts violently with water, liberating extremely flammable gases."}, {"R15", "Contact with water liberates extremely flammable gases."}, {"R15/29", "Contact with water liberates toxic, extremely flammable gas."}, {"R16", "Explosive when mixed with oxidising substances."}, {"R17", "Spontaneously flammable in air."}, {"R18", "In use, may form flammable/explosive vapour-air mixture."}, {"R19", "May form explosive peroxides."}, {"R2", "Risk of explosion by shock, friction, fire or other sources of ignition."}, {"R20", "Harmful by inhalation."}, {"R20/21", "Harmful by inhalation and in contact with skin."}, {"R20/21/22", "Harmful by inhalation, in contact with skin and if swallowed."}, {"R20/22", "Harmful by inhalation and if swallowed."}, {"R21", "Harmful in contact with skin."}, {"R21/22", "Harmful in contact with skin and if swallowed."}, {"R22", "Harmful if swallowed."}, {"R23", "Toxic by inhalation."}, {"R23/24", "Toxic by inhalation and in contact with skin."}, {"R23/24/25", "Toxic by inhalation, in contact with skin and if swallowed."}, {"R23/25", "Toxic by inhalation and if swallowed."}, {"R24", "Toxic in contact with skin."}, {"R24/25", "Toxic in contact with skin and if swallowed."}, {"R25", "Toxic if swallowed."}, {"R26", "Very toxic by inhalation."}, {"R26/27", "Very toxic by inhalation and in contact with skin."}, {"R26/27/28", "Very toxic by inhalation, in contact with skin and if swallowed."}, {"R26/28", "Very toxic by inhalation and if swallowed."}, {"R27", "Very toxic in contact with skin."}, {"R27/28", "Very toxic in contact with skin and if swallowed."}, {"R28", "Very toxic if swallowed."}, {"R29", "Contact with water liberates toxic gas."}, {"R3", "Extreme risk of explosion by shock, friction, fire or other sources of ignition."}, {"R30", "Can become highly flammable in use."}, {"R31", "Contact with acids liberates toxic gas."}, {"R32", "Contact with acids liberates very toxic gas."}, {"R33", "Danger of cumulative effects."}, {"R34", "Causes burns."}, {"R35", "Causes severe burns."}, {"R36", "Irritating to eyes."}, {"R36/37", "Irritating to eyes and respiratory system."}, {"R36/37/38", "Irritating to eyes, respiratory system and skin."}, {"R36/38", "Irritating to eyes and skin."}, {"R37", "Irritating to respiratory system."}, {"R37/38", "Irritating to respiratory system and skin."}, {"R38", "Irritating to skin."}, {"R39", "Danger of very serious irreversible effects."}, {"R39/23", "Toxic: danger of very serious irreversible effects through inhalation."}, {"R39/23/24", "Toxic: danger of very serious irreversible effects through inhalation and in contact with skin."}, {"R39/23/24/25", "Toxic: danger of very serious irreversible effects through inhalation, in contact with skin and if swallowed."}, {"R39/23/25", "Toxic: danger of very serious irreversible effects through inhalation and if swallowed."}, {"R39/24", "Toxic: danger of very serious irreversible effects in contact with skin."}, {"R39/24/25", "Toxic: danger of very serious irreversible effects in contact with skin and if swallowed."}, {"R39/25", "Toxic: danger of very serious irreversible effects if swallowed."}, {"R39/26", "Very toxic: danger of very serious irreversible effects through inhalation."}, {"R39/26/27", "Very toxic: danger of very serious irreversible effects through inhalation and in contact with skin."}, {"R39/26/27/28", "Very toxic: danger of very serious irreversible effects through inhalation, in contact with skin and if swallowed."}, {"R39/26/28", "Very toxic: danger of very serious irreversible effects through inhalation and if swallowed."}, {"R39/27", "Very toxic: danger of very serious irreversible effects in contact with skin."}, {"R39/27/28", "Very toxic: danger of very serious irreversible effects in contact with skin and if swallowed."}, {"R39/28", "Very toxic: danger of very serious irreversible effects if swallowed."}, {"R4", "Forms very sensitive explosive metallic compounds."}, {"R40", "Limited evidence of a carcinogenic effect."}, {"R41", "Risk of serious damage to eyes."}, {"R42", "May cause sensitisation by inhalation."}, {"R42/43", "May cause sensitisation by inhalation and skin contact."}, {"R43", "May cause sensitisation by skin contact."}, {"R44", "Risk of explosion if heated under confinement."}, {"R45", "May cause cancer."}, {"R46", "May cause heritable genetic damage."}, {"R48", "Danger of serious damage to health by prolonged exposure."}, {"R48/20", "Harmful: danger of serious damage to health by prolonged exposure through inhalation."}, {"R48/20/21", "Harmful: danger of serious damage to health by prolonged exposure through inhalation and in contact with skin."}, {"R48/20/21/22", "Harmful: danger of serious damage to health by prolonged exposure through inhalation, in contact with skin and if swallowed."}, {"R48/20/22", "Harmful: danger of serious damage to health by prolonged exposure through inhalation and if swallowed."}, {"R48/21", "Harmful: danger of serious damage to health by prolonged exposure in contact with skin."}, {"R48/21/22", "Harmful: danger of serious damage to health by prolonged exposure in contact with skin and if swallowed."}, {"R48/22", "Harmful: danger of serious damage to health by prolonged exposure if swallowed."}, {"R48/23", "Toxic: danger of serious damage to health by prolonged exposure through inhalation."}, {"R48/23/24", "Toxic: danger of serious damage to health by prolonged exposure through inhalation and in contact with skin."}, {"R48/23/24/25", "Toxic: danger of serious damage to health by prolonged exposure through inhalation, in contact with skin and if swallowed."}, {"R48/23/25", "Toxic: danger of serious damage to health by prolonged exposure through inhalation and if swallowed."}, {"R48/24", "Toxic: danger of serious damage to health by prolonged exposure in contact with skin."}, {"R48/24/25", "Toxic: danger of serious damage to health by prolonged exposure in contact with skin and if swallowed."}, {"R48/25", "Toxic: danger of serious damage to health by prolonged exposure if swallowed."}, {"R49", "May cause cancer by inhalation."}, {"R5", "Heating may cause an explosion."}, {"R50", "Very toxic to aquatic organisms."}, {"R50/53", "Very toxic to aquatic organisms, may cause long-term adverse effects in the aquatic environment."}, {"R51", "Toxic to aquatic organisms."}, {"R51/53", "Toxic to aquatic organisms, may cause long-term adverse effects in the aquatic environment."}, {"R52", "Harmful to aquatic organisms."}, {"R52/53", "Harmful to aquatic organisms, may cause long-term adverse effects in the aquatic environment."}, {"R53", "May cause long-term adverse effects in the aquatic environment."}, {"R54", "Toxic to flora."}, {"R55", "Toxic to fauna."}, {"R56", "Toxic to soil organisms."}, {"R57", "Toxic to bees."}, {"R58", "May cause long-term adverse effects in the environment."}, {"R59", "Dangerous for the ozone layer."}, {"R6", "Explosive with or without contact with air."}, {"R60", "May impair fertility."}, {"R61", "May cause harm to the unborn child."}, {"R62", "Possible risk of impaired fertility."}, {"R63", "Possible risk of harm to the unborn child."}, {"R64", "May cause harm to breastfed babies."}, {"R65", "Harmful: may cause lung damage if swallowed."}, {"R66", "Repeated exposure may cause skin dryness or cracking."}, {"R67", "Vapours may cause drowsiness and dizziness."}, {"R68", "Possible risk of irreversible effects."}, {"R68/20", "Harmful: possible risk of irreversible effects through inhalation."}, {"R68/20/21", "Harmful: possible risk of irreversible effects through inhalation and in contact with skin."}, {"R68/20/21/22", "Harmful: possible risk of irreversible effects through inhalation, in contact with skin and if swallowed."}, {"R68/20/22", "Harmful: possible risk of irreversible effects through inhalation and if swallowed."}, {"R68/21", "Harmful: possible risk of irreversible effects in contact with skin."}, {"R68/21/22", "Harmful: possible risk of irreversible effects in contact with skin and if swallowed."}, {"R68/22", "Harmful: possible risk of irreversible effects if swallowed."}, {"R7", "May cause fire."}, {"R8", "Contact with combustible material may cause fire."}, {"R9", "Explosive when mixed with combustible material."} }; #endregion #region Safety Phrases Dictionary<string, string> SafetyPhrases = new Dictionary<string, string>() { {"S1", "Keep locked up."}, {"S1/2", "Keep locked up and out of the reach of children."}, {"S12", "Do not keep the container sealed."}, {"S13", "Keep away from food, drink and animal feedingstuffs."}, {"S14", "Keep away from . (incompatible materials to be indicated by the manufacturer)."}, {"S15", "Keep away from heat."}, {"S16", "Keep away from sources of ignition . No smoking."}, {"S17", "Keep away from combustible material."}, {"S18", "Handle and open container with care."}, {"S2", "Keep out of the reach of children."}, {"S20", "When using do not eat or drink."}, {"S20/21", "When using do not eat, drink or smoke."}, {"S21", "When using do not smoke."}, {"S22", "Do not breathe dust."}, {"S23", "Do not breathe gas/fumes/vapour/spray (appropriate wording to be specified by the manufacturer)."}, {"S24", "Avoid contact with skin."}, {"S24/25", "Avoid contact with skin and eyes."}, {"S25", "Avoid contact with eyes."}, {"S26", "In case of contact with eyes, rinse immediately with plenty of water and seek medical advice."}, {"S27", "Take off immediately all contaminated clothing."}, {"S27/28", "After contact with skin, take off immediately all contaminated clothing, and wash immediately with plenty of (to be specified by the manufacturer)."}, {"S28", "After contact with skin, wash immediately with plenty of . (to be specified by the manufacturer)."}, {"S29", "Do not empty into drains."}, {"S29/35", "Do not empty into drains; dispose of this material and its container in a safe way."}, {"S29/56", "Do not empty into drains, dispose of this material and its container at hazardous or special waste collection point."}, {"S3", "Keep in a cool place."}, {"S3/14", "Keep in a cool place away from . (incompatible materials to be indicated by the manufacturer)."}, {"S3/7", "Keep container tightly closed in a cool place."}, {"S3/9/14", "Keep in a cool, well-ventilated place away from . (incompatible materials to be indicated by the manufacturer)."}, {"S3/9/14/49", "Keep only in the original container in a cool, well-ventilated place away from . (incompatible materials to be indicated by the manufacturer)."}, {"S3/9/49", "Keep only in the original container in a cool, well-ventilated place."}, {"S30", "Never add water to this product."}, {"S33", "Take precautionary measures against static discharges."}, {"S35", "This material and its container must be disposed of in a safe way."}, {"S36", "Wear suitable protective clothing."}, {"S36/37", "Wear suitable protective clothing and gloves."}, {"S36/37/39", "Wear suitable protective clothing, gloves and eye/face protection."}, {"S36/39", "Wear suitable protective clothing and eye/face protection."}, {"S37", "Wear suitable gloves."}, {"S37/39", "Wear suitable gloves and eye/face protection."}, {"S38", "In case of insufficient ventilation, wear suitable respiratory equipment."}, {"S39", "Wear eye/face protection."}, {"S4", "Keep away from living quarters."}, {"S40", "To clean the floor and all objects contaminated by this material, use . (to be specified by the manufacturer)."}, {"S41", "In case of fire and/or explosion do not breathe fumes."}, {"S42", "During fumigation/spraying wear suitable respiratory equipment (appropriate wording to be specified by the manufacturer)."}, {"S43", "In case of fire, use . (indicate in the space the precise type of fire-fighting equipment. If water increases risk, add .Never use water.)."}, {"S45", "In case of accident or if you feel unwell, seek medical advice immediately (show the label where possible)."}, {"S46", "If swallowed, seek medical advice immediately and show this container or label."}, {"S47", "Keep at temperature not exceeding . °C (to be specified by the manufacturer)."}, {"S47/49", "Keep only in the original container at a temperature not exceeding . °C (to be specified by the manufacturer)."}, {"S48", "Keep wet with . (appropriate material to be specified by the manufacturer)."}, {"S49", "Keep only in the original container."}, {"S5", "Keep contents under . (appropriate liquid to be specified by the manufacturer)."}, {"S50", "Do not mix with . (to be specified by the manufacturer)."}, {"S51", "Use only in well-ventilated areas."}, {"S52", "Not recommended for interior use on large surface areas."}, {"S53", "Avoid exposure . obtain special instructions before use."}, {"S56", "Dispose of this material and its container to hazardous or special waste collection point."}, {"S57", "Use appropriate container to avoid environmental contamination."}, {"S59", "Refer to manufacturer/supplier for information on recovery/recycling."}, {"S6", "Keep under . (inert gas to be specified by the manufacturer)."}, {"S60", "This material and its container must be disposed of as hazardous waste."}, {"S61", "Avoid release to the environment. Refer to special instructions/safety data sheets."}, {"S62", "If swallowed, do not induce vomiting: seek medical advice immediately and show this container or label."}, {"S63", "In case of accident by inhalation: remove casualty to fresh air and keep at rest."}, {"S64", "If swallowed, rinse mouth with water (only if the person is conscious)."}, {"S7", "Keep container tightly closed."}, {"S7/47", "Keep container tightly closed and at a temperature not exceeding . °C (to be specified by the manufacturer)."}, {"S7/8", "Keep container tightly closed and dry."}, {"S7/9", "Keep container tightly closed and in a well-ventilated place."}, {"S8", "Keep container dry."}, {"S9", "Keep container in a well-ventilated place."} }; #endregion CswNbtMetaDataObjectClass DSDPhraseOC = _CswNbtSchemaModTrnsctn.MetaData.getObjectClass( CswEnumNbtObjectClass.DSDPhraseClass ); foreach( KeyValuePair<string, string> Phrase in RiskPhrases ) { _CswNbtSchemaModTrnsctn.Nodes.makeNodeFromNodeTypeId( DSDPhraseOC.getNodeTypeIds().FirstOrDefault(), OnAfterMakeNode: delegate( CswNbtNode NewNode ) { CswNbtObjClassDSDPhrase NewPhrase = NewNode; NewPhrase.Code.Text = Phrase.Key; NewPhrase.English.Text = Phrase.Value; NewPhrase.Category.Value = "Risk"; } ); } foreach( KeyValuePair<string, string> Phrase in SafetyPhrases ) { _CswNbtSchemaModTrnsctn.Nodes.makeNodeFromNodeTypeId( DSDPhraseOC.getNodeTypeIds().FirstOrDefault(), OnAfterMakeNode: delegate( CswNbtNode NewNode ) { CswNbtObjClassDSDPhrase NewPhrase = NewNode; NewPhrase.Code.Text = Phrase.Key; NewPhrase.English.Text = Phrase.Value; NewPhrase.Category.Value = "Safety"; } ); } #endregion #region DSD Tab CswNbtMetaDataObjectClass ChemicalOC = _CswNbtSchemaModTrnsctn.MetaData.getObjectClass( CswEnumNbtObjectClass.ChemicalClass ); foreach( CswNbtMetaDataNodeType ChemicalNT in ChemicalOC.getNodeTypes() ) { CswNbtMetaDataNodeTypeTab GHSTab = ChemicalNT.getNodeTypeTab( "GHS" ); int DSDTabOrder = ( null != GHSTab ? GHSTab.TabOrder : ChemicalNT.getMaximumTabOrder() ) + 1; CswNbtMetaDataNodeTypeTab DSDTab = ChemicalNT.getNodeTypeTab( "DSD" ) ?? _CswNbtSchemaModTrnsctn.MetaData.makeNewTab( ChemicalNT, "DSD", DSDTabOrder ); CswNbtMetaDataNodeTypeProp PictogramsNTP = ChemicalNT.getNodeTypePropByObjectClassProp( CswNbtObjClassChemical.PropertyName.Pictograms ); PictogramsNTP.removeFromAllLayouts(); PictogramsNTP.updateLayout( CswEnumNbtLayoutType.Edit, true, DSDTab.TabId ); CswNbtMetaDataNodeTypeProp LabelCodesNTP = ChemicalNT.getNodeTypePropByObjectClassProp( CswNbtObjClassChemical.PropertyName.LabelCodes ); LabelCodesNTP.Extended = ","; LabelCodesNTP.removeFromAllLayouts(); LabelCodesNTP.updateLayout( CswEnumNbtLayoutType.Edit, true, DSDTab.TabId ); CswNbtView LabelCodesView = _CswNbtSchemaModTrnsctn.ViewSelect.restoreView( "DSD Label Codes Property Grid", CswEnumNbtViewVisibility.Property ); CswNbtMetaDataNodeTypeProp LabelCodesGridNTP = ChemicalNT.getNodeTypePropByObjectClassProp( CswNbtObjClassChemical.PropertyName.LabelCodesGrid ); LabelCodesGridNTP.ViewId = LabelCodesView.ViewId; LabelCodesGridNTP.Extended = "Small"; LabelCodesGridNTP.removeFromAllLayouts(); LabelCodesGridNTP.updateLayout( CswEnumNbtLayoutType.Edit, true, DSDTab.TabId ); } #endregion #region DSD Module int dsdModuleId = _CswNbtSchemaModTrnsctn.createModule( "Dangerous Substances Directive", CswEnumNbtModuleName.DSD, false ); _CswNbtSchemaModTrnsctn.Modules.CreateModuleDependency( CswEnumNbtModuleName.CISPro, CswEnumNbtModuleName.DSD ); _CswNbtSchemaModTrnsctn.createModuleObjectClassJunction( dsdModuleId, DSDPhraseOC.ObjectClassId ); #endregion } // update()
public static void Main() { Logging.log_entry("starting"); Debug.EnableGCMessages(false); // >>> inicializace site Microsoft.SPOT.Net.NetworkInformation.NetworkInterface[] interfaces = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); string dhcp = FileUtilities.file_get_contents(@"\SD\setup\dhcp"); if (dhcp.Trim().Equals("0")) { interfaces[0].EnableStaticIP( FileUtilities.file_get_contents(@"\SD\setup\ip_address").Trim(), FileUtilities.file_get_contents(@"\SD\setup\netmask").Trim(), FileUtilities.file_get_contents(@"\SD\setup\gateway").Trim() ); } else { Logging.log_entry("default dhcp"); interfaces[0].EnableDhcp(); } Logging.log_entry("init networking done, ip: " + interfaces[0].IPAddress); // <<< // >>> datum a cas z ntp int timezone; try { timezone = int.Parse(FileUtilities.file_get_contents(@"\SD\setup\timezone").Trim()); } catch (Exception) { timezone = 0; } string ntp_servers = FileUtilities.file_get_contents(@"\SD\setup\ntp_server").Trim(); DateTime time = new DateTime(); if (ntp_servers.Length > 0) { // je k dispozici nastaveni, vyzkousim string[] ntp_server = ntp_servers.Split('\n'); if (ntp_server.Length > 0) { for (int i = 0; i < ntp_server.Length; i++) { try { time = NTP.NTPTime(ntp_server[i].Trim(), timezone).ToUniversalTime(); } catch (Exception) { } if (time.Year > 2000) { Logging.log_entry("got time from " + ntp_server[i].Trim()); break; } } } else { time = new DateTime(); } } else { Logging.log_entry("using default ntp"); time = NTP.NTPTime("time-a.nist.gov", timezone).ToUniversalTime(); } if (time.ToString().Length > 0 && time.Year > 2000) { Utility.SetLocalTime(time); Logging.log_entry("init time, local time set to " + time.ToString()); } else { Logging.log_entry("init time, cannot set local time, rebooting"); PowerState.RebootDevice(false); } // <<< // >>> spusteni webserveru Logging.log_entry("starting webserver"); new Thread(startWebServer).Start(); // <<< new Thread(blinkerThread).Start(); }
static int Main(string[] args) { string logFile = DateTime.Now.ToString("yyyy-MM-dd HH") + ".log"; bool alsoLog = args.Contains(LogSwitch); foreach (string s in HelpSwitches) { if (args.Contains(s)) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("\r\n==================================================================================================="); Console.WriteLine("UpdateLocalTimeNTP.exe Usage: *NOTE: PROGRAM MUST BE RUN AS ADMIN TO APPLY CHANGES!*"); Console.WriteLine(" -nochange Test operation but make no clock changes."); Console.WriteLine(" -force (cannot be used with -nochange) Force an update even if drastically off or tiny."); Console.WriteLine(" -log Log operations to local folder for unattended troubleshooting."); Console.WriteLine(" Logs do not clean themselves up! Format=YEAR-MM-DD Hour.log (one log file per hour)."); Console.WriteLine(" Error logs are always written even if -log is not specified (ERROR-...log"); Console.WriteLine(" -nopause Exit upon completion (allow console window to close)."); Console.WriteLine(" -resetlist Re-add all servers, even ones that have failed in the past."); Console.WriteLine(" If servers.txt is missing, program will recreate it from internal list."); Console.WriteLine(" Edit active.txt or servers.txt if you want to use your own servers. (active.txt is rebuilt"); Console.WriteLine(" from servers.txt if present or internal list)."); Console.WriteLine(" -count:X (no spaces) Number of servers to use where X is between " + ServerListHandler.MIN_SERVER_REQUEST + " and " + ServerListHandler.MAX_SERVER_REQUEST + " (inclusive, default " + DefaultServerCount + ")"); Console.WriteLine(" -mincor:X (no spaces) Number of minimum MILLISECONDS to allow for adjustment (default, " + MinCorrection + " ms)"); Console.WriteLine(" -maxcor:X (no spaces) Number of maximum MINUTES to allow for adjustment (default, " + MaxCorrection + " minutes)"); Console.WriteLine(" Corrections above the max or below the min will be ignored without -force switch."); Console.WriteLine("=====================================================================================================\r\n"); return(0); } } if (args.Contains(FullServerListSwitch)) { ServerListHandler.ResetActiveServers(alsoLog, logFile); } if (args.Contains(ForceSwitch) && args.Contains(NoChangeSwitch)) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*INVALID SWITCH COMBINATION! Force and No Change cannot be used", true, true, logFile); Common.WriteAndLogThisLine(" at the same time! Operation canceled*", true, true, logFile); return(-1); } if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*No Network Detected! Check your network connections and be sure ", true, true, logFile); Common.WriteAndLogThisLine(" this machine is connected to the Internet. Operation canceled*", true, true, logFile); return(-1); } Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ImportantColor; Common.WriteAndLogThisLine("Update Local Date/Time via NTP", alsoLog, false, logFile); Common.WriteAndLogThisLine("======================================================================", alsoLog, false, logFile); foreach (string a in args) { if (a.StartsWith(CountParameter) && a.Length > CountParameter.Length) { int index = a.IndexOf(':'); if (index > 0) { string c = a.Substring(a.IndexOf(':') + 1); if (!int.TryParse(c, out serverCount)) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*Warning (non-fatal): '-count:' flag value not an integer", true, false, logFile); Common.WriteAndLogThisLine(" Defaulting to " + DefaultServerCount + " servers.", true, false, logFile); serverCount = DefaultServerCount; } else if (serverCount > ServerListHandler.MAX_SERVER_REQUEST || serverCount < ServerListHandler.MIN_SERVER_REQUEST) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*Warning (non-fatal): '-count:' flag value out of range " + "(" + ServerListHandler.MIN_SERVER_REQUEST + " to " + ServerListHandler.MAX_SERVER_REQUEST + " inclusive)! ", true, false, logFile); Common.WriteAndLogThisLine(" Defaulting to " + DefaultServerCount + " servers.", true, false, logFile); serverCount = DefaultServerCount; } } } if (a.StartsWith(MaxCorParameter) && a.Length > MaxCorParameter.Length) { int index = a.IndexOf(':'); if (index > 0) { string c = a.Substring(a.IndexOf(':') + 1); if (!int.TryParse(c, out MaxUserCorrection)) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*Warning (non-fatal): '-maxcor:' flag value not an integer", true, false, logFile); Common.WriteAndLogThisLine(" Defaulting to " + MaxCorrection + " minutes.", true, false, logFile); MaxUserCorrection = MaxCorrection; } else if (MaxUserCorrection > 24 * 60 || MaxUserCorrection < 1) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*Warning (non-fatal): '-maxcor:' flag value out of range " + "(1 to " + (24 * 60).ToString() + " (=1 day) minutes inclusive)! ", true, false, logFile); Common.WriteAndLogThisLine(" Defaulting to " + MaxCorrection + " minutes.", true, false, logFile); MaxUserCorrection = MaxCorrection; } } } if (a.StartsWith(MinCorParameter) && a.Length > MinCorParameter.Length) { int index = a.IndexOf(':'); if (index > 0) { string c = a.Substring(a.IndexOf(':') + 1); if (!int.TryParse(c, out MinUserCorrection)) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*Warning (non-fatal): '-mincor:' flag value not an integer", true, false, logFile); Common.WriteAndLogThisLine(" Defaulting to " + MinCorrection + " milliseconds.", true, false, logFile); MinUserCorrection = MinCorrection; } else if (MinUserCorrection < 100 || MinUserCorrection > 600000) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*Warning (non-fatal): '-mincor:' flag value out of range " + "(100 to 600000 (=10 minutes) milliseconds inclusive)! ", true, false, logFile); Common.WriteAndLogThisLine(" Defaulting to " + MinCorrection + " milliseconds.", true, false, logFile); MinUserCorrection = MinCorrection; } } } } Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = NormalColor; System.Diagnostics.Stopwatch programElapsedTime = new System.Diagnostics.Stopwatch(); programElapsedTime.Start(); Common.WriteAndLogThisLine(" Started: " + DateTimeOffset.Now.ToString(), alsoLog, false, logFile); Common.WriteAndLogThisLine(" Time corrections shown are additive differences between local and", alsoLog, false, logFile); Common.WriteAndLogThisLine(" remote (in seconds).", alsoLog, false, logFile); Common.WriteAndLogThisLine(" Negative numbers indicate local time is ahead of remote time.", alsoLog, false, logFile); if (args.Contains(NoChangeSwitch)) { Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ImportantColor; Common.WriteAndLogThisLine(" NO CHANGE switch active: No actual changes will be applied to the system.", alsoLog, false, logFile); Console.ForegroundColor = NormalColor; } //===========DO THE WORK Console.ForegroundColor = NormalColor; string[] servers = ServerListHandler.GetRandomActiveServers(serverCount, alsoLog, logFile); Common.WriteAndLogThisLine(" Using random " + serverCount + " servers from active.txt...", alsoLog, false, logFile); //try //{ // servers = System.IO.File.ReadAllLines("servers.txt"); //} //catch (Exception ex) if (servers == null || servers.Length < 3) { Console.ForegroundColor = ConsoleColor.Red; Common.WriteAndLogThisLine(" *Problem getting servers (null or too few), Operation Terminated!", alsoLog, true, logFile); Common.WriteAndLogThisLine(" Use '-resetlist' or delete 'active.txt' and 'servers.txt' to correct.", alsoLog, true, logFile); if (!args.Contains(NoPauseSwitch)) { Console.WriteLine("...press any key to terminate program..."); Console.ReadKey(true); } return(-1); } if (serverCount > servers.Length) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*Warning (non-fatal): Requested server count not available, use '-resetlist' and try again.", alsoLog, false, logFile); } Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ImportantColor; Common.WriteAndLogThisLine("=Begin server communication============", alsoLog, false, logFile); foreach (string server in servers) { if (string.IsNullOrWhiteSpace(server)) { continue; } NTPInformation stuff = new NTPInformation(); NTP.InterrogateRemote(server, ref stuff); if (stuff.Success) { successes++; Console.ForegroundColor = SuccessColor; Common.WriteAndLogThisLine("-" + server + " success, offset=" + stuff.Correction.TotalSeconds.ToString(), alsoLog, false, logFile); corrections.Add(stuff.Correction.TotalSeconds); } else { failures.Add(server); Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*" + server + " fail! ", alsoLog, false, logFile);// + stuff.Error.Message); } //*/ } int returnVal = 0; Console.ForegroundColor = ImportantColor; Console.BackgroundColor = ConsoleColor.Black; Common.WriteAndLogThisLine("=End server communication==============", alsoLog, false, logFile); Console.ForegroundColor = NormalColor; Common.WriteAndLogThisLine(" Calculating...", alsoLog, false, logFile); if (corrections != null && corrections.Count >= 3) { Statistics.Boundaries b = Statistics.Outliers.GetOuterBoundaries(corrections, true); Common.WriteAndLogThisLine(" Upper Outlier Limit:" + b.High.ToString(), alsoLog, false, logFile); Common.WriteAndLogThisLine(" Lower Outlier Limit:" + b.Low.ToString(), alsoLog, false, logFile); double average = double.NaN; int datapoints = 0; foreach (double correction in corrections) { if (!double.IsNaN(correction)) { if (correction >= b.Low && correction <= b.High) { datapoints++; if (double.IsNaN(average)) { average = correction; } else { average += correction; } } else { Console.ForegroundColor = WarningColor; Console.BackgroundColor = ConsoleColor.Black; Common.WriteAndLogThisLine("*Outlier Ignored=" + correction.ToString(), alsoLog, false, logFile); } } } if (datapoints > 0 && !double.IsNaN(average)) { average = Math.Round(average / datapoints, 7); Console.ForegroundColor = NormalColor; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine(" Average difference : " + average.ToString() + " seconds."); if (Math.Abs(average) < ((float)MinUserCorrection / 1000) && !args.Contains(ForceSwitch)) { Console.ForegroundColor = ImportantColor; Common.WriteAndLogThisLine(" Difference too small. Time drift considered OK.", alsoLog, false, logFile); } else if (Math.Abs(average) > (MaxCorrection * 60) && !args.Contains(ForceSwitch)) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine(" *Warning: Difference TOO BIG! Time drift needs manual intervention, or use", alsoLog, true, logFile); Common.WriteAndLogThisLine(" '-force' command-line switch.", alsoLog, true, logFile); returnVal = -1; } else if (!args.Contains(NoChangeSwitch)) { // maybe there should be a prompt here to ask the user if they didn't specify -nochange or -force??? if (!NTP.AdjustMachineTime(average)) { Console.ForegroundColor = ErrorColor; Common.WriteAndLogThisLine(" *FAILED TO UPDATE SYSTEM TIME!", alsoLog, true, logFile); Common.WriteAndLogThisLine(" *System API call failed!", alsoLog, true, logFile); returnVal = -1; } else { ServerListHandler.UpdateActiveServers(failures, alsoLog, logFile); // remove failed servers from active list } } else if (args.Contains(NoChangeSwitch)) { Console.ForegroundColor = ImportantColor; Common.WriteAndLogThisLine(" NO CHANGE switch active: No actual changes will be applied to the system.", alsoLog, false, logFile); ServerListHandler.UpdateActiveServers(failures, alsoLog, logFile); } } else { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine(" *Some strangeness in the data (internal error). No changes made.", alsoLog, true, logFile); returnVal = -1; } } else if (corrections != null && corrections.Count < 3) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine(" *Not enough data to use! No changes made.", alsoLog, true, logFile); returnVal = -1; } else { Console.ForegroundColor = ErrorColor; Common.WriteAndLogThisLine(" *No data to use! No changes made.", alsoLog, true, logFile); returnVal = -1; } // all done, statistics then exit Console.ForegroundColor = NormalColor; Common.WriteAndLogThisLine(" Connections: " + successes + " Failures: " + failures.Count(), alsoLog, false, logFile); Common.WriteAndLogThisLine(" Finished at: " + DateTimeOffset.Now.ToString(), alsoLog, false, logFile); Common.WriteAndLogThisLine(" Process Duration (hh:mm:ss.fffffff): " + programElapsedTime.Elapsed.ToString(), alsoLog, false, logFile); Console.ForegroundColor = ImportantColor; Common.WriteAndLogThisLine("======================================================================", alsoLog, false, logFile); Console.BackgroundColor = StartingBackground; Console.ForegroundColor = StartingForeground; if (!args.Contains(NoPauseSwitch)) { Common.WriteAndLogThisLine("...press any key to terminate program...", false, false, null); if (Console.KeyAvailable) { do { Console.ReadKey(true); } while (Console.KeyAvailable); } Console.ReadKey(true); } return(returnVal); }