internal TranslationInfo Parse() { var rslt = new TranslationInfo(); foreach (var s in this.Translation_statements) { rslt.Statments.Add(s.Parse()); } return rslt; }
public void ChangeLang(string lang) { try { Directory.GetFiles(workingDir).ToList().ForEach(file => { try { FileInfo fi = new FileInfo(file); if (fi.Extension == ".xml") { XDocument xdocT = XDocument.Load(fi.FullName); if (xdocT.Descendants("info").First().Attribute("language").Value == lang) { xdoc = XDocument.Load(fi.FullName); var infoSource = xdoc.Descendants("info").Select(x => new { Language = x.Attribute("language").Value, LanguageLong = x.Attribute("language-long").Value, Application = x.Attribute("application").Value, LastEdit = x.Attribute("lastedit").Value, Author = x.Attribute("author") == null ? string.Empty : x.Attribute("author").Value, AuthorLink = x.Attribute("author-link") == null ? string.Empty : x.Attribute("author-link").Value }).First(); info = new TranslationInfo() { Author = infoSource.Author, AuthorLink = infoSource.AuthorLink, Language = infoSource.LanguageLong, LanguageShort = infoSource.Language, LastEdit = infoSource.LastEdit }; return; } } } catch { } }); } catch (Exception e) { System.Windows.Forms.MessageBox.Show("Couldn't change language file. Please reinstall the software!\n\nError: \n" + e.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } }
/// <summary> /// This method is called at the being of the thread that processes a request. /// </summary> protected override OperationContext ValidateRequest(RequestHeader requestHeader, RequestType requestType) { OperationContext context = base.ValidateRequest(requestHeader, requestType); if (requestType == RequestType.Write) { // reject all writes if no user provided. if (context.UserIdentity.TokenType == UserTokenType.Anonymous) { // construct translation object with default text. TranslationInfo info = new TranslationInfo( "NoWriteAllowed", "en-US", "Must provide a valid user before calling write."); // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( StatusCodes.BadUserAccessDenied, "NoWriteAllowed", Opc.Ua.Gds.Namespaces.OpcUaGds, new LocalizedText(info))); } UserIdentityToken securityToken = context.UserIdentity.GetIdentityToken(); // check for a user name token. UserNameIdentityToken userNameToken = securityToken as UserNameIdentityToken; if (userNameToken != null) { lock (m_lock) { m_contexts.Add(context.RequestId, new ImpersonationContext()); } } } return(context); }
public BaseEventState GetInjectionTestReport(ISystemContext SystemContext, ushort namespaceIndex, DataRow row) { // construct translation object with default text. var info = new TranslationInfo( "InjectionTestReport", "en-US", "An injection test report is available."); // construct the event. var e = new InjectionTestReportState(null); e.Initialize( SystemContext, null, EventSeverity.Medium, new LocalizedText(info)); // override event id and time. e.EventId.Value = new Guid((string)row[Opc.Ua.BrowseNames.EventId]).ToByteArray(); e.Time.Value = (DateTime)row[Opc.Ua.BrowseNames.Time]; var nameWell = (string)row[BrowseNames.NameWell]; var uidWell = (string)row[BrowseNames.UidWell]; e.SetChildValue(SystemContext, Opc.Ua.BrowseNames.SourceName, nameWell, false); e.SetChildValue(SystemContext, Opc.Ua.BrowseNames.SourceNode, new NodeId(uidWell, namespaceIndex), false); e.SetChildValue(SystemContext, Opc.Ua.BrowseNames.LocalTime, _timeZone, false); e.SetChildValue(SystemContext, new QualifiedName(BrowseNames.NameWell, namespaceIndex), nameWell, false); e.SetChildValue(SystemContext, new QualifiedName(BrowseNames.UidWell, namespaceIndex), uidWell, false); e.SetChildValue(SystemContext, new QualifiedName(BrowseNames.TestDate, namespaceIndex), row[BrowseNames.TestDate], false); e.SetChildValue(SystemContext, new QualifiedName(BrowseNames.TestReason, namespaceIndex), row[BrowseNames.TestReason], false); e.SetChildValue(SystemContext, new QualifiedName(BrowseNames.InjectedFluid, namespaceIndex), row[BrowseNames.InjectedFluid], false); e.SetChildValue(SystemContext, new QualifiedName(BrowseNames.TestDuration, namespaceIndex), row[BrowseNames.TestDuration], false); e.TestDuration.SetChildValue(SystemContext, Opc.Ua.BrowseNames.EngineeringUnits, new EUInformation((string)row[Opc.Ua.BrowseNames.EngineeringUnits], Namespaces.HistoricalEvents), false); return(e); }
public virtual ServiceResult OnWriteValue(ISystemContext context, NodeState node, ref object value) { if (context.UserIdentity == null || context.UserIdentity.TokenType == UserTokenType.Anonymous) { TranslationInfo info = new TranslationInfo( "BadUserAccessDenied", "en-US", "User cannot change value."); return(new ServiceResult(StatusCodes.BadUserAccessDenied, new LocalizedText(info))); } try { // attempt to update file system. string filePath = value as string; if (node is PropertyState <string> variable && !string.IsNullOrEmpty(variable.Value)) { FileInfo file = new FileInfo(variable.Value); if (file.Exists) { file.Delete(); } } if (!string.IsNullOrEmpty(filePath)) { using (StreamWriter writer = new FileInfo(filePath).CreateText()) { //TODO: //writer.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name); } } value = filePath; } catch (Exception e) { return(ServiceResult.Create(e, StatusCodes.BadUserAccessDenied, "Could not update file system.")); } return(ServiceResult.Good); }
private void Search(bool matchFilter) { string searchText = (SearchText ?? "").Trim(); IEnumerable <TranslationInfo> translations = WordList.GetAllTranslations(); List <TranslationInfo> filteredTranslations = translations.Where(tr => tr.Translation.StartsWith(searchText, true, CultureInfo.InvariantCulture)).OrderBy(w => w.Translation).ToList(); MatchingTranslations = new ObservableCollection <TranslationInfo>(filteredTranslations); if (matchFilter) { TranslationInfo matchingTranslation = null; foreach (TranslationInfo translationInfo in filteredTranslations) { if (translationInfo.Translation.Equals(searchText, StringComparison.InvariantCultureIgnoreCase)) { matchingTranslation = translationInfo; break; } } CurrentTranslation = matchingTranslation; } }
/// <summary> /// Verifies that a certificate user token is trusted. /// </summary> private bool VerifyCertificate(X509Certificate2 certificate) { try { if (_certificateValidator != null) { _certificateValidator.Validate(certificate); } else { CertificateValidator.Validate(certificate); } // determine if self-signed. var isSelfSigned = Utils.CompareDistinguishedName( certificate.Subject, certificate.Issuer); // do not allow self signed application certs as user token if (isSelfSigned && Utils.HasApplicationURN(certificate)) { throw new ServiceResultException(StatusCodes.BadCertificateUseNotAllowed); } return(false); } catch (Exception e) { TranslationInfo info; StatusCode result = StatusCodes.BadIdentityTokenRejected; if (e is ServiceResultException se && se.StatusCode == StatusCodes.BadCertificateUseNotAllowed) { info = new TranslationInfo( "InvalidCertificate", "en-US", "'{0}' is an invalid user certificate.", certificate.Subject); result = StatusCodes.BadIdentityTokenInvalid; }
/// <summary> /// Reports an audit activate session event. /// </summary> private void ReportAuditActivateSessionEvent(ServerSystemContext context) { AuditActivateSessionEventState e = new AuditActivateSessionEventState(null); TranslationInfo message = new TranslationInfo( "AuditActivateSessionEvent", "en-US", "Session {0} activated.", m_sessionName); InitializeSessionAuditEvent(context, e, message); if (m_softwareCertificates != null) { e.SetChildValue(context, BrowseNames.ClientSoftwareCertificates, m_softwareCertificates.ToArray(), false); } if (m_identityToken != null) { e.SetChildValue(context, BrowseNames.UserIdentityToken, Utils.Clone(m_identityToken), false); } m_server.ReportEvent(context, e); }
/// <summary> /// Verifies that a certificate user token is trusted. /// </summary> private void VerifyCertificate(X509Certificate2 certificate) { try { m_certificateValidator.Validate(certificate); } catch (Exception e) { // construct translation object with default text. TranslationInfo info = new TranslationInfo( "InvalidCertificate", "en-US", "'{0}' is not a trusted user certificate.", certificate.Subject); // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( e, StatusCodes.BadIdentityTokenRejected, "InvalidCertificate", "http://opcfoundation.org/UA/Sample/", new LocalizedText(info))); } }
public bool IsContain(TranslationInfo translationInfo) { return(this._translationInfoSet.Translations.Any(t => t.GUID == translationInfo.GUID)); }
/// <summary> /// Peridically checks the system state. /// </summary> private void OnCheckSystemStatus(object state) { #if CONDITION_SAMPLES lock (Lock) { try { // create the dialog. if (m_dialog == null) { m_dialog = new DialogConditionState(null); CreateNode( SystemContext, ExpandedNodeId.ToNodeId(ObjectIds.Data_Conditions, SystemContext.NamespaceUris), ReferenceTypeIds.HasComponent, new QualifiedName("ResetSystemDialog", m_namespaceIndex), m_dialog); m_dialog.OnAfterResponse = OnDialogComplete; } StatusCode systemStatus = m_system.SystemStatus; m_systemStatusCondition.UpdateStatus(systemStatus); // cycle through different status codes in order to simulate a real system. if (StatusCode.IsGood(systemStatus)) { m_systemStatusCondition.UpdateSeverity((ushort)EventSeverity.Low); m_system.SystemStatus = StatusCodes.Uncertain; } else if (StatusCode.IsUncertain(systemStatus)) { m_systemStatusCondition.UpdateSeverity((ushort)EventSeverity.Medium); m_system.SystemStatus = StatusCodes.Bad; } else { m_systemStatusCondition.UpdateSeverity((ushort)EventSeverity.High); m_system.SystemStatus = StatusCodes.Good; } // request a reset if status is bad. if (StatusCode.IsBad(systemStatus)) { m_dialog.RequestResponse( SystemContext, "Reset the test system?", (uint)(int)(DialogConditionChoice.Ok | DialogConditionChoice.Cancel), (ushort)EventSeverity.MediumHigh); } // report the event. TranslationInfo info = new TranslationInfo( "TestSystemStatusChange", "en-US", "The TestSystem status is now {0}.", systemStatus); m_systemStatusCondition.ReportConditionChange( SystemContext, null, new LocalizedText(info), false); } catch (Exception e) { Utils.Trace(e, "Unexpected error monitoring system status."); } } #endif }
/// <summary> /// Validates the password for a username token. /// </summary> private void VerifyPassword(string userName, string password) { if (String.IsNullOrEmpty(password)) { // construct translation object with default text. TranslationInfo info = new TranslationInfo( "InvalidPassword", "en-US", "Specified password is not valid for user '{0}'.", userName); // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( StatusCodes.BadIdentityTokenRejected, "InvalidPassword", "http://opcfoundation.org/UA/Sample/", new LocalizedText(info))); } }
/// <summary> /// Initializes a session audit event. /// </summary> private void InitializeSessionAuditEvent(ServerSystemContext systemContext, AuditEventState e, TranslationInfo message) { e.Initialize( systemContext, null, EventSeverity.MediumLow, new LocalizedText(message), true, DateTime.UtcNow); e.SetChildValue(systemContext, BrowseNames.SourceNode, m_sessionId, false); e.SetChildValue(systemContext, BrowseNames.SourceName, m_sessionName, false); e.SetChildValue(systemContext, BrowseNames.SessionId, m_sessionId, false); e.SetChildValue(systemContext, BrowseNames.ServerId, m_server.ServerUris.GetString(0), false); e.SetChildValue(systemContext, BrowseNames.ClientUserId, m_identity.DisplayName, false); e.SetChildValue(systemContext, BrowseNames.ClientAuditEntryId, systemContext.OperationContext.AuditEntryId, false); }
/// <summary> /// Reports an audit create session event. /// </summary> private void ReportAuditCreateSessionEvent(ServerSystemContext context) { // raise an audit event. AuditCreateSessionEventState e = new AuditCreateSessionEventState(null); TranslationInfo message = new TranslationInfo( "AuditCreateSessionEvent", "en-US", "Session {0} created.", m_sessionName); InitializeSessionAuditEvent(context, e, message); e.SetChildValue(context, BrowseNames.ClientCertificate, m_securityDiagnostics.ClientCertificate, false); e.SetChildValue(context, BrowseNames.SecureChannelId, m_secureChannelId, false); m_server.ReportEvent(context, e); }
static IEnumerable <SkuView> GenerateAllSkuViews(string lang) { using (DatabaseContext context = Util.CreateContext()) { var allAccounts = context.Database.SqlQuery <Account>(@"SELECT * FROM Accounts").ToList(); var allSkus = context.Database.SqlQuery <Sku>(@"SELECT * FROM Skus").ToList(); var allManufacturers = context.Database.SqlQuery <Manufacturer>(@"SELECT * FROM Manufacturers").ToList(); var allProducts = context.Database.SqlQuery <Product>(@"SELECT * FROM Products").ToList(); var allCategories = context.Database.SqlQuery <Category>(@"SELECT * FROM Categories").ToList(); var allProductCategories = context.Database.SqlQuery <ProductCategory>(@"SELECT * FROM ProductCategories").ToList(); var allOrders = context.Database.SqlQuery <Order>(@"SELECT * FROM Orders").ToList(); var allTrades = context.Database.SqlQuery <Trade>(@"SELECT * FROM Trades").ToList(); var allViewCounts = context.ViewCounts.AsNoTracking().ToList(); var baseUrl = WebConfigurationManager.AppSettings["BaseUrl"]; var webUrl = WebConfigurationManager.AppSettings["WebUrl"]; var skuViews = allSkus.ConvertAll(sku => { var product = allProducts.Find(p => p.Guid == sku.ProductGuid); var manufacturer = allManufacturers.Find(m => m.Guid == product.ManufacturerGuid); var productCategory = allProductCategories.Find(pc => pc.ProductGuid == sku.ProductGuid); var category = allCategories.Find(c => c.Guid == productCategory.CategoryGuid); var viewCount = allViewCounts.Find(c => c.Guid == sku.Guid); var skuView = new SkuView { CategoryGuid = category.Guid, CategoryName = TranslationInfo.ExtractTranslation(category.NameTranslations, lang), ProductGuid = product.Guid, ProductName = TranslationInfo.ExtractTranslation(product.NameTranslations, lang), ProductDescription = TranslationInfo.ExtractTranslation(product.DescriptionTranslations, lang), ManufacturerGuid = manufacturer.Guid, ManufacturerName = TranslationInfo.ExtractTranslation(manufacturer.NameTranslations, lang), Guid = sku.Guid, SkuName = TranslationInfo.ExtractTranslation(sku.NameTranslations, lang), ImageSrc = String.Format("{0}/v1/productimages/{1}?lang={2}", baseUrl, product.Guid, lang), Url = String.Format("{0}/{1}/market/{2}", webUrl, lang, sku.Guid), ManufacturerLink = product.ManufacturerLink, ViewCount = viewCount == null ? 0 : viewCount.Count }; string[] fullNameParts = skuView.SkuName == "null" ? new string[] { skuView.ManufacturerName, skuView.ProductName } : new string[] { skuView.ManufacturerName, skuView.ProductName, skuView.SkuName }; skuView.FullName = String.Join(" ", fullNameParts); Func <string, string[]> getValues = (nameTranslations) => { var translations = JsonConvert.DeserializeObject <TranslationInfo[]>(nameTranslations); return((from t in translations select t.Text == "null" ? "" : t.Text).ToArray()); }; List <string> keywordParts = new List <string>(); keywordParts.AddRange(getValues(category.NameTranslations)); keywordParts.AddRange(getValues(manufacturer.NameTranslations)); keywordParts.AddRange(getValues(product.NameTranslations)); keywordParts.AddRange(getValues(sku.NameTranslations)); skuView.Keywords = String.Join(" ", keywordParts.Distinct()); ////build price low only for active orders var results = (from o in allOrders where o.SkuGuid == sku.Guid && !o.IsCancelled && o.Quantity > 0 && o.ValidFrom <DateTime.UtcNow && o.ValidTo> DateTime.UtcNow select o).ToList(); skuView.OrdersCount = results.Count; //only summarise sell order pricing var sellOrders = results.Where(o => o.Type == "Sell").ToList(); if (sellOrders.Count > 0) { var cheapest = sellOrders.OrderBy(o => o.Price).First(); skuView.PriceLow = cheapest.Price; skuView.IsExclusive = cheapest.IsExclusive; skuView.Currency = cheapest.Currency; var latest = (from order in results orderby order.LastModified descending select order).First(); skuView.LastModified = latest.LastModified; } skuView.SoldCount = (from t in allTrades where t.SkuGuid == sku.Guid select t.Quantity).Sum(); return(skuView); }); return(skuViews); } }
/* * /// <summary> * /// Tworzy instancję obiektu * /// </summary> * public TranslationState() * { * } * * Przykłady użycia * * implement INotifyPropertyChanged * implement INotifyPropertyChanged_Passive * implement ToString ##Principles## ##PhpVersion## * implement ToString Principles=##Principles##, PhpVersion=##PhpVersion## * implement equals Principles, PhpVersion * implement equals * * implement equals *, ~exclude1, ~exclude2 */ #region Constructors /// <summary> /// Tworzy instancję obiektu /// <param name="principles"></param> /// </summary> public TranslationState(TranslationInfo principles) { _principles = principles; }
private ServiceResult AddApplication(ISystemContext context, MethodState method, IList <object> inputArguments, IList <object> outputArguments) { if (inputArguments.Count != 1) { return(StatusCodes.BadArgumentsMissing); } // check the data type of the input arguments. string value = inputArguments[0] as string; if (value == null) { return(StatusCodes.BadTypeMismatch); } if (_applications == null) { _applications = new List <string>(); } _applications.Add(value); if (_processor == null) { _processor = new Processor(); _processor.Name = "Turbo"; _processor.MinSpeed = 0; _processor.MaxSpeed = 0; } _processor.MinSpeed = 1; _processor.MaxSpeed += 1; //Could not encode outgoing outputArguments[0] = _applications.ToArray(); outputArguments[1] = _processor; //Report TranslationInfo info = new TranslationInfo( "AddApplication", "en-US", "The Confirm method was called."); AuditUpdateMethodEventState auditUpdateMethodEventState = new AuditUpdateMethodEventState(method); auditUpdateMethodEventState.Initialize( context, method, EventSeverity.Low, new LocalizedText(info), ServiceResult.IsGood(StatusCodes.Good), DateTime.UtcNow); auditUpdateMethodEventState.SourceName.Value = "Attribute/Call"; auditUpdateMethodEventState.MethodId = new PropertyState <NodeId>(method) { Value = method.NodeId }; auditUpdateMethodEventState.InputArguments = new PropertyState <object[]>(method) { Value = new object[] { inputArguments } }; auditUpdateMethodEventState.SetChildValue(context, BrowseNames.InputArguments, inputArguments.ToArray(), true); bool valid = auditUpdateMethodEventState.Validate(context); if (valid) { ApplicationNodeManager.Server.ReportEvent(auditUpdateMethodEventState); } return(ServiceResult.Good); }
private static TranslationInfo TranslateCSharpShaderLanguage2GLSL(string fullname) { TranslationInfo translationInfo = new TranslationInfo() { fullname = fullname, }; CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider(); CompilerParameters objCompilerParameters = new CompilerParameters(); objCompilerParameters.ReferencedAssemblies.Add("CSharpShaderLanguage.dll"); objCompilerParameters.GenerateExecutable = false; objCompilerParameters.GenerateInMemory = true; objCompilerParameters.IncludeDebugInformation = true; CompilerResults cr = objCSharpCodePrivoder.CompileAssemblyFromFile( objCompilerParameters, fullname); if (cr.Errors.HasErrors) { translationInfo.errors = cr.Errors; } else { //List<SemanticShader> semanticShaderList = new List<SemanticShader>(); //Assembly assembly = cr.CompiledAssembly; //Type[] types = assembly.GetTypes(); //foreach (var type in types) //{ // if (type.IsSubclassOf(typeof(CSShaderCode))) // { // CSShaderCode shaderCode = Activator.CreateInstance(type) as CSShaderCode; // SemanticShader semanticShader = shaderCode.Dump(fullname); // semanticShaderList.Add(semanticShader); // } //} //foreach (var item in semanticShaderList) //{ // SemanticShaderInfo info = new SemanticShaderInfo(); // info.codeUpdated = item.Dump2File(); // info.shader = item; // translationInfo.semanticShaderList.Add(info); //} // 下面是Linq的写法。 var result = from semanticShader in (from type in cr.CompiledAssembly.GetTypes() where type.IsSubclassOf(typeof(CSShaderCode)) select (Activator.CreateInstance(type) as CSShaderCode).Dump(fullname)) select new SemanticShaderInfo() { codeUpdated = semanticShader.Dump2File(), shader = semanticShader }; translationInfo.semanticShaderList = result.ToList(); } return translationInfo; }
/// <summary> /// Validates a SAML WSS user token. /// </summary> private SecurityToken ParseAndVerifySamlToken(byte[] tokenData) { XmlDocument document = new XmlDocument(); XmlNodeReader reader = null; try { string text = new UTF8Encoding().GetString(tokenData); document.InnerXml = text.Trim(); if (document.DocumentElement.NamespaceURI != "urn:oasis:names:tc:SAML:1.0:assertion") { throw new ServiceResultException(StatusCodes.BadNotSupported); } reader = new XmlNodeReader(document.DocumentElement); SecurityToken samlToken = new SamlSerializer().ReadToken( reader, m_tokenSerializer, m_tokenResolver); return samlToken; } catch (Exception e) { // construct translation object with default text. TranslationInfo info = new TranslationInfo( "InvalidSamlToken", "en-US", "'{0}' is not a valid SAML token.", document.DocumentElement.LocalName); // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( e, StatusCodes.BadIdentityTokenRejected, "InvalidSamlToken", "http://opcfoundation.org/UA/Sample/", new LocalizedText(info))); } finally { if (reader != null) { reader.Close(); } } }
// Internal Methods internal static Translator PrepareTranslator() { if (_translator != null) { return(_translator); } var csProject = LangPhpTestCsProj; using (var comp = new Cs2PhpCompiler { VerboseToConsole = true, ThrowExceptions = true }) { Console.WriteLine("Try to load " + csProject); #if DEBUG comp.LoadProject(csProject, "DEBUG"); #else comp.LoadProject(csProject, "RELEASE"); #endif /* * linked with C:\programs\_CS2PHP\PUBLIC\Lang.Php.Compiler\bin\Debug\Lang.Php.Compiler.dll * linked with C:\programs\_CS2PHP\PUBLIC\Lang.Php.Framework\bin\Debug\Lang.Php.Framework.dll * linked with C:\programs\_CS2PHP\PUBLIC\Lang.Php.Test\bin\Debug\Lang.Php.dll */ Console.WriteLine("Preparing before compilation"); string[] removeL = "Lang.Php.Compiler,Lang.Php.Framework,Lang.Php".Split(','); #region Remove Lang.Php reference { foreach (var r in removeL) { // ... will be replaced by reference to dll from compiler base dir // I know - compilation libraries should be loaded into separate application domain var remove = comp.CSharpProject.MetadataReferences.FirstOrDefault(i => i.Display.EndsWith(r + ".dll")); if (remove != null) { comp.RemoveMetadataReferences(remove); } } } #endregion string[] filenames; #region We have to remove and add again references - strange { // in other cases some referenced libraries are ignored var refToRemove = comp.CSharpProject.MetadataReferences.OfType <MetadataFileReference>().ToList(); foreach (var i in refToRemove) { comp.RemoveMetadataReferences(i); } var ref1 = refToRemove.Select(i => i.FilePath).ToList(); // foreach (var r in removeL) // ref1.Add(Path.Combine(Directory.GetCurrentDirectory(), r + ".dll")); ref1.Add(typeof(DirectCallAttribute).Assembly.Location); ref1.Add(typeof(EmitContext).Assembly.Location); ref1.Add(typeof(Extension).Assembly.Location); filenames = ref1.Distinct().ToArray(); } #endregion #region Translation assemblies { comp.TranslationAssemblies.Add(typeof(Extension).Assembly); comp.TranslationAssemblies.Add(typeof(Translator).Assembly); } #endregion foreach (var fileName in filenames) { var g = new MetadataFileReference(fileName, MetadataReferenceProperties.Assembly); comp.AddMetadataReferences(g); Console.WriteLine(" Add reference {0}", g.Display); } // using (var sandbox = new AssemblySandbox()) // { // // // Console.WriteLine("Start compile"); // var result = comp.CompileCSharpProject(sandbox, comp.DllFileName); // if (!result.Success) // { // foreach (var i in result.Diagnostics) // Console.WriteLine(i); // } // Assert.True(result.Success, "Compilation failed"); // } TranslationInfo translationInfo = comp.ParseCsSource(); translationInfo.CurrentAssembly = comp.CompiledAssembly; var assemblyTi = translationInfo.GetOrMakeTranslationInfo(comp.CompiledAssembly); var ecBaseDir = Path.Combine(Directory.GetCurrentDirectory(), assemblyTi.RootPath.Replace("/", "\\")); Console.WriteLine("Output root {0}", ecBaseDir); var translationState = new TranslationState(translationInfo); _translator = new Translator(translationState); _translator.Translate(comp.Sandbox); return(_translator); } }
/// <summary> /// 文本处理 /// </summary> private static void ProcessInfos() { s_DicUniqueChars = new Dictionary <int, string>(); s_DicUniqueASCII = new Dictionary <int, string>(); int nextAddr = 0; for (int i = 0; i < s_TranslationInfos.Count; ++i) { TranslationInfo info = s_TranslationInfos[i]; if (nextAddr == 0) { nextAddr = info.addr; } info.addr = nextAddr; for (int j = 0; j < info.textBlocks.Count; ++j) { TextBlockInfo ti = info.textBlocks[j]; // 如果bankNo为0,说明使用了默认bank。一般来说这是有问题的!不过也不排除某种极端情况。安全起见给出个警告吧! if (ti.bankNo > 0) { if (!s_DicUniqueChars.ContainsKey(ti.bankNo)) { s_DicUniqueChars.Add(ti.bankNo, string.Empty); } if (!s_DicUniqueASCII.ContainsKey(ti.bankNo)) { s_DicUniqueASCII.Add(ti.bankNo, string.Empty); } // 首先处理fullDigitalMode if (ti.isFullDigitalMode) { s_DicUniqueASCII[ti.bankNo] = "0123456789"; } s_DicUniqueChars[ti.bankNo] = GetUniqueChars(s_DicUniqueChars[ti.bankNo] + ti.str); s_DicUniqueASCII[ti.bankNo] = GetUniqueASCII(s_DicUniqueASCII[ti.bankNo] + ti.str); if (s_DicUniqueChars[ti.bankNo].Length > MAX_UNIQUE_CHAR_COUNT) { Console.WriteLine("FATAL ERROR! Too many characters in bank " + ti.bankNo); Console.WriteLine(s_DicUniqueChars[ti.bankNo]); } } else { Console.WriteLine("WARNING! bankNo == 0!"); } char[] chars = ti.str.ToArray(); int start = -1; for (int k = 0; k < chars.Length; ++k) { char c = chars[k]; switch (c) { case '[': { start = k; break; } case ']': { string control = ti.str.Substring(start, k - start + 1); start = -1; Byte v = 0xFF; if (s_Ctrl2Code.ContainsKey(control)) { v = s_Ctrl2Code[control]; } ti.data.Add(v); break; } case '<': { start = k; break; } case '>': { string value = ti.str.Substring(start + 1, k - start - 1); start = -1; Byte v = (Byte)int.Parse(value, System.Globalization.NumberStyles.AllowHexSpecifier); ti.data.Add(v); break; } case '{': { start = k; break; } case '}': { string value = ti.str.Substring(start + 1, k - start - 1); start = -1; Byte bankNo = (Byte)int.Parse(value, System.Globalization.NumberStyles.AllowHexSpecifier); ti.data.Add((Byte)(bankNo + 0x20)); break; } default: { if (start < 0) { if (c <= 0x7F) { if (c == ' ') { ti.data.Add(0xFE); } else { int offset = s_DicUniqueASCII[ti.bankNo].IndexOf(c); ti.data.Add((Byte)(offset + 0x80)); } } else { int offset = s_DicUniqueChars[ti.bankNo].IndexOf(c); ti.data.Add((Byte)(offset + 0x60)); } } break; } } } nextAddr += ti.data.Count; } s_TranslationInfos[i] = info; } }
public QuizWord(TranslationInfo translationInfo) { this.translationInfo = translationInfo; this.title = translationInfo.Translation; UpdateState(); }
/// <summary> /// Translates the text provided. /// </summary> protected virtual LocalizedText Translate(IList <string> preferredLocales, LocalizedText defaultText, TranslationInfo info) { // check for trivial case. if (info == null || String.IsNullOrEmpty(info.Text)) { return(defaultText); } // check for exact match. if (preferredLocales != null && preferredLocales.Count > 0) { if (defaultText != null && preferredLocales[0] == defaultText.Locale) { return(defaultText); } if (preferredLocales[0] == info.Locale) { return(new LocalizedText(info)); } } // use the text as the key. string key = info.Key; if (key == null) { key = info.Text; } // find the best translation. string translatedText = info.Text; CultureInfo culture = CultureInfo.InvariantCulture; lock (m_lock) { translatedText = FindBestTranslation(preferredLocales, key, out culture); // use the default if no translation available. if (translatedText == null) { return(defaultText); } // get a culture to use for formatting if (culture == null) { if (info.Args != null && info.Args.Length > 0 && !String.IsNullOrEmpty(info.Locale)) { try { culture = CultureInfo.GetCultureInfo(info.Locale); } catch { culture = CultureInfo.InvariantCulture; } } } } // format translated text. string formattedText = translatedText; if (info.Args != null && info.Args.Length > 0) { try { formattedText = String.Format(culture, translatedText, info.Args); } catch { formattedText = translatedText; } } // construct translated localized text. Opc.Ua.LocalizedText finalText = new LocalizedText(culture.Name, formattedText); finalText.TranslationInfo = info; return(finalText); }
public CompilationTestInfo(Cs2PyCompiler compiler, TranslationInfo info, Translator translator) { Compiler = compiler; Info = info; Translator = translator; }
public ChooseLanguage() { InitializeComponent(); var defaultLanguage = new Language(); DefaultTranslation = new TranslationInfo(defaultLanguage.General.CultureName, defaultLanguage.Name); var currentLanguage = Configuration.Settings.Language; if (currentLanguage == null) { CurrentTranslation = new TranslationInfo(CultureInfo.CurrentUICulture.Name, CultureInfo.CurrentUICulture.NativeName); } else { CurrentTranslation = new TranslationInfo(currentLanguage.General.CultureName, currentLanguage.Name); } var translations = new HashSet <TranslationInfo>(); translations.Add(DefaultTranslation); if (Directory.Exists(Path.Combine(Configuration.BaseDirectory, "Languages"))) { var versionInfo = Utilities.AssemblyVersion.Split('.'); var currentVersion = string.Format("{0}.{1}.{2}", versionInfo[0], versionInfo[1], versionInfo[2]); var document = new XmlDocument { XmlResolver = null }; foreach (var fileName in Directory.GetFiles(Path.Combine(Configuration.BaseDirectory, "Languages"), "*.xml")) { document.Load(fileName); try { var version = document.DocumentElement.SelectSingleNode("General/Version").InnerText.Trim(); if (version == currentVersion) { var cultureName = document.DocumentElement.SelectSingleNode("General/CultureName").InnerText.Trim(); var displayName = document.DocumentElement.Attributes["Name"].Value.Trim(); if (!string.IsNullOrEmpty(cultureName) && !string.IsNullOrEmpty(displayName)) { translations.Add(new TranslationInfo(cultureName, displayName)); } } } catch { } } } int index = -1; foreach (var translation in translations.OrderBy(ti => ti.DisplayName, StringComparer.CurrentCultureIgnoreCase).ThenBy(ti => ti.CultureName, StringComparer.Ordinal)) { int i = comboBoxLanguages.Items.Add(translation); if (translation.Equals(CurrentTranslation) || (index < 0 && translation.Equals(DefaultTranslation))) { index = i; } } comboBoxLanguages.SelectedIndex = index; Text = Configuration.Settings.Language.ChooseLanguage.Title; labelLanguage.Text = Configuration.Settings.Language.ChooseLanguage.Language; buttonOK.Text = Configuration.Settings.Language.General.Ok; buttonCancel.Text = Configuration.Settings.Language.General.Cancel; UiUtil.FixLargeFonts(this, buttonOK); }
static void Main(string[] args) { //CSharpShadingLanguage.NeverUsed.PrintVec234Components.PrintComponents(); //return; StringBuilder builder = new StringBuilder(); StringBuilder simpleBuilder = new StringBuilder(); string time = DateTime.Now.ToString("yyyyMMdd-HHmmss"); string logName = string.Format("CSSL2GLSLDump{0}.log", time); string simpleLogName = string.Format("CSSL2GLSLDump{0}.simple.log", time); string logFullname = Path.Combine(Environment.CurrentDirectory, logName); string simpleLogFullname = Path.Combine(Environment.CurrentDirectory, simpleLogName); try { string directoryName = string.Empty; if (args.Length > 0) { directoryName = args[0]; } else { directoryName = Environment.CurrentDirectory; } Console.WriteLine("Searching *.cssl.cs files..."); string[] files = System.IO.Directory.GetFiles(directoryName, "*.cssl.cs", System.IO.SearchOption.AllDirectories); List <TranslationInfo> translationInfoList = new List <TranslationInfo>(); foreach (var fullname in files) { Console.WriteLine("translating {0}", fullname); TranslationInfo translationInfo = TranslateCSharpShaderLanguage2GLSL(fullname); translationInfoList.Add(translationInfo); } builder.AppendFormat("Directory: {0}", directoryName); builder.AppendLine(); simpleBuilder.AppendFormat("Directory: {0}", directoryName); simpleBuilder.AppendLine(); var foundCSSLCount = (from item in translationInfoList select item.GetCompiledShaderCount()).Sum(); var updatedCSSLCount = (from item in translationInfoList select item.GetUpdatedShaderCount()).Sum(); builder.AppendFormat("Found {0} CSSL shaders, and {1} of them are dumped to GLSL as needed.", foundCSSLCount, updatedCSSLCount); simpleBuilder.AppendFormat("Found {0} CSSL shaders, and {1} of them are dumped to GLSL as needed.", foundCSSLCount, updatedCSSLCount); builder.AppendLine(); simpleBuilder.AppendLine(); { var list = from item in translationInfoList orderby item.GetUpdatedShaderCount() descending select item; foreach (var item in list) { item.Append(builder, 4); item.AppendSimple(simpleBuilder, 4); } } builder.AppendFormat("Translation all done!"); builder.AppendLine(); simpleBuilder.AppendFormat("Translation all done!"); simpleBuilder.AppendLine(); } catch (Exception e) { builder.AppendFormat("*********************Translation break off!*********************"); builder.AppendLine(); builder.AppendFormat("Exception for CSSL2GLSL:"); builder.AppendLine(); builder.AppendFormat(e.ToString()); builder.AppendLine(); simpleBuilder.AppendFormat("*********************Translation break off!*********************"); builder.AppendLine(); simpleBuilder.AppendFormat("Exception for CSSL2GLSL:"); builder.AppendLine(); simpleBuilder.AppendFormat(e.ToString()); builder.AppendLine(); } File.WriteAllText(logFullname, builder.ToString()); File.WriteAllText(simpleLogFullname, simpleBuilder.ToString()); Process.Start("explorer", simpleLogFullname); if (args.Length >= 2 && args[1] == "-open-folder") { Process.Start("explorer", "/select," + simpleLogFullname); } Console.WriteLine("done!"); }
private static TranslationInfo TranslateCSharpShaderLanguage2GLSL(string fullname) { TranslationInfo translationInfo = new TranslationInfo() { fullname = fullname, }; CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider(); CompilerParameters objCompilerParameters = new CompilerParameters(); objCompilerParameters.ReferencedAssemblies.Add( typeof(CSharpShadingLanguage.CSShaderCode).Assembly.Location); objCompilerParameters.GenerateExecutable = false; objCompilerParameters.GenerateInMemory = true; objCompilerParameters.IncludeDebugInformation = true; CompilerResults cr = objCSharpCodePrivoder.CompileAssemblyFromFile( objCompilerParameters, fullname); if (cr.Errors.HasErrors) { translationInfo.errors = cr.Errors; } else { //List<SemanticShader> semanticShaderList = new List<SemanticShader>(); //Assembly assembly = cr.CompiledAssembly; //Type[] types = assembly.GetTypes(); //foreach (var type in types) //{ // if (type.IsSubclassOf(typeof(CSShaderCode))) // { // CSShaderCode shaderCode = Activator.CreateInstance(type) as CSShaderCode; // SemanticShader semanticShader = shaderCode.Dump(fullname); // semanticShaderList.Add(semanticShader); // } //} //foreach (var item in semanticShaderList) //{ // SemanticShaderInfo info = new SemanticShaderInfo(); // info.codeUpdated = item.Dump2File(); // info.shader = item; // translationInfo.semanticShaderList.Add(info); //} // 下面是Linq的写法。 var result = from semanticShader in (from type in cr.CompiledAssembly.GetTypes() where type.IsSubclassOf(typeof(CSShaderCode)) select(Activator.CreateInstance(type) as CSShaderCode).GetSemanticShader(fullname)) select new SemanticShaderInfo() { codeUpdated = semanticShader.Dump2File(), shader = semanticShader }; translationInfo.semanticShaderList = result.ToList(); } return(translationInfo); }
private void Check_for_TetrisLinesMadeEvent(int oldScore, int newScore, BaseObjectState sourceNode) { //---------- determine whether actual lines were made and score increased ----------- if (!(newScore > oldScore) || sourceNode == null) { return; } // determine score inscrease: int pointsScored = newScore - oldScore; // ... and the nr of lines (slightly dirty implementation: TetrisGame knowledge assumed...) int nrOfLinesMade = 0; switch (pointsScored) { case 10: nrOfLinesMade = 1; break; case 30: nrOfLinesMade = 2; break; case 60: nrOfLinesMade = 3; break; case 100: nrOfLinesMade = 4; break; default: return; } //------------------------------ Create the event ----------------------------------- //TetrisLinesMadeEventState linesMadeEvent = new TetrisLinesMadeEventState(null); TetrisLinesMadeEventState linesMadeEvent = new TetrisLinesMadeEventState(null); // construct the message of the event (on of the event fields): TranslationInfo message = new TranslationInfo( "TetrisLinesMade", "en-US", "In the TetrisGame {0} lines where made for a total of {1} points", nrOfLinesMade, pointsScored); // initialize the event: linesMadeEvent.Initialize( SystemContext, sourceNode, EventSeverity.Low, new LocalizedText(message)); // set our two new fields: linesMadeEvent.SetChildValue(SystemContext, BrowseNames_TetrisEvents.NrOfLines, nrOfLinesMade, false); linesMadeEvent.SetChildValue(SystemContext, BrowseNames_TetrisEvents.PointsScored, pointsScored, false); //----------------------------- Report the event ------------------------------------ sourceNode.ReportEvent(SystemContext, linesMadeEvent); }
public IEnumerable <OrderView> Get(string accountGuid = "", string skuId = "", string orderId = "", string type = "", string query = "", string categories = "", string manufacturers = "", string lang = "en-US", bool showExpired = false, bool showSoldOut = false, bool showCancelled = false) { using (DatabaseContext context = Util.CreateContext()) { var activeAccounts = new AccountController().GetAccounts().ToList(); var relevantSkuViews = new SkuViewController().GetList(query, categories, manufacturers, skuId, true, lang).ToList(); var orders = (from o in context.Orders.AsNoTracking() select o).ToList(); //only show orders which match sku filters var relevantSkuGuids = relevantSkuViews.ConvertAll(s => s.Guid); orders = orders.Where(o => relevantSkuGuids.Contains(o.SkuGuid)).ToList(); //store filter if (!String.IsNullOrEmpty(accountGuid)) { orders = orders.Where(o => { return(o.CreatedByAccountGuid == new Guid(accountGuid)); }).ToList(); } if (!String.IsNullOrEmpty(type)) { orders = orders.Where(o => o.Type == type).ToList(); } if (!String.IsNullOrEmpty(skuId)) { orders = orders.Where(o => o.SkuGuid == new Guid(skuId)).ToList(); } if (!String.IsNullOrEmpty(orderId)) { orders = orders.Where(o => o.Guid == new Guid(orderId)).ToList(); } if (!showExpired) { orders = orders.Where(o => o.ValidTo > DateTime.UtcNow).ToList(); } if (!showSoldOut) { orders = (from order in orders where activeAccounts.Any(a => a.Guid == order.CreatedByAccountGuid) && order.Quantity > 0 select order).ToList(); } if (!showCancelled) { orders = (from order in orders where !order.IsCancelled select order).ToList(); } var webUrl = ConfigurationManager.AppSettings["WebUrl"]; var baseUrl = ConfigurationManager.AppSettings["BaseUrl"]; var marketLocations = new MarketLocationController().Get(lang).ToList(); var productConditions = new ProductConditionController().Get(lang).ToList(); var productColours = (from c in context.ProductColours.AsNoTracking() select c).ToList(); var orderViews = orders.ConvertAll(o => { var sku = relevantSkuViews.Where(s => s.Guid == o.SkuGuid).FirstOrDefault(); var account = activeAccounts.Where(a => a.Guid == o.CreatedByAccountGuid).FirstOrDefault(); var marketLocation = marketLocations.Where(l => l.Key == o.Location).FirstOrDefault(); var isActive = DateTime.UtcNow > o.ValidFrom && DateTime.UtcNow < o.ValidTo && o.Quantity > 0 && !o.IsCancelled; var status = o.IsCancelled ? "Cancelled" : o.Quantity == 0 ? "Sold out" : DateTime.UtcNow > o.ValidTo ? "Expired" : "Active"; var viewCount = (from c in context.ViewCounts where c.Guid == o.Guid select c).FirstOrDefault(); var productCondition = productConditions.Where(c => c.Key == o.ProductCondition).FirstOrDefault(); var productColour = (from c in productColours where c.Guid == o.ProductColourGuid select c).FirstOrDefault(); var imageGuids = JsonConvert.DeserializeObject <Guid[]>(o.ImageGuids).ToList(); var imageUrls = imageGuids.ConvertAll(guid => String.Format("{0}/v1/image/{1}", baseUrl, guid)); var orderView = new OrderView { Price = o.Price, Currency = o.Currency, Quantity = o.Quantity, QuantityInitial = o.QuantityInitial, MinimumOrder = o.MinimumOrder, IsExclusive = o.IsExclusive, Guid = o.Guid, SkuGuid = o.SkuGuid, CreatedByAccountGuid = o.CreatedByAccountGuid, AccountUserName = account.Username, AccountPhone = account.Phone, Location = marketLocation.Key, LocationName = marketLocation.Name, ProductColourGuid = o.ProductColourGuid, ProductColourName = TranslationInfo.ExtractTranslation(productColour.NameTranslations, lang), ProductColourValue = productColour.Value, ProductCondition = o.ProductCondition, ProductConditionName = productCondition.Name, Type = o.Type, Created = DateTime.SpecifyKind(o.Created, DateTimeKind.Utc), ValidFrom = DateTime.SpecifyKind(o.ValidFrom, DateTimeKind.Utc), ValidTo = DateTime.SpecifyKind(o.ValidTo, DateTimeKind.Utc), SkuName = sku.SkuName, SkuFullName = sku.FullName, CategoryGuid = sku.CategoryGuid, CategoryName = sku.CategoryName, ManufacturerGuid = sku.ManufacturerGuid, ManufacturerName = sku.ManufacturerName, ProductGuid = sku.ProductGuid, ProductName = sku.ProductName, LastModified = DateTime.SpecifyKind(o.LastModified, DateTimeKind.Utc), ImageSrc = sku.ImageSrc, Description = o.Description, IsActive = isActive, Status = status, Url = String.Format("{0}/{1}/order/{2}", webUrl, lang, o.Guid), ViewCount = viewCount != null ? viewCount.Count : 0, ImageUrls = imageUrls.ToArray() }; return(orderView); }); return(orderViews); } }
// Getters private BoardSpace GetSpaceAutoMoveTo() { TranslationInfo ti = BoardUtils.GetTranslationInfo(BoardRef, ColRow, MathUtils.GetSide(AutoMoveDir)); return(GetSpace(ti.to)); }
// translations info from http://tanzil.net public static void LoadTranslationInfos(Book book) { if (book != null) { book.TranslationInfos = new Dictionary<string, TranslationInfo>(); string filename = Globals.TRANSLATIONS_FOLDER + "/" + "Offline" + "/" + "metadata.txt"; if (File.Exists(filename)) { using (StreamReader reader = File.OpenText(filename)) { string line = reader.ReadLine(); // skip header row while ((line = reader.ReadLine()) != null) { string[] parts = line.Split('\t'); if (parts.Length >= 4) { TranslationInfo translation = new TranslationInfo(); translation.Url = "?transID=" + parts[0] + "&type=" + TranslationInfo.FileType; translation.Flag = parts[1]; translation.Language = parts[2]; translation.Translator = parts[3]; translation.Name = parts[2] + " - " + parts[3]; book.TranslationInfos.Add(parts[0], translation); } } } } } }
/// <summary> /// Adds the translations to the resource manager. /// </summary> public void Add(uint statusCode, string locale, string text) { lock (m_lock) { string key = statusCode.ToString(); Add(key, locale, text); if (m_statusCodeMapping == null) { m_statusCodeMapping = new Dictionary<uint,TranslationInfo>(); } if (String.IsNullOrEmpty(locale) || locale == "en-US") { m_statusCodeMapping[statusCode] = new TranslationInfo(key, locale, text); } } }
public void DoImport(TranslationInfo translationInfo) { this._translationIOUnit.DoImport(translationInfo); }
private ServiceResult OnStart(ISystemContext context, MethodState method, IList <object> inputArguments, IList <object> outputArguments) { // all arguments must be provided. if (inputArguments.Count < 2) { return(StatusCodes.BadArgumentsMissing); } // check the data type of the input arguments. uint?initialState = inputArguments[0] as uint?; uint?finalState = inputArguments[1] as uint?; if (initialState == null || finalState == null) { return(StatusCodes.BadTypeMismatch); } lock (_processLock) { // check if the process is running. if (_processTimer != null) { _processTimer.Dispose(); _processTimer = null; } // start the process. _state = initialState.Value; _finalState = finalState.Value; _processTimer = new Timer(OnUpdateProcess, null, 1000, 1000); // the calling function sets default values for all output arguments. // only need to update them here. outputArguments[0] = _state; outputArguments[1] = _finalState; } // signal update to state node. lock (ApplicationNodeManager.Lock) { _stateNode.Value = _state; _stateNode.ClearChangeMasks(ApplicationNodeManager.SystemContext, true); } TranslationInfo info = new TranslationInfo( "OnStart", "en-US", "The Confirm method was called."); AuditUpdateMethodEventState auditUpdateMethodEventState = new AuditUpdateMethodEventState(method); auditUpdateMethodEventState.Initialize( context, method, EventSeverity.Low, new LocalizedText(info), ServiceResult.IsGood(StatusCodes.Good), DateTime.UtcNow); auditUpdateMethodEventState.SourceName.Value = "Attribute/Call"; auditUpdateMethodEventState.MethodId = new PropertyState <NodeId>(method) { Value = method.NodeId }; auditUpdateMethodEventState.InputArguments = new PropertyState <object[]>(method) { Value = new object[] { inputArguments } }; auditUpdateMethodEventState.SetChildValue(context, BrowseNames.InputArguments, inputArguments.ToArray(), true); bool valid = auditUpdateMethodEventState.Validate(context); if (valid) { ApplicationNodeManager.Server.ReportEvent(auditUpdateMethodEventState); } return(ServiceResult.Good); }
/// <summary> /// Adds the translations to the resource manager. /// </summary> public void Add(XmlQualifiedName symbolicId, string locale, string text) { lock (m_lock) { if (symbolicId != null) { string key = symbolicId.ToString(); Add(key, locale, text); if (m_symbolicIdMapping == null) { m_symbolicIdMapping = new Dictionary<XmlQualifiedName, TranslationInfo>(); } if (String.IsNullOrEmpty(locale) || locale == "en-US") { m_symbolicIdMapping[symbolicId] = new TranslationInfo(key, locale, text); } } } }
/// <summary> /// Constructs an event and reports to the server. /// </summary> private void RaiseAuditUpdateMethodEvent( ISystemContext context, MethodState method, bool status, IList <object> inputArguments) { BaseObjectState parent = method.Parent as BaseObjectState; #region Task #D6 - Add Support for Notifiers // check if it is even necessary to produce an event. if (parent != null && !parent.AreEventsMonitored) { return; } #endregion // construct translation object with default text. TranslationInfo info = new TranslationInfo( "AuditUpdateMethodEvent", "en-US", "A method was called."); // intialize the event. AuditUpdateMethodEventState e = new AuditUpdateMethodEventState(null); e.Initialize( SystemContext, null, EventSeverity.Medium, new LocalizedText(info), true, DateTime.UtcNow); // fill in additional fields. e.SetChildValue(SystemContext, Opc.Ua.BrowseNames.SourceNode, method.Parent.NodeId, false); e.SetChildValue(SystemContext, Opc.Ua.BrowseNames.SourceName, "Attribute/Call", false); e.SetChildValue(SystemContext, Opc.Ua.BrowseNames.ServerId, context.ServerUris.GetString(0), false); e.SetChildValue(SystemContext, Opc.Ua.BrowseNames.ClientAuditEntryId, context.AuditEntryId, false); if (context.UserIdentity != null) { e.SetChildValue(SystemContext, Opc.Ua.BrowseNames.ClientUserId, context.UserIdentity.DisplayName, false); } e.SetChildValue(SystemContext, Opc.Ua.BrowseNames.MethodId, method.NodeId, false); // need to change data type. Variant[] values = new Variant[inputArguments.Count]; for (int ii = 0; ii < values.Length; ii++) { values[ii] = new Variant(inputArguments[ii]); } e.SetChildValue(SystemContext, Opc.Ua.BrowseNames.InputArguments, values, false); #region Task #D6 - Add Support for Notifiers // report the event to the parent. let it propagate up the tree. if (parent != null && parent.AreEventsMonitored) { parent.ReportEvent(context, e); return; } #endregion // report the event to the server object. Server.ReportEvent(e); }
/// <summary> /// Called when a client tries to change its user identity. /// </summary> private void SessionManager_ImpersonateUser(Session session, ImpersonateEventArgs args) { if (session == null) { throw new ArgumentNullException(nameof(session)); } if (args.NewIdentity is AnonymousIdentityToken guest) { args.Identity = new UserIdentity(guest); Utils.Trace("Guest access accepted: {0}", args.Identity.DisplayName); return; } // check for a user name token. if (args.NewIdentity is UserNameIdentityToken userNameToken) { var admin = VerifyPassword(userNameToken.UserName, userNameToken.DecryptedPassword); args.Identity = new UserIdentity(userNameToken); if (admin) { args.Identity = new SystemConfigurationIdentity(args.Identity); } Utils.Trace("UserName Token accepted: {0}", args.Identity.DisplayName); return; } // check for x509 user token. if (args.NewIdentity is X509IdentityToken x509Token) { var admin = VerifyCertificate(x509Token.Certificate); args.Identity = new UserIdentity(x509Token); if (admin) { args.Identity = new SystemConfigurationIdentity(args.Identity); } Utils.Trace("X509 Token accepted: {0}", args.Identity.DisplayName); return; } // check for x509 user token. if (args.NewIdentity is IssuedIdentityToken wssToken) { var admin = VerifyToken(wssToken); args.Identity = new UserIdentity(wssToken); if (admin) { args.Identity = new SystemConfigurationIdentity(args.Identity); } Utils.Trace("Issued Token accepted: {0}", args.Identity.DisplayName); return; } // construct translation object with default text. var info = new TranslationInfo("InvalidToken", "en-US", "Specified token is not valid."); // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( StatusCodes.BadIdentityTokenRejected, "Bad token", kServerNamespaceUri, new LocalizedText(info))); }
public TranslationResult translate(TranslationInfo info) { OperationContext context = OperationContext.Current; MessageProperties messageProperties = context.IncomingMessageProperties; RemoteEndpointMessageProperty enpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; GraphContainer graphContainer = new GraphContainer(); if (info.InputFormat != 0 && info.OutputFormat != 0 && info.InputFormat != info.OutputFormat) { //(@"C:\Program Files (x86)\DesignBuilder"); string appPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\DataExchangeSolution\"; if (!Directory.Exists(appPath)) { Directory.CreateDirectory(appPath); } string guid = Guid.NewGuid().ToString(); List<string> files = new List<string>(); List<DataFormat> formats = new List<DataFormat>(); List<DataFormat> path; byte[] outFile = new byte[0]; bool result = false; path = graphContainer.FindPath(info.InputFormat, info.OutputFormat); if (path.Count() > 0) { files.Add(appPath + guid + getExtension(info.InputFormat)); formats.Add(info.InputFormat); File.WriteAllBytes(files.ElementAt(0), info.Data); for (var i = 0; i < path.Count(); i++) { files.Add(appPath + guid + getExtension(path[i])); formats.Add(path[i]); } Program.logger.log("Starting conversion from " + formats.First() + " to " + formats.Last() + " requested by: " + enpointProperty.Address); for (var i = 0; i < path.Count(); i++) { try { result = convert(formats.ElementAt(i), formats.ElementAt(i + 1), files.ElementAt(i), files.ElementAt(i + 1)); } catch (Exception e) { Program.logger.log(e.Message, Logger.LogType.ERROR); } if (!result) { break; } } if (result) { Program.logger.log("Conversion requested by: " + enpointProperty.Address + " succeeded"); outFile = File.ReadAllBytes(files.Last()); } else { Program.logger.log("Conversion requested by: " + enpointProperty.Address + " failed",Logger.LogType.ERROR); } for (var i = 0; i < files.Count(); i++) { if (File.Exists(files.ElementAt(i))) { File.Delete(files.ElementAt(i)); } } if (result) { return new TranslationResult { Data = outFile, Succeeded = true }; } } } return new TranslationResult(); }
/// <summary> /// Refreshes the conditions. /// </summary> public void ConditionRefresh() { ServerSystemContext systemContext = m_server.DefaultSystemContext.Copy(m_session); List<IEventMonitoredItem> monitoredItems = new List<IEventMonitoredItem>(); lock (m_lock) { // generate start event. RefreshStartEventState e = new RefreshStartEventState(null); TranslationInfo message = new TranslationInfo( "RefreshStartEvent", "en-US", "Condition refresh started for subscription {0}.", m_id); e.Initialize( systemContext, null, EventSeverity.Low, new LocalizedText(message)); e.SetChildValue(systemContext, BrowseNames.SourceNode, m_diagnosticsId, false); e.SetChildValue(systemContext, BrowseNames.SourceName, Utils.Format("Subscription/{0}", m_id), false); e.SetChildValue(systemContext, BrowseNames.ReceiveTime, DateTime.UtcNow, false); // build list of items to refresh. foreach (LinkedListNode<IMonitoredItem> monitoredItem in m_monitoredItems.Values) { MonitoredItem eventMonitoredItem = monitoredItem.Value as MonitoredItem; if (eventMonitoredItem.EventFilter != null) { // queue start refresh event. eventMonitoredItem.QueueEvent(e, true); // add to list that gets reported to the NodeManagers. monitoredItems.Add(eventMonitoredItem); } } // nothing to do if no event subscriptions. if (monitoredItems.Count == 0) { return; } } // tell the NodeManagers to report the current state of the conditions. try { m_refreshInProgress = true; OperationContext operationContext = new OperationContext(m_session, DiagnosticsMasks.None); m_server.NodeManager.ConditionRefresh(operationContext, monitoredItems); } finally { m_refreshInProgress = false; } lock (m_lock) { // generate start event. RefreshEndEventState e = new RefreshEndEventState(null); TranslationInfo message = new TranslationInfo( "RefreshEndEvent", "en-US", "Condition refresh completed for subscription {0}.", m_id); e.Initialize( systemContext, null, EventSeverity.Low, new LocalizedText(message)); e.SetChildValue(systemContext, BrowseNames.SourceNode, m_diagnosticsId, false); e.SetChildValue(systemContext, BrowseNames.SourceName, Utils.Format("Subscription/{0}", m_id), false); e.SetChildValue(systemContext, BrowseNames.ReceiveTime, DateTime.UtcNow, false); // send refresh end event. for (int ii = 0; ii < monitoredItems.Count; ii++) { MonitoredItem monitoredItem = monitoredItems[ii] as MonitoredItem; if (monitoredItem.EventFilter != null) { monitoredItem.QueueEvent(e, true); } } // TraceState("CONDITION REFRESH"); } }
private async Task _InstallAsync(PatchCache patchCache, PluginInfo pluginInfo, CancellationToken ct = default) { App.Current.Logger.Info(nameof(EnglishPatchPhase), "Downloading english translation information"); var translation = await TranslationInfo.FetchEnglishAsync(ct); App.Current.Logger.Info(nameof(EnglishPatchPhase), "Getting data from patch cache"); var cacheData = await patchCache.SelectAllAsync(); string CreateRelativePath(string path) { var root = new Uri(_InstallConfiguration.PSO2BinDirectory); var relative = root.MakeRelativeUri(new Uri(path)); return(relative.OriginalString); } bool Verify(string path, string hash) { var relative = CreateRelativePath(path); var info = new FileInfo(path); if (info.Exists == false) { return(false); } if (cacheData.ContainsKey(relative) == false) { return(false); } var data = cacheData[relative]; if (data.Hash != hash) { return(false); } if (data.LastWriteTime != info.LastWriteTimeUtc.ToFileTimeUtc()) { return(false); } return(true); } using (var client = new ArksLayerHttpClient()) { async Task VerifyAndDownlodRar(string path, string downloadHash, Uri downloadPath) { if (Verify(path, downloadHash) == false) { App.Current.Logger.Info(nameof(EnglishPatchPhase), $"Downloading \"{Path.GetFileName(downloadPath.LocalPath)}\""); using (var response = await client.GetAsync(downloadPath)) using (var stream = await response.Content.ReadAsStreamAsync()) using (var archive = RarArchive.Open(stream)) { foreach (var file in archive.Entries.Where(e => !e.IsDirectory)) { var filePath = Path.Combine(_InstallConfiguration.ArksLayer.PatchesDirectory, file.Key); using (var fs = File.Create(filePath, 4096, FileOptions.Asynchronous)) await file.OpenEntryStream().CopyToAsync(fs); await patchCache.InsertUnderTransactionAsync(new[] { new PatchCacheEntry() { Name = CreateRelativePath(filePath), Hash = downloadHash, LastWriteTime = new FileInfo(filePath).LastWriteTimeUtc.ToFileTimeUtc() } }); } } } } await VerifyAndDownlodRar(_InstallConfiguration.ArksLayer.EnglishBlockPatch, translation.BlockMD5, new Uri(translation.BlockPatch)); await VerifyAndDownlodRar(_InstallConfiguration.ArksLayer.EnglishItemPatch, translation.ItemMD5, new Uri(translation.ItemPatch)); await VerifyAndDownlodRar(_InstallConfiguration.ArksLayer.EnglishTextPatch, translation.TextMD5, new Uri(translation.TextPatch)); await VerifyAndDownlodRar(_InstallConfiguration.ArksLayer.EnglishTitlePatch, translation.TitleMD5, new Uri(translation.TitlePatch)); } App.Current.Logger.Info(nameof(EnglishPatchPhase), "Validating plugin dlls"); await pluginInfo.PSO2BlockRenameDll.ValidateFileAsync(_InstallConfiguration.ArksLayer.PluginPSO2BlockRenameDll, ct); await pluginInfo.PSO2ItemTranslatorDll.ValidateFileAsync(_InstallConfiguration.ArksLayer.PluginPSO2ItemTranslatorDll, ct); await pluginInfo.PSO2TitleTranslatorDll.ValidateFileAsync(_InstallConfiguration.ArksLayer.PluginPSO2TitleTranslatorDll, ct); await pluginInfo.PSO2RAISERSystemDll.ValidateFileAsync(_InstallConfiguration.ArksLayer.PluginPSO2RAISERSystemDll, ct); }
/* /// <summary> /// Tworzy instancję obiektu /// </summary> public TranslationState() { } Przykłady użycia implement INotifyPropertyChanged implement INotifyPropertyChanged_Passive implement ToString ##Principles## ##PhpVersion## implement ToString Principles=##Principles##, PhpVersion=##PhpVersion## implement equals Principles, PhpVersion implement equals * implement equals *, ~exclude1, ~exclude2 */ #region Constructors /// <summary> /// Tworzy instancję obiektu /// <param name="principles"></param> /// </summary> public TranslationState(TranslationInfo principles) { _principles = principles; }
/// <summary> /// Translates the text provided. /// </summary> protected virtual LocalizedText Translate(IList<string> preferredLocales, LocalizedText defaultText, TranslationInfo info) { // check for trivial case. if (info == null || String.IsNullOrEmpty(info.Text)) { return defaultText; } // check for exact match. if (preferredLocales != null && preferredLocales.Count > 0) { if (defaultText != null && preferredLocales[0] == defaultText.Locale) { return defaultText; } if (preferredLocales[0] == info.Locale) { return new LocalizedText(info); } } // use the text as the key. string key = info.Key; if (key == null) { key = info.Text; } // find the best translation. string translatedText = info.Text; CultureInfo culture = CultureInfo.InvariantCulture; lock (m_lock) { translatedText = FindBestTranslation(preferredLocales, key, out culture); // use the default if no translation available. if (translatedText == null) { return defaultText; } // get a culture to use for formatting if (culture == null) { if (info.Args != null && info.Args.Length > 0 && !String.IsNullOrEmpty(info.Locale)) { try { culture = CultureInfo.GetCultureInfo(info.Locale); } catch { culture = CultureInfo.InvariantCulture; } } } } // format translated text. string formattedText = translatedText; if (info.Args != null && info.Args.Length > 0) { try { formattedText = String.Format(culture, translatedText, info.Args); } catch { formattedText = translatedText; } } // construct translated localized text. Opc.Ua.LocalizedText finalText = new LocalizedText(culture.Name, formattedText); finalText.TranslationInfo = info; return finalText; }
/// <summary> /// Constructor. /// </summary> public ModConfig() { this.translationInfo = new TranslationInfo(); this.useLegacyBirthdayFiles = true; }
/// <summary> /// Translates a status code. /// </summary> private LocalizedText TranslateStatusCode(IList<string> preferredLocales, StatusCode statusCode, object[] args) { lock (m_lock) { if (m_statusCodeMapping != null) { TranslationInfo info = null; if (m_statusCodeMapping.TryGetValue(statusCode.Code, out info)) { // merge the argument list with the trahslateion info cached for the status code. if (args != null) { info = new TranslationInfo( info.Key, info.Locale, info.Text, args); } return Translate(preferredLocales, null, info); } } } return String.Format("{0:X8}", statusCode.Code); }
/// <summary> /// Translates a symbolic id. /// </summary> private LocalizedText TranslateSymbolicId(IList<string> preferredLocales, string symbolicId, string namespaceUri, object[] args) { lock (m_lock) { if (m_symbolicIdMapping != null) { TranslationInfo info = null; if (m_symbolicIdMapping.TryGetValue(new XmlQualifiedName(symbolicId, namespaceUri), out info)) { // merge the argument list with the trahslateion info cached for the symbolic id. if (args != null) { info = new TranslationInfo( info.Key, info.Locale, info.Text, args); } return Translate(preferredLocales, null, info); } } } return symbolicId; }
/// <summary> /// Publishes all available event notifications. /// </summary> public virtual bool Publish(OperationContext context, Queue<EventFieldList> notifications) { if (context == null) throw new ArgumentNullException("context"); if (notifications == null) throw new ArgumentNullException("notifications"); lock (m_lock) { // check if the item reports events. if ((m_typeMask & MonitoredItemTypeMask.Events) == 0) { return false; } // only publish if reporting. if (!IsReadyToPublish) { return false; } // go to the next sampling interval. IncrementSampleTime(); // publish events. if (m_events != null) { Utils.Trace("MONITORED ITEM: Publish(QueueSize={0})", notifications.Count); EventFieldList overflowEvent = null; if (m_overflow) { // construct event. EventQueueOverflowEventState e = new EventQueueOverflowEventState(null); TranslationInfo message = new TranslationInfo( "EventQueueOverflowEventState", "en-US", "Events lost due to queue overflow."); ISystemContext systemContext = new ServerSystemContext(m_server, context); e.Initialize( systemContext, null, EventSeverity.Low, new LocalizedText(message)); e.SetChildValue(systemContext, BrowseNames.SourceNode, ObjectIds.Server, false); e.SetChildValue(systemContext, BrowseNames.SourceName, "Internal", false); // fetch the event fields. overflowEvent = GetEventFields( new FilterContext(m_server.NamespaceUris, m_server.TypeTree, m_session.PreferredLocales), m_filterToUse as EventFilter, e); } // place event at the beginning of the queue. if (overflowEvent != null && m_discardOldest) { notifications.Enqueue(overflowEvent); } for (int ii = 0; ii < m_events.Count; ii++) { EventFieldList fields = (EventFieldList)m_events[ii]; // apply any diagnostic masks. for (int jj = 0; jj < fields.EventFields.Count; jj++) { object value = fields.EventFields[jj].Value; StatusResult result = value as StatusResult; if (result != null) { result.ApplyDiagnosticMasks(context.DiagnosticsMask, context.StringTable); } } notifications.Enqueue((EventFieldList)m_events[ii]); } m_events.Clear(); // place event at the end of the queue. if (overflowEvent != null && !m_discardOldest) { notifications.Enqueue(overflowEvent); } Utils.Trace("MONITORED ITEM: Publish(QueueSize={0})", notifications.Count); } // reset state variables. m_overflow = false; m_readyToPublish = false; m_readyToTrigger = false; m_triggered = false; return false; } }