public void Test() { using (var session = sessions.OpenSession()) using (var transaction = session.BeginTransaction()) { _keyword = new Keyword(); session.Save(_keyword); var nodeKeyword = new NodeKeyword(); nodeKeyword.NodeId = 1; nodeKeyword.Keyword = _keyword; session.Save(nodeKeyword); transaction.Commit(); } using (var session = sessions.OpenSession()) { //If uncomment the line below the test will pass //GetResult(session); var result = GetResult(session); Assert.That(result, Has.Count.EqualTo(2)); Assert.That(result[0], Has.Count.EqualTo(1)); Assert.That(result[1], Has.Count.EqualTo(1)); } }
public Ongoing(Keyword keyword, EffectType effect_type, int modifier, int duration) { key = keyword; type = effect_type; mod = modifier; dur = duration; }
public CaseExpr( IPersistentMap sourceSpan, LocalBindingExpr expr, int shift, int mask, int low, int high, Expr defaultExpr, SortedDictionary<int, Expr> tests, Dictionary<int, Expr> thens, Keyword switchType, Keyword testType, IPersistentSet skipCheck) { _sourceSpan = sourceSpan; _expr = expr; _shift = shift; _mask = mask; //_low = low; //_high = high; _defaultExpr = defaultExpr; _tests = tests; _thens = thens; if (switchType != _compactKey && switchType != _sparseKey) throw new ArgumentException("Unexpected switch type: " + switchType); //_switchType = switchType; if (testType != _intKey && testType != _hashEquivKey && testType != _hashIdentityKey) throw new ArgumentException("Unexpected test type: " + testType); _testType = testType; _skipCheck = skipCheck; ICollection<Expr> returns = new List<Expr>(thens.Values); returns.Add(defaultExpr); _returnType = Compiler.MaybeClrType(returns); if (RT.count(skipCheck) > 0 && RT.booleanCast(RT.WarnOnReflectionVar.deref())) { RT.errPrintWriter().WriteLine("Performance warning, {0}:{1} - hash collision of some case test constants; if selected, those entries will be tested sequentially.", Compiler.SourcePathVar.deref(),RT.get(sourceSpan,RT.StartLineKey)); } }
/// <summary> /// Adds a new keyword xml node to a <see cref="T:System.Xml.XmlNode" /> /// </summary> /// <param name="node"><see cref="T:System.Xml.XmlNode" /></param> /// <param name="name">xml Node Name</param> /// <param name="value"><see cref="T:Tridion.ContentManager.ContentManagement.Keyword" /></param> /// <param name="includeLevel">if set to <c>true</c> [include level].</param> /// <returns> /// <see cref="T:System.Xml.XmlElement" /> keyword node /// </returns> public static XmlElement AddKeywordNode(this XmlNode node, String name, Keyword value, bool includeLevel) { if (node != null && !String.IsNullOrEmpty(name) && node.OwnerDocument != null && value != null) { XmlElement xElement = node.OwnerDocument.CreateElement(name); xElement.SetAttribute("uri", value.Id); if (!String.IsNullOrEmpty(value.Key)) xElement.SetAttribute("key", value.Key); if (!String.IsNullOrEmpty(value.Description)) xElement.SetAttribute("description", value.Description); xElement.SetAttribute("root", value.IsRoot.ToString().ToLower()); if (includeLevel) xElement.SetAttribute("level", value.Level().ToString()); xElement.InnerXml = SecurityElement.Escape(value.Title); node.AppendChild(xElement); return xElement; } return null; }
public JsonKeyword Map(Keyword keyword) { switch (keyword) { case Keyword.Given: { return JsonKeyword.Given; } case Keyword.When: { return JsonKeyword.When; } case Keyword.Then: { return JsonKeyword.Then; } case Keyword.And: { return JsonKeyword.And; } case Keyword.But: { return JsonKeyword.But; } default: throw new ArgumentOutOfRangeException(nameof(keyword), keyword, null); } }
/// <summary> /// Add a new entry to one of the dropdown tables in the database. /// </summary> /// <param name="table">Table to add a new entry to.</param> /// <param name="entry"> /// DropdownEntry containing the value and code, /// if exists. /// </param> public void addEntry(Constants.DropdownTable table, DropdownEntry entry) { switch (table) { case Constants.DropdownTable.Keyword: var kw = new Keyword { KeywordValue = entry.value }; _db.Keywords.InsertOnSubmit(kw); break; case Constants.DropdownTable.QuestionType: var qType = new QuestionType { Code = entry.code, Value = entry.value }; _db.QuestionTypes.InsertOnSubmit(qType); break; case Constants.DropdownTable.Region: var region = new Region { Code = entry.code, Value = entry.value }; _db.Regions.InsertOnSubmit(region); break; case Constants.DropdownTable.RequestorType: var rType = new RequestorType { Code = entry.code, Value = entry.value }; _db.RequestorTypes.InsertOnSubmit(rType); break; case Constants.DropdownTable.TumourGroup: var tGroup = new TumourGroup { Code = entry.code, Value = entry.value }; _db.TumourGroups.InsertOnSubmit(tGroup); break; case Constants.DropdownTable.UserGroup: var uGroup = new UserGroup { Code = entry.code, Value = entry.value }; _db.UserGroups.InsertOnSubmit(uGroup); break; } _db.SubmitChanges(); }
public void UpdateKeywordIsPersisted() { using (var businessContext = new BusinessContext()) { var language = new Language { Name = "LanguageName" }; businessContext.AddNewLanguage(language); var keyword = new Keyword { Name = "KeywordName", LanguageId = 1, }; businessContext.AddNewKeyword(keyword); keyword.Name = "New KeywordName"; businessContext.UpdateKeyword(keyword); bool updated = businessContext.DataContext.Keywords.Any(k => k.Id == keyword.Id && k.Name == keyword.Name); Assert.IsTrue(updated); } }
public bool TryGetKeyword(string categoryUriToLookIn, string keywordName, out IKeyword keyword) { using (var client = new TridionBrokerServiceClient()) { string result = client.GetKeywordHierarchy(categoryUriToLookIn, keywordName); if (!string.IsNullOrEmpty(result)) { XElement keyWord = XElement.Parse(result); var tkeyword = new Keyword() { Id = keyWord.Element("Uri").Value, Title = keyWord.Element("KeywordName").Value, TaxonomyId = keyWord.Element("TaxonomyUri").Value }; foreach (XElement parentElement in keyWord.Element("ParentKeywords").Elements()) { tkeyword.ParentKeywords.Add( new Keyword { Id = parentElement.Attribute("Uri").Value, Title = parentElement.Value, TaxonomyId = parentElement.Attribute("TaxonomyUri").Value } ); } keyword = tkeyword; return true; } } keyword = null; return false; }
// EasyTraceEvent // Checks the keyword and level before emiting the event static internal void EasyTraceEvent(Keyword keywords, Level level, Event eventID) { if (IsEnabled(keywords, level)) { EventProvider.TraceEvent(eventID, keywords, level); } }
public void Test() { IDriver driver = sessions.ConnectionProvider.Driver; if (!driver.SupportsMultipleQueries) { Assert.Ignore("Driver {0} does not support multi-queries", driver.GetType().FullName); } using (ISession session = sessions.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { _keyword = new Keyword(); session.Save(_keyword); NodeKeyword nodeKeyword = new NodeKeyword(); nodeKeyword.NodeId = 1; nodeKeyword.Keyword = _keyword; session.Save(nodeKeyword); transaction.Commit(); } using (ISession session = sessions.OpenSession()) { //If uncomment the line below the test will pass //GetResult(session); IList result = GetResult(session); Assert.That(result, Has.Count.EqualTo(2)); Assert.That(result[0], Has.Count.EqualTo(1)); Assert.That(result[1], Has.Count.EqualTo(1)); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to which keywords are added. /// </param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupCriterionService. AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService) user.GetService( AdWordsService.v201509.AdGroupCriterionService); List<AdGroupCriterionOperation> operations = new List<AdGroupCriterionOperation>(); foreach (string keywordText in KEYWORDS) { // Create the keyword. Keyword keyword = new Keyword(); keyword.text = keywordText; keyword.matchType = KeywordMatchType.BROAD; // Create the biddable ad group criterion. BiddableAdGroupCriterion keywordCriterion = new BiddableAdGroupCriterion(); keywordCriterion.adGroupId = adGroupId; keywordCriterion.criterion = keyword; // Optional: Set the user status. keywordCriterion.userStatus = UserStatus.PAUSED; // Optional: Set the keyword destination url. keywordCriterion.finalUrls = new UrlList() { urls = new string[] { "http://example.com/mars/cruise/?kw=" + HttpUtility.UrlEncode(keywordText) } }; // Create the operations. AdGroupCriterionOperation operation = new AdGroupCriterionOperation(); operation.@operator = Operator.ADD; operation.operand = keywordCriterion; operations.Add(operation); } try { // Create the keywords. AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(operations.ToArray()); // Display the results. if (retVal != null && retVal.value != null) { foreach (AdGroupCriterion adGroupCriterion in retVal.value) { // If you are adding multiple type of criteria, then you may need to // check for // // if (adGroupCriterion is Keyword) { ... } // // to identify the criterion type. Console.WriteLine("Keyword with ad group id = '{0}', keyword id = '{1}', text = " + "'{2}' and match type = '{3}' was created.", adGroupCriterion.adGroupId, adGroupCriterion.criterion.id, (adGroupCriterion.criterion as Keyword).text, (adGroupCriterion.criterion as Keyword).matchType); } } else { Console.WriteLine("No keywords were added."); } } catch (Exception e) { throw new System.ApplicationException("Failed to create keywords.", e); } }
static internal void EasyTraceEvent(Keyword keywords, Level level, Event eventID, object param1, object param2) { if (IsEnabled(keywords, Level.Info)) { EventProvider.TraceEvent(eventID, keywords, Level.Info, param1, param2); } }
public IHttpActionResult Create(Keyword keyword) { var createdKeyword = KeywordLogic.CreateKeyword(keyword); if (createdKeyword == null) return Conflict(); return Ok(createdKeyword); }
private List<Keyword> ComputeArticleTfidf(string content, int titleLength) { var tm = new HashMap<string, Keyword>(); var parse = NlpAnalysis.Parse(content); foreach (var term in parse) { var weight = getWeight(term, content.Length, titleLength); if (weight == 0) continue; var keyword = tm[term.Name]; if (keyword == null) { keyword = new Keyword(term.Name, term.Nature.allFrequency, weight); tm[term.Name] = keyword; } else { keyword.UpdateWeight(1); } } var treeSet = new SortedSet<Keyword>(tm.Values); var arrayList = new List<Keyword>(treeSet); if (treeSet.Count <= _keywordAmount) { return arrayList; } return arrayList.Take(_keywordAmount).ToList(); }
public void DeleteKeywordIsPersisted() { using (var businessContext = new BusinessContext()) { var language = new Language { Name = "LanguageName" }; businessContext.AddNewLanguage(language); var keyword = new Keyword { Name = "KeywordName", LanguageId = 1, }; businessContext.AddNewKeyword(keyword); //businessContext.DeleteKeyword(keyword); bool notDeleted = businessContext.DataContext.Keywords.Any(k => k.Id == keyword.Id); //Assert.IsFalse(notDeleted); } }
public void Add(int index, Keyword keyword, int topicCount) { if (_cache.Count > MaxItems) Clear(); _index.Add(index); _cache.Add(keyword); _topicCount.Add(topicCount); }
public void SetKeyword(string keywordText) { Keyword keyword; if (Enum.TryParse<Keyword>(keywordText, out keyword)) { this.keyword = keyword; } }
internal NavigationNode(Keyword keyword) { Keyword = keyword; _keywordMeta = new XmlDocument(); _keywordMeta.LoadXml(keyword.Metadata.OuterXml); _nm = new XmlNamespaceManager(new NameTable()); _nm.AddNamespace("meta", keyword.MetadataSchema.NamespaceUri); _log = TemplatingLogger.GetLogger(GetType()); }
public InteractionResult(Keyword keyword) { KeywordName = keyword.Name; Result = Result.CreateFail(string.Format("Failure to access keyword {0}.\r\n Keyword exists = {1}.\r\n Parameters are correct = {2}", keyword.Name, keyword.KeywordExists, keyword.ParametersAreCorrect)); }
public StepResult(Keyword keyword) { KeywordName = keyword.Name; Result = Result.CreateFail(string.Format("Can't find step '{0}'.</br>- - - - ->Step exists = {1}.\r\n Parameters are correct = {2}", keyword.Name, keyword.KeywordExists, keyword.ParametersAreCorrect)); }
public void SetKeyword(string keywordText) { this.nativeKeyword = keywordText; Keyword? keyword = this.TryParseKeyword(keywordText); if (keyword.HasValue) { this.keyword = keyword.Value; } }
private static string FindKeywordPath(Keyword keyword) { IList<Keyword> parentKeywords = keyword.ParentKeywords; string path = @"\" + keyword.Title; while (parentKeywords.Count > 0) { path = @"\" + parentKeywords[0].Title + path; parentKeywords = parentKeywords[0].ParentKeywords; } return @"\" + keyword.OrganizationalItem.Title + path; }
public static Dynamic.Keyword BuildKeyword(Keyword keyword) { Dynamic.Keyword dk = new Dynamic.Keyword(); dk.Id = keyword.Id; dk.Title = keyword.Title; dk.Path = FindKeywordPath(keyword); dk.Description = keyword.Description; dk.Key = keyword.Key; dk.TaxonomyId = keyword.OrganizationalItem.Id; return dk; }
public TermExpression( Token start, Expression left, Keyword oper, Expression right) : base(start) { this.Left = left; this.Operator = oper; this.Right = right; }
public override Symbol Intern(string name) { Predicate<Symbol> matchString = new Predicate<Symbol> (new StringMatcher (name).MatchesSymbol); Symbol probe = this.PresentSymbolList.Find (matchString); if (probe == null) { probe = new Keyword (name); this.PresentSymbolList.Add (probe); this.ExternalSymbolList.Add (probe); } return probe; }
public static IList<Keyword> GetKeywordTrail(Keyword keyword) { List<Keyword> keywords = new List<Keyword>(); Keyword kw = keyword; while(!kw.IsRoot) { keywords.Add(kw); kw = kw.ParentKeywords[0]; } return keywords; }
public void AddNewKeyword_ThrowsException_WhenLanguageIdDoesNotExist() { using (var businessContext = new BusinessContext()) { var keyword = new Keyword { Name = "KeywordName", LanguageId = 0 }; businessContext.AddNewKeyword(keyword); } }
public void DllTest() { Assembly a = Assembly.LoadFrom(@"F:\Prog\gnutella2\bin\Debug\gnutella2.dll"); Type type = a.GetType("ActionInnocence.P2PScan.ProtocolPlugin"); IProtocol protocol = (IProtocol)Activator.CreateInstance(type, new string[] { @"F:\Prog\gnutella2\bin\Debug\", "192.168.1.38" }); protocol.NewResult += new SearchResultHandler(protocol_NewResult); protocol.Connect(); Thread.Sleep(1000 * 2); Keyword w = new Keyword("gnutella2","madonna"); KeywordCollection coll = new KeywordCollection(); coll.Add(w); protocol.SearchKeyword(new SearchTransaction("1", coll, 1, null)); System.Threading.Thread.Sleep(1000 * 30); protocol.Disconnect(); }
public int Update(Keyword model) { Keyword entity = Get(model.Id); if (entity == null) { entity = model; context.Keywords.Add(entity); } else { context.Entry(entity).CurrentValues.SetValues(model); } context.SaveChanges(); return (int)entity.Id; }
public void TestMethod3() { //Create Keyword and Paper Keyword expectedKeyword = new Keyword(null); Paper expectedPaper = new Paper("Some Paper About Testing"); //Add keyword to paper expectedPaper.AddKeyword(expectedKeyword); //A mapping system to store the papers in SystematicMappingSystem sms = new SystematicMappingSystem(); //Add paper to the system sms.AddPaper(expectedPaper); List<Keyword> keyWordsList = sms.GetKeywordsFromPaper("Some Paper About Testing"); Assert.Fail(); }
/// <summary> /// Implementation of <see cref="IWorkflowScript.OnWorkflowScriptExecute" />. /// <seealso cref="IWorkflowScript" /> /// This script assigns the appropriate Processing Unit and Load Balanced User to App Processing queues /// 1. Gets Trans Code and License Type from Application document type /// 2. Perform lookup to SQL DB for user assignment and Processing Unit and assign as keywords /// REMOVED 3. Update last_user and last_assigned with last assigned user / datetime (load balance) /// 3. (11/23/2010-TT) Unknown change time, but script actually does a /// "least # documents assigned across lifecycle" assignment - see getNextUser() function /// (11/23/2010-TT) Modified the "getNextUser()" function's SQL call to better reflect actual workload of users /// </summary> /// <param name="app">Unity Application object</param> /// <param name="args">Workflow event arguments</param> public void OnWorkflowScriptExecute(Application app, WorkflowEventArgs args) // public void OnWorkflowScriptExecute(Application app, WorkflowEventArgs args=null) { try { // Initialize global settings IntializeScript(ref app, ref args); KeywordType ktwTranCode = _currentDocument.DocumentType.KeywordRecordTypes.FindKeywordType(gParamTranCode); string strTranCode = ""; if (ktwTranCode != null) { KeywordRecord keyRecTranCode = _currentDocument.KeywordRecords.Find(ktwTranCode); if (keyRecTranCode != null) { Keyword kwdTranCode = keyRecTranCode.Keywords.Find(ktwTranCode); if (kwdTranCode != null) strTranCode = kwdTranCode.ToString(); } } KeywordType ktwLicType = _currentDocument.DocumentType.KeywordRecordTypes.FindKeywordType(gParamLicType); string strLicType = ""; if (ktwLicType != null) { KeywordRecord keyRecLicType = _currentDocument.KeywordRecords.Find(ktwLicType); if (keyRecLicType != null) { Keyword kwdLicType = keyRecLicType.Keywords.Find(ktwLicType); if (kwdLicType != null) strLicType = kwdLicType.ToString(); } } if (strLicType == "" || strTranCode == "") { throw new Exception(string.Format("{0} or {1} is blank.", gParamLicType, gParamTranCode)); } //access Config Item for OnBase User string gUSER = ""; if (app.Configuration.TryGetValue("OnBaseUser", out gUSER)) { } //access Config Item for OnBase Password string gPASS = ""; if (app.Configuration.TryGetValue("OnBasePassword", out gPASS)) { } /* COMMENT THIS SECTION OUT WHEN MOVING TO PROD */ //access Config Item for OnBase UAT ODBC string gODBCMISC = ""; if (app.Configuration.TryGetValue("CIUOnbaseMISC", out gODBCMISC)) { } string gODBCOnBase = ""; if (app.Configuration.TryGetValue("OnBaseUAT", out gODBCOnBase)) { } /* UNCOMMENT THIS SECTION WHEN MOVING TO PROD //access Config Item for OnBase PROD ODBC string gODBCOnBase = ""; if (app.Configuration.TryGetValue("OnBasePROD", out gODBCOnBase)) { } */ // ************** // Get Routing Values - This query gets the Proc Unit, Users and LastUser from SQL strSql.Append(@"SELECT users AS USER, proc_unit AS UNIT "); strSql.Append(@" FROM dbo.tbl_ccb "); strSql.Append(@" WHERE license_type = '"); strSql.Append(strLicType); strSql.Append(@"' AND tran_code = '"); strSql.Append(strTranCode); strSql.Append(@"'"); string connectionString = string.Format("DSN={0};Uid={1};Pwd={2};", gODBCMISC, gUSER, gPASS); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("Sql Query: {0}", strSql.ToString())); using (OdbcConnection con = new OdbcConnection(connectionString)) { try { con.Open(); using (OdbcCommand command = new OdbcCommand(strSql, con)) using (OdbcDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { reader.Read(); string strUnit = ""; List<string> lstUser = new List<string>(); lstUser.Add(reader["USER"].ToString()); strUnit = reader["UNIT"].ToString(); string strSQLUsers = ""; foreach (string result in lstUser) { if (result != "" && strSQLUsers == "") { strSQLUsers = "'" + strSQLUsers + result + "'"; } else if (result != "" && strSQLUsers != "") { strSQLUsers = strSQLUsers + ",'" + result + "'"; } } strSql.Append(@"select CT1.username, sum(CT1.DocCount) as DocCount from ((select ua.username, count(ilcu.usernum) as DocCount "); strSql.Append(@" from hsi.useraccount ua left outer join (select usernum,itemnum from hsi.itemlcxuser where hsi.itemlcxuser.lcnum= "); strSql.Append(gLCNUM); strSql.Append(@" or hsi.itemlcxuser.lcnum="); strSql.Append(gLCNUM2); strSql.Append(@" ) ilcu on ua.usernum = ilcu.usernum inner join hsi.itemlc il on il.itemnum = ilcu.itemnum "); strSql.Append(@" inner join hsi.itemdata id on ilcu.itemnum = id.itemnum inner join hsi.lcstate lcs on il.statenum = lcs.statenum where ua.username in( "); strSql.Append(strSQLUsers); strSql.Append(@") and id.status=0 and (lcs.statename like 'CIU-Application Processing%' or lcs.statename like 'DDC - Application Processing%')"); strSql.Append(@" and lcs.statename not like 'CIU-Application Processing Routing Exceptions' and lcs.statename not like 'DDC - Application Processing Routing Exceptions' "); strSql.Append(@" and lcs.statename not like 'DDC - Application Processing - Pending Info' group by ua.username ) UNION ( select ua.username, 0 as DocCount from hsi.useraccount ua where ua.username in ( "); strSql.Append(strSQLUsers); strSql.Append(@") ) ) CT1 group by CT1.username order by DocCount asc"); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("2nd Sql Query: {0}", strSql.ToString())); string connectionStringOnBase = string.Format("DSN={0};Uid={1};Pwd={2};", gODBCOnBase, gUSER, gPASS); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("Connection string: {0}", connectionStringOnBase)); string strNextUser = ""; using (OdbcConnection conOnBase = new OdbcConnection(connectionStringOnBase)) { try { conOnBase.Open(); using (OdbcCommand command = new OdbcCommand(strSql, conOnBase)) using (OdbcDataReader readerOnBase = command.ExecuteReader()) { if (readerOnBase.HasRows) { while (readerOnBase.Read()) { strNextUser = readerOnBase[0].ToString(); } } } } catch (Exception ex) { throw new ApplicationException("Error during database operations!", ex); } finally { if (conOnBase.State == ConnectionState.Open) conOnBase.Close(); } } Keyword kwdUser = null; if (!String.IsNullOrEmpty(strNextUser)) { KeywordType kwtUser = app.Core.KeywordTypes.Find(gSaveToAssignedProc); if (kwtUser != null) kwdUser = CreateKeywordHelper(kwtUser, strNextUser); } Keyword kwdUnit = null; if (!String.IsNullOrEmpty(strUnit)) { KeywordType kwtUnit = app.Core.KeywordTypes.Find(gSaveToAssignedProcUnit); if (kwtUnit != null) kwdUnit = CreateKeywordHelper(kwtUnit, strUnit); } using (DocumentLock documentLock = _currentDocument.LockDocument()) { // Ensure lock was obtained if (documentLock.Status != DocumentLockStatus.LockObtained) { throw new Exception("Document lock not obtained"); } // Create keyword modifier object to hold keyword changes KeywordModifier keyModifier = _currentDocument.CreateKeywordModifier(); // Add update keyword call to keyword modifier object //Note Overloads available for use //(I.E.): keyModifier.AddKeyword(keywordTypeName,keywordValue) if (kwdUnit != null) keyModifier.AddKeyword(kwdUnit); if (kwdUser != null) keyModifier.AddKeyword(kwdUser); // Apply keyword change to the document keyModifier.ApplyChanges(); string output = String.Format("Keyword: '{0}' Value: '{1}', {3}added to Document {2}.", gSaveToAssignedProcUnit, strUnit, _currentDocument.ID, Environment.NewLine); //Output the results to the OnBase Diagnostics Console app.Diagnostics.WriteIf(Hyland.Unity.Diagnostics.DiagnosticsLevel.Verbose, output); string output2 = String.Format("Keyword: '{0}' Value: '{1}', {3}added to Document {2}.", gSaveToAssignedProc, strWFUser, _currentDocument.ID, Environment.NewLine); app.Diagnostics.WriteIf(Hyland.Unity.Diagnostics.DiagnosticsLevel.Verbose, output2); } } else { throw new Exception(string.Format("No records found in database for {0}='{1}'", gParamBatchType, strBatchType)); } } } catch (Exception ex) { throw new ApplicationException("Error during database operations!", ex); } finally { if (con.State == ConnectionState.Open) con.Close(); } } } catch (Exception ex) { // Handle exceptions and log to Diagnostics Console and document history HandleException(ex, ref app, ref args); } finally { // Log script execution end app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Info, string.Format("End Script - [{0}]", ScriptName)); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to which keywords are added. /// </param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupCriterionService. AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)user.GetService( AdWordsService.v201406.AdGroupCriterionService); List <AdGroupCriterionOperation> operations = new List <AdGroupCriterionOperation>(); for (int i = 0; i < NUM_ITEMS; i++) { // Create the keyword. Keyword keyword = new Keyword(); keyword.text = "mars cruise"; keyword.matchType = KeywordMatchType.BROAD; // Create the biddable ad group criterion. BiddableAdGroupCriterion keywordCriterion = new BiddableAdGroupCriterion(); keywordCriterion.adGroupId = adGroupId; keywordCriterion.criterion = keyword; // Optional: Set the user status. keywordCriterion.userStatus = UserStatus.PAUSED; // Optional: Set the keyword destination url. keywordCriterion.destinationUrl = "http://example.com/mars/cruise/" + i; // Create the operations. AdGroupCriterionOperation operation = new AdGroupCriterionOperation(); operation.@operator = Operator.ADD; operation.operand = keywordCriterion; operations.Add(operation); } try { // Create the keywords. AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(operations.ToArray()); // Display the results. if (retVal != null && retVal.value != null) { foreach (AdGroupCriterion adGroupCriterion in retVal.value) { // If you are adding multiple type of criteria, then you may need to // check for // // if (adGroupCriterion is Keyword) { ... } // // to identify the criterion type. Console.WriteLine("Keyword with ad group id = '{0}', keyword id = '{1}', text = " + "'{2}' and match type = '{3}' was created.", adGroupCriterion.adGroupId, adGroupCriterion.criterion.id, (adGroupCriterion.criterion as Keyword).text, (adGroupCriterion.criterion as Keyword).matchType); } } else { Console.WriteLine("No keywords were added."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to create keywords.", ex); } }
public CaseExpr(IPersistentMap sourceSpan, LocalBindingExpr expr, int shift, int mask, int low, int high, Expr defaultExpr, SortedDictionary <int, Expr> tests, Dictionary <int, Expr> thens, Keyword switchType, Keyword testType, IPersistentSet skipCheck) { _sourceSpan = sourceSpan; _expr = expr; _shift = shift; _mask = mask; _low = low; _high = high; _defaultExpr = defaultExpr; _tests = tests; _thens = thens; if (switchType != _compactKey && switchType != _sparseKey) { throw new ArgumentException("Unexpected switch type: " + switchType); } _switchType = switchType; if (testType != _intKey && testType != _hashEquivKey && testType != _hashIdentityKey) { throw new ArgumentException("Unexpected test type: " + testType); } _testType = testType; _skipCheck = skipCheck; ICollection <Expr> returns = new List <Expr>(thens.Values); returns.Add(defaultExpr); _returnType = Compiler.MaybeClrType(returns); if (RT.count(skipCheck) > 0 && RT.booleanCast(RT.WarnOnReflectionVar.deref())) { RT.errPrintWriter().WriteLine("Performance warning, {0}:{1}:{2} - hash collision of some case test constants; if selected, those entries will be tested sequentially.", Compiler.SourcePathVar.deref(), Compiler.GetLineFromSpanMap(sourceSpan), Compiler.GetColumnFromSpanMap(sourceSpan)); } }
internal bool IsVolatile(LocalBinding lb) { return(RT.booleanCast(RT.contains(Fields, lb.Symbol)) && RT.booleanCast(RT.get(lb.Symbol.meta(), Keyword.intern("volatile-mutable")))); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> public void Run(AdWordsUser user) { // Get the AdGroupCriterionService. AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)user.GetService(AdWordsService.v201402.AdGroupCriterionService); // Create a selector. Selector selector = new Selector(); selector.fields = new string[] { "Id", "AdGroupId", "KeywordText" }; // Select only keywords. Predicate predicate = new Predicate(); predicate.field = "CriteriaType"; predicate.@operator = PredicateOperator.EQUALS; predicate.values = new string[] { "KEYWORD" }; selector.predicates = new Predicate[] { predicate }; // Set the selector paging. selector.paging = new Paging(); int offset = 0; int pageSize = 500; AdGroupCriterionPage page = new AdGroupCriterionPage(); try { do { selector.paging.startIndex = offset; selector.paging.numberResults = pageSize; // Get the keywords. page = adGroupCriterionService.get(selector); // Display the results. if (page != null && page.entries != null) { int i = offset; foreach (AdGroupCriterion adGroupCriterion in page.entries) { bool isNegative = (adGroupCriterion is NegativeAdGroupCriterion); // If you are retrieving multiple type of criteria, then you may // need to check for // // if (adGroupCriterion is Keyword) { ... } // // to identify the criterion type. Keyword keyword = (Keyword)adGroupCriterion.criterion; if (isNegative) { Console.WriteLine("{0}) Negative keyword with ad group ID = '{1}', keyword ID " + "= '{2}', and text = '{3}' was found.", i + 1, adGroupCriterion.adGroupId, keyword.id, keyword.text); } else { Console.WriteLine("{0}) Keyword with ad group ID = '{1}', keyword ID = '{2}', " + "text = '{3}' and matchType = '{4} was found.", i + 1, adGroupCriterion.adGroupId, keyword.id, keyword.text, keyword.matchType); } i++; } } offset += pageSize; } while (offset < page.totalNumEntries); Console.WriteLine("Number of keywords found: {0}", page.totalNumEntries); } catch (Exception ex) { throw new System.ApplicationException("Failed to retrieve keywords.", ex); } }
public IList <IKeyword> GetMatchingKeywords(string word) { return(Keyword.Where(keyword => keyword.Word.Equals(word)).ToList <IKeyword>()); }
private object GetValue(Keyword kw) { switch (kw) { case Keyword.UserID: return(this.UserID); case Keyword.Password: return(this.Password); case Keyword.Server: return(this.Server); case Keyword.Port: return(this.Port); case Keyword.UseUsageAdvisor: return(this.UseUsageAdvisor); case Keyword.CharacterSet: return(this.CharacterSet); case Keyword.Compress: return(this.UseCompression); case Keyword.PipeName: return(this.PipeName); case Keyword.Logging: return(this.Logging); case Keyword.SharedMemoryName: return(this.SharedMemoryName); case Keyword.AllowBatch: return(this.AllowBatch); case Keyword.ConvertZeroDatetime: return(this.ConvertZeroDateTime); case Keyword.PersistSecurityInfo: return(this.PersistSecurityInfo); case Keyword.Database: return(this.Database); case Keyword.ConnectionTimeout: return(this.ConnectionTimeout); case Keyword.Pooling: return(this.Pooling); case Keyword.MinimumPoolSize: return(this.MinimumPoolSize); case Keyword.MaximumPoolSize: return(this.MaximumPoolSize); case Keyword.ConnectionLifetime: return(this.ConnectionLifeTime); case Keyword.DriverType: return(this.DriverType); case Keyword.Protocol: return(this.ConnectionProtocol); case Keyword.ConnectionReset: return(this.ConnectionReset); case Keyword.AllowZeroDatetime: return(this.AllowZeroDateTime); case Keyword.UsePerformanceMonitor: return(this.UsePerformanceMonitor); case Keyword.ProcedureCacheSize: return(this.ProcedureCacheSize); case Keyword.IgnorePrepare: return(this.IgnorePrepare); case Keyword.UseSSL: return(this.UseSSL); case Keyword.UseProcedureBodies: return(this.UseProcedureBodies); case Keyword.AutoEnlist: return(this.AutoEnlist); case Keyword.RespectBinaryFlags: return(this.RespectBinaryFlags); case Keyword.TreatBlobsAsUTF8: return(this.TreatBlobsAsUTF8); case Keyword.BlobAsUTF8IncludePattern: return(this.blobAsUtf8IncludePattern); case Keyword.BlobAsUTF8ExcludePattern: return(this.blobAsUtf8ExcludePattern); case Keyword.DefaultCommandTimeout: return(this.defaultCommandTimeout); case Keyword.TreatTinyAsBoolean: return(this.treatTinyAsBoolean); case Keyword.AllowUserVariables: return(this.allowUserVariables); case Keyword.InteractiveSession: return(this.interactiveSession); case Keyword.FunctionsReturnString: return(this.functionsReturnString); } return(null); }
/// <summary> /// Gets the shared criteria in a shared set. /// </summary> /// <param name="user">The user that owns the shared set.</param> /// <param name="sharedSetIds">The shared criteria IDs.</param> /// <returns>The list of shared criteria.</returns> private List <SharedCriterion> GetSharedCriteria(AdWordsUser user, List <string> sharedSetIds) { using (SharedCriterionService sharedCriterionService = (SharedCriterionService)user.GetService( AdWordsService.v201802.SharedCriterionService)) { Selector selector = new Selector() { fields = new string[] { SharedSet.Fields.SharedSetId, Criterion.Fields.Id, Keyword.Fields.KeywordText, Keyword.Fields.KeywordMatchType, Placement.Fields.PlacementUrl }, predicates = new Predicate[] { Predicate.In(SharedSet.Fields.SharedSetId, sharedSetIds) }, paging = Paging.Default }; List <SharedCriterion> sharedCriteria = new List <SharedCriterion>(); SharedCriterionPage page = new SharedCriterionPage(); try { do { // Get the campaigns. page = sharedCriterionService.get(selector); // Display the results. if (page != null && page.entries != null) { int i = selector.paging.startIndex; foreach (SharedCriterion sharedCriterion in page.entries) { switch (sharedCriterion.criterion.type) { case CriterionType.KEYWORD: Keyword keyword = (Keyword)sharedCriterion.criterion; Console.WriteLine("{0}) Shared negative keyword with ID {1} and text '{2}' " + "was found.", i + 1, keyword.id, keyword.text); break; case CriterionType.PLACEMENT: Placement placement = (Placement)sharedCriterion.criterion; Console.WriteLine("{0}) Shared negative placement with ID {1} and URL '{2}' " + "was found.", i + 1, placement.id, placement.url); break; default: Console.WriteLine("{0}) Shared criteria with ID {1} was found.", i + 1, sharedCriterion.criterion.id); break; } i++; sharedCriteria.Add(sharedCriterion); } } selector.paging.IncreaseOffset(); } while (selector.paging.startIndex < page.totalNumEntries); return(sharedCriteria); } catch (Exception e) { throw new Exception("Failed to get shared criteria.", e); } } }
/// <summary> /// Implementation of <see cref="IWorkflowScript.OnWorkflowScriptExecute" />. /// <seealso cref="IWorkflowScript" /> /// </summary> /// <param name="app">Unity Application object</param> /// <param name="args">Workflow event arguments</param> public void OnWorkflowScriptExecute(Application app, WorkflowEventArgs args) // public void OnWorkflowScriptExecute(Application app, WorkflowEventArgs args=null) { try { // Initialize global settings IntializeScript(ref app, ref args); KeywordType ktwBatchType = _currentDocument.DocumentType.KeywordRecordTypes.FindKeywordType(gParamBatchType); string strBatchType = ""; if (ktwBatchType != null) { KeywordRecord keyRecBatchType = _currentDocument.KeywordRecords.Find(ktwBatchType); if (keyRecBatchType != null) { Keyword kwdBatchType = keyRecBatchType.Keywords.Find(ktwBatchType); if (kwdBatchType != null) { strBatchType = kwdBatchType.ToString(); } } } if (strBatchType == "") { throw new Exception(string.Format("{0} is blank.", gParamBatchType)); } KeywordType ktwTranCode = _currentDocument.DocumentType.KeywordRecordTypes.FindKeywordType(gParamTranCode); string strTranCode = ""; if (ktwTranCode != null) { KeywordRecord keyRecTranCode = _currentDocument.KeywordRecords.Find(ktwTranCode); if (keyRecTranCode != null) { Keyword kwdTranCode = keyRecTranCode.Keywords.Find(ktwTranCode); if (kwdTranCode != null) { strTranCode = kwdTranCode.ToString(); } } } KeywordType ktwLicType = _currentDocument.DocumentType.KeywordRecordTypes.FindKeywordType(gParamLicType); string strLicType = ""; if (ktwLicType != null) { KeywordRecord keyRecLicType = _currentDocument.KeywordRecords.Find(ktwLicType); if (keyRecLicType != null) { Keyword kwdLicType = keyRecLicType.Keywords.Find(ktwLicType); if (kwdLicType != null) { strLicType = kwdLicType.ToString(); } } } if (strLicType == "") { throw new Exception(string.Format("{0} is blank.", gParamLicType)); } //access Config Item for OnBase User string gUSER = ""; if (app.Configuration.TryGetValue("OnBaseUser", out gUSER)) { } //access Config Item for OnBase Password string gPASS = ""; if (app.Configuration.TryGetValue("OnBasePassword", out gPASS)) { } /* COMMENT THIS SECTION OUT WHEN MOVING TO PROD */ //access Config Item for OnBase UAT ODBC string gODBCBET = ""; if (app.Configuration.TryGetValue("BETOnBaseMISC", out gODBCBET)) { } string gODBCOnBase = ""; if (app.Configuration.TryGetValue("OnBaseUAT", out gODBCOnBase)) { } /* UNCOMMENT THIS SECTION WHEN MOVING TO PROD * //access Config Item for OnBase PROD ODBC * string gODBCOnBase = ""; * if (app.Configuration.TryGetValue("OnBasePROD", out gODBCOnBase)) * { * } */ string obDocTypeFull = _currentDocument.DocumentType.Name.ToString(); string obDocType = obDocTypeFull.Substring(7); if (strTranCode != "" && strLicType != "") { app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("Trans Code and License Type Present")); //StringBuilder strSql = new StringBuilder(); strSql.Append(@"SELECT users AS USER, proc_unit AS UNIT, last_user AS LASTUSER "); strSql.Append(@" FROM dbo.tbl_ccb "); strSql.Append(@" WHERE license_type = '"); strSql.Append(strLicType); strSql.Append(@"' AND tran_code = '"); strSql.Append(strTranCode); strSql.Append(@"'"); } else if (strLicType != "" && strTranCode == "" && (strBatchType == "BET - CAND. (FEE)" || strBatchType == "BET - CAND. (NON FEE)")) { app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("BET - CAND FEE or NON FEE")); string strMidLicType = strLicType.Substring(1, 2); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("LicType {0}, Doc Type - Description {1}", strMidLicType, obDocType)); //StringBuilder strSql = new StringBuilder(); strSql.Append(@"SELECT users AS USER, proc_unit AS UNIT, last_user AS LASTUSER "); strSql.Append(@" FROM dbo.tbl_ccb "); strSql.Append(@" WHERE license_type = '"); strSql.Append(strMidLicType); strSql.Append(@"' AND description = '"); strSql.Append(obDocType); strSql.Append(@"'"); } else if (strLicType != "" && strTranCode == "") { app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("License Type but NO Trans Code")); strSql.Append(@"SELECT users AS USER, proc_unit AS UNIT, last_user AS LASTUSER "); strSql.Append(@" FROM dbo.tbl_ccb "); strSql.Append(@" WHERE license_type = '"); strSql.Append(strLicType); strSql.Append(@"' AND description = '"); strSql.Append(obDocType); strSql.Append(@"'"); } app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("Sql Query: {0}", strSql.ToString())); string connectionString = string.Format("DSN={0};Uid={1};Pwd={2};", gODBCBET, gUSER, gPASS); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("Connection string: {0}", connectionString)); using (OdbcConnection con = new OdbcConnection(connectionString)) { try { con.Open(); using (OdbcCommand command = new OdbcCommand(strSql.ToString(), con)) using (OdbcDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { //string strUser = ""; string strUnit = ""; List <string> lstUser = new List <string>(); //string strLastUser = ""; reader.Read(); lstUser.Add(reader["USER"].ToString()); //strUser = reader["USER"].ToString(); //strLastUser = reader["LASTUSER"].ToString(); strUnit = reader["UNIT"].ToString(); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("Checking Users")); string strSQLUsers = ""; foreach (string result in lstUser) { if (result != "" && strSQLUsers == "") { strSQLUsers = "'" + strSQLUsers + result + "'"; } else if (result != "" && strSQLUsers != "") { strSQLUsers = strSQLUsers + ",'" + result + "'"; } } app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("users to pass to OnBase " + strSQLUsers)); //StringBuilder strSql = new StringBuilder(); strSql.Append(@"SELECT TOP 1 ua.username AS WFUSER "); strSql.Append(@" FROM hsi.useraccount ua "); strSql.Append(@" LEFT OUTER JOIN (SELECT usernum FROM hsi.itemlcxuser "); strSql.Append(@" WHERE hsi.itemlcxuser.lcnum = "); strSql.Append(gLCNUM); strSql.Append(@" ) ilcu ON us.usernum = ilcu.usernum "); strSql.Append(@" WHERE ua.username IN("); strSql.Append(strSQLUsers); strSql.Append(@"'"); string connectionStringOnBase = string.Format("DSN={0};Uid={1};Pwd={2};", gODBCOnBase, gUSER, gPASS); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("Connection string: {0}", connectionStringOnBase)); using (OdbcConnection conOnBase = new OdbcConnection(connectionStringOnBase)) { try { conOnBase.Open(); using (OdbcCommand commandOnBase = new OdbcCommand(strSql.ToString(), conOnBase)) using (OdbcDataReader readerOnBase = commandOnBase.ExecuteReader()) { if (readerOnBase.HasRows) { strWFUser = readerOnBase["WFUSER"].ToString(); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("WFUser set to " + strWFUser)); } } } catch (Exception ex) { throw new ApplicationException("Error during database operations!", ex); } finally { if (conOnBase.State == ConnectionState.Open) { conOnBase.Close(); } } } Keyword kwdUnit = null; if (!String.IsNullOrEmpty(strUnit)) { KeywordType kwtUnit = app.Core.KeywordTypes.Find(gSaveToAssignedProcUnit); if (kwtUnit != null) { kwdUnit = CreateKeywordHelper(kwtUnit, strUnit); } } Keyword kwdUser = null; if (!String.IsNullOrEmpty(strWFUser)) { KeywordType kwtUser = app.Core.KeywordTypes.Find(gSaveToAssignedProc); if (kwtUser != null) { kwdUser = CreateKeywordHelper(kwtUser, strWFUser); } } using (DocumentLock documentLock = _currentDocument.LockDocument()) { // Ensure lock was obtained if (documentLock.Status != DocumentLockStatus.LockObtained) { throw new Exception("Document lock not obtained"); } // Create keyword modifier object to hold keyword changes KeywordModifier keyModifier = _currentDocument.CreateKeywordModifier(); // Add update keyword call to keyword modifier object //Note Overloads available for use //(I.E.): keyModifier.AddKeyword(keywordTypeName,keywordValue) if (kwdUnit != null) { keyModifier.AddKeyword(kwdUnit); } if (kwdUser != null) { keyModifier.AddKeyword(kwdUser); } // Apply keyword change to the document keyModifier.ApplyChanges(); string output = String.Format("Keyword: '{0}' Value: '{1}', {3}added to Document {2}.", gSaveToAssignedProcUnit, strUnit, _currentDocument.ID, Environment.NewLine); //Output the results to the OnBase Diagnostics Console app.Diagnostics.WriteIf(Hyland.Unity.Diagnostics.DiagnosticsLevel.Verbose, output); string output2 = String.Format("Keyword: '{0}' Value: '{1}', {3}added to Document {2}.", gSaveToAssignedProc, strWFUser, _currentDocument.ID, Environment.NewLine); app.Diagnostics.WriteIf(Hyland.Unity.Diagnostics.DiagnosticsLevel.Verbose, output2); } } else { throw new Exception(string.Format("No records found in database for {0}='{1}'", gParamBatchType, strBatchType)); } } } catch (Exception ex) { throw new ApplicationException("Error during database operations!", ex); } finally { if (con.State == ConnectionState.Open) { con.Close(); } } } } catch (Exception ex) { // Handle exceptions and log to Diagnostics Console and document history HandleException(ex, ref app, ref args); } finally { // Log script execution end app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Info, string.Format("End Script - [{0}]", ScriptName)); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad groups to which keywords are /// added.</param> public void Run(AdWordsUser user, long adGroupId) { // Get the MutateJobService. MutateJobService mutateJobService = (MutateJobService)user.GetService( AdWordsService.v201506.MutateJobService); const int RETRY_INTERVAL = 30; const int RETRIES_COUNT = 30; const int KEYWORD_NUMBER = 100; const string INDEX_REGEX = "operations\\[(\\d+)\\].operand"; List <Operation> operations = new List <Operation>(); // Create AdGroupCriterionOperation to add keywords. for (int i = 0; i < KEYWORD_NUMBER; i++) { Keyword keyword = new Keyword(); keyword.text = string.Format("mars cruise {0}", i); keyword.matchType = KeywordMatchType.BROAD; BiddableAdGroupCriterion criterion = new BiddableAdGroupCriterion(); criterion.adGroupId = adGroupId; criterion.criterion = keyword; AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation(); adGroupCriterionOperation.@operator = Operator.ADD; adGroupCriterionOperation.operand = criterion; operations.Add(adGroupCriterionOperation); } BulkMutateJobPolicy policy = new BulkMutateJobPolicy(); // You can specify up to 3 job IDs that must successfully complete before // this job can be processed. policy.prerequisiteJobIds = new long[] {}; SimpleMutateJob job = mutateJobService.mutate(operations.ToArray(), policy); // Wait for the job to complete. bool completed = false; int retryCount = 0; Console.WriteLine("Retrieving job status..."); while (completed == false && retryCount < RETRIES_COUNT) { BulkMutateJobSelector selector = new BulkMutateJobSelector(); selector.jobIds = new long[] { job.id }; try { Job[] allJobs = mutateJobService.get(selector); if (allJobs != null && allJobs.Length > 0) { job = (SimpleMutateJob)allJobs[0]; if (job.status == BasicJobStatus.COMPLETED || job.status == BasicJobStatus.FAILED) { completed = true; break; } else { Console.WriteLine("{0}: Current status is {1}, waiting {2} seconds to retry...", retryCount, job.status, RETRY_INTERVAL); Thread.Sleep(RETRY_INTERVAL * 1000); retryCount++; } } } catch (Exception ex) { throw new System.ApplicationException("Failed to fetch simple mutate job with " + "id = {0}.", ex); } } if (job.status == BasicJobStatus.COMPLETED) { // Handle cases where the job completed. // Create the job selector. BulkMutateJobSelector selector = new BulkMutateJobSelector(); selector.jobIds = new long[] { job.id }; // Get the job results. JobResult jobResult = mutateJobService.getResult(selector); if (jobResult != null) { SimpleMutateResult results = (SimpleMutateResult)jobResult.Item; if (results != null) { // Display the results. if (results.results != null) { for (int i = 0; i < results.results.Length; i++) { Operand operand = results.results[i]; Console.WriteLine("Operation {0} - {1}", i, (operand.Item is PlaceHolder) ? "FAILED" : "SUCCEEDED"); } } // Display the errors. if (results.errors != null) { foreach (ApiError apiError in results.errors) { Match match = Regex.Match(apiError.fieldPath, INDEX_REGEX, RegexOptions.IgnoreCase); string index = (match.Success)? match.Groups[1].Value : "???"; Console.WriteLine("Operation index {0} failed due to reason: '{1}', " + "trigger: '{2}'", index, apiError.errorString, apiError.trigger); } } } } Console.WriteLine("Job completed successfully!"); } else if (job.status == BasicJobStatus.FAILED) { // Handle the cases where job failed. Console.WriteLine("Job failed with reason: " + job.failureReason); } else if (job.status == BasicJobStatus.PROCESSING || job.status == BasicJobStatus.PENDING) { // Handle the cases where job didn't complete after wait period. Console.WriteLine("Job did not complete in {0} secconds.", RETRY_INTERVAL * RETRIES_COUNT); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">ID of the ad group from which keywords are /// retrieved.</param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupCriterionService. AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)user.GetService( AdWordsService.v201506.AdGroupCriterionService); // Create a selector. Selector selector = new Selector(); selector.fields = new string[] { "Id", "KeywordMatchType", "KeywordText", "CriteriaType" }; // Select only keywords. Predicate criteriaPredicate = new Predicate(); criteriaPredicate.field = "CriteriaType"; criteriaPredicate.@operator = PredicateOperator.IN; criteriaPredicate.values = new string[] { "KEYWORD" }; // Restrict search to an ad group. Predicate adGroupPredicate = new Predicate(); adGroupPredicate.field = "AdGroupId"; adGroupPredicate.@operator = PredicateOperator.EQUALS; adGroupPredicate.values = new string[] { adGroupId.ToString() }; selector.predicates = new Predicate[] { adGroupPredicate, criteriaPredicate }; // Set the selector paging. selector.paging = new Paging(); int offset = 0; int pageSize = 500; AdGroupCriterionPage page = new AdGroupCriterionPage(); try { do { selector.paging.startIndex = offset; selector.paging.numberResults = pageSize; // Get the keywords. page = adGroupCriterionService.get(selector); // Display the results. if (page != null && page.entries != null) { int i = offset; foreach (AdGroupCriterion adGroupCriterion in page.entries) { bool isNegative = (adGroupCriterion is NegativeAdGroupCriterion); // If you are retrieving multiple type of criteria, then you may // need to check for // // if (adGroupCriterion is Keyword) { ... } // // to identify the criterion type. Keyword keyword = (Keyword)adGroupCriterion.criterion; string keywordType = isNegative ? "Negative keyword" : "Keyword"; Console.WriteLine("{0}) {1} with text = '{2}', matchtype = '{3}', ID = '{4}' and " + "criteria type = '{5}' was found.", i + 1, keywordType, keyword.text, keyword.matchType, keyword.id, keyword.CriterionType); i++; } } offset += pageSize; } while (offset < page.totalNumEntries); Console.WriteLine("Number of keywords found: {0}", page.totalNumEntries); } catch (Exception ex) { throw new System.ApplicationException("Failed to retrieve keywords.", ex); } }
public Directive(Keyword keyword, string content) { this.Keyword = keyword; this.Content = content; }
public async Task RegistrarKeyword(Keyword keyword) { await _appContext.Keyword.AddAsync(keyword); await _appContext.SaveChangesAsync(); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">Id of the campaign to which targeting criteria /// are added.</param> public void Run(AdWordsUser user, long campaignId) { // Get the CampaignCriterionService. CampaignCriterionService campaignCriterionService = (CampaignCriterionService)user.GetService( AdWordsService.v201502.CampaignCriterionService); // Create language criteria. // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html // for a detailed list of language codes. Language language1 = new Language(); language1.id = 1002; // French CampaignCriterion languageCriterion1 = new CampaignCriterion(); languageCriterion1.campaignId = campaignId; languageCriterion1.criterion = language1; Language language2 = new Language(); language2.id = 1005; // Japanese CampaignCriterion languageCriterion2 = new CampaignCriterion(); languageCriterion2.campaignId = campaignId; languageCriterion2.criterion = language2; // Target Tier 3 income group near Miami, Florida. LocationGroups incomeLocationGroups = new LocationGroups(); IncomeOperand incomeOperand = new IncomeOperand(); // Tiers are numbered 1-10, and represent 10% segments of earners. // For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. // Tiers 6 through 10 are grouped into TIER_6_TO_10. incomeOperand.tier = IncomeTier.TIER_3; GeoTargetOperand geoTargetOperand1 = new GeoTargetOperand(); geoTargetOperand1.locations = new long[] { 1015116 }; // Miami, FL. incomeLocationGroups.matchingFunction = new Function(); incomeLocationGroups.matchingFunction.lhsOperand = new FunctionArgumentOperand[] { incomeOperand }; incomeLocationGroups.matchingFunction.@operator = FunctionOperator.AND; incomeLocationGroups.matchingFunction.rhsOperand = new FunctionArgumentOperand[] { geoTargetOperand1 }; CampaignCriterion locationGroupCriterion1 = new CampaignCriterion(); locationGroupCriterion1.campaignId = campaignId; locationGroupCriterion1.criterion = incomeLocationGroups; // Target places of interest near Downtown Miami, Florida. LocationGroups interestLocationGroups = new LocationGroups(); PlacesOfInterestOperand placesOfInterestOperand = new PlacesOfInterestOperand(); placesOfInterestOperand.category = PlacesOfInterestOperandCategory.DOWNTOWN; GeoTargetOperand geoTargetOperand2 = new GeoTargetOperand(); geoTargetOperand2.locations = new long[] { 1015116 }; // Miami, FL. interestLocationGroups.matchingFunction = new Function(); interestLocationGroups.matchingFunction.lhsOperand = new FunctionArgumentOperand[] { placesOfInterestOperand }; interestLocationGroups.matchingFunction.@operator = FunctionOperator.AND; interestLocationGroups.matchingFunction.rhsOperand = new FunctionArgumentOperand[] { geoTargetOperand2 }; CampaignCriterion locationGroupCriterion2 = new CampaignCriterion(); locationGroupCriterion2.campaignId = campaignId; locationGroupCriterion2.criterion = interestLocationGroups; // Distance targeting. Area of 10 miles around targets above. ConstantOperand radius = new ConstantOperand(); radius.type = ConstantOperandConstantType.DOUBLE; radius.unit = ConstantOperandUnit.MILES; radius.doubleValue = 10.0; LocationExtensionOperand distance = new LocationExtensionOperand(); distance.radius = radius; LocationGroups radiusLocationGroups = new LocationGroups(); radiusLocationGroups.matchingFunction = new Function(); radiusLocationGroups.matchingFunction.@operator = FunctionOperator.IDENTITY; radiusLocationGroups.matchingFunction.lhsOperand = new FunctionArgumentOperand[] { distance }; CampaignCriterion locationGroupCriterion3 = new CampaignCriterion(); locationGroupCriterion3.campaignId = campaignId; locationGroupCriterion3.criterion = radiusLocationGroups; // Create location criteria. // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html // for a detailed list of country codes. Location location1 = new Location(); location1.id = 2840; // USA CampaignCriterion locationCriterion1 = new CampaignCriterion(); locationCriterion1.campaignId = campaignId; locationCriterion1.criterion = location1; Location location2 = new Location(); location2.id = 2392; // Japan CampaignCriterion locationCriterion2 = new CampaignCriterion(); locationCriterion2.campaignId = campaignId; locationCriterion2.criterion = location2; // Add a negative campaign keyword. NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion(); negativeCriterion.campaignId = campaignId; Keyword keyword = new Keyword(); keyword.matchType = KeywordMatchType.BROAD; keyword.text = "jupiter cruise"; negativeCriterion.criterion = keyword; CampaignCriterion[] criteria = new CampaignCriterion[] { languageCriterion1, languageCriterion2, locationCriterion1, locationCriterion2, negativeCriterion, locationGroupCriterion1, locationGroupCriterion2, locationGroupCriterion3 }; List <CampaignCriterionOperation> operations = new List <CampaignCriterionOperation>(); foreach (CampaignCriterion criterion in criteria) { CampaignCriterionOperation operation = new CampaignCriterionOperation(); operation.@operator = Operator.ADD; operation.operand = criterion; operations.Add(operation); } try { // Set the campaign targets. CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray()); if (retVal != null && retVal.value != null) { // Display campaign targets. foreach (CampaignCriterion criterion in retVal.value) { Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" + " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId); } } } catch (Exception e) { throw new System.ApplicationException("Failed to set Campaign criteria.", e); } }
public IList <IKeyword> GetAllKeywords() { return(Keyword.ToList <IKeyword>()); }
public KeywordAttribute(Keyword keyword) { this.Keyword = keyword; }
public Armor(OGLContext context, String name, String description, Price price, int baseAC, double weight, int strengthrequired = 0, bool stealthdisadvantage = false, Keyword kw1 = null, Keyword kw2 = null, Keyword kw3 = null, Keyword kw4 = null, Keyword kw5 = null, Keyword kw6 = null, Keyword kw7 = null) : base(context, name, description, price, weight, kw1, kw2, kw3, kw4, kw5, kw6, kw7) { BaseAC = baseAC; StrengthRequired = strengthrequired; StealthDisadvantage = stealthdisadvantage; }
public void ParsesSimple() { //corrected grammar from week 5 exercise 3 Parser p = new Parser(); NonTerminal L = new NonTerminal("L"); NonTerminal Q = new NonTerminal("Q"); NonTerminal R = new NonTerminal("R"); NonTerminal Q2 = new NonTerminal("Q2"); NonTerminal R2 = new NonTerminal("R2"); Keyword a = new Keyword("a"); Keyword b = new Keyword("b"); Keyword c = new Keyword("c"); List <Token> prod1 = new List <Token>(); prod1.Add(R); prod1.Add(a); p.addProduction(L, prod1); List <Token> prod2 = new List <Token>(); prod2.Add(Q); prod2.Add(b); prod2.Add(a); p.addProduction(L, prod2); List <Token> prod3 = new List <Token>(); prod3.Add(b); prod3.Add(Q2); p.addProduction(Q, prod3); List <Token> prod4 = new List <Token>(); prod4.Add(b); prod4.Add(c); p.addProduction(Q2, prod4); List <Token> prod5 = new List <Token>(); prod5.Add(c); p.addProduction(Q2, prod5); List <Token> prod6 = new List <Token>(); prod6.Add(a); prod6.Add(b); prod6.Add(a); prod6.Add(R2); p.addProduction(R, prod6); List <Token> prod7 = new List <Token>(); prod7.Add(c); prod7.Add(a); prod7.Add(b); prod7.Add(a); prod7.Add(R2); p.addProduction(R, prod7); List <Token> prod8 = new List <Token>(); prod8.Add(b); prod8.Add(c); prod8.Add(R2); p.addProduction(R2, prod8); List <Token> prod9 = new List <Token>(); p.addProduction(R2, prod9); List <Token> parseThese = new List <Token>(); parseThese.Add(a); parseThese.Add(b); parseThese.Add(a); parseThese.Add(b); parseThese.Add(c); parseThese.Add(b); parseThese.Add(c); parseThese.Add(a); p.setStartSymbol(L); p.prepareForParsing(); SyntaxTree parsed = p.parse(parseThese); Assert.AreEqual(L, parsed.root.token); Assert.AreEqual(R, parsed.root.children[0].token); Assert.AreEqual(a, parsed.root.children[0].children[0].token); Assert.AreEqual(b, parsed.root.children[0].children[1].token); Assert.AreEqual(a, parsed.root.children[0].children[2].token); Assert.AreEqual(R2, parsed.root.children[0].children[3].token); Assert.AreEqual(b, parsed.root.children[0].children[3].children[0].token); Assert.AreEqual(c, parsed.root.children[0].children[3].children[1].token); Assert.AreEqual(R2, parsed.root.children[0].children[3].children[2].token); Assert.AreEqual(b, parsed.root.children[0].children[3].children[2].children[0].token); Assert.AreEqual(c, parsed.root.children[0].children[3].children[2].children[1].token); Assert.AreEqual(a, parsed.root.children[1].token); }
protected void EmitValue(object value, CljILGen ilg) { bool partial = true; if (value == null) { ilg.Emit(OpCodes.Ldnull); } else if (value is String) { ilg.Emit(OpCodes.Ldstr, (String)value); } else if (value is Boolean) { ilg.EmitBoolean((Boolean)value); ilg.Emit(OpCodes.Box, typeof(bool)); } else if (value is Int32) { ilg.EmitInt((int)value); ilg.Emit(OpCodes.Box, typeof(int)); } else if (value is Int64) { ilg.EmitLong((long)value); ilg.Emit(OpCodes.Box, typeof(long)); } else if (value is Double) { ilg.EmitDouble((double)value); ilg.Emit(OpCodes.Box, typeof(double)); } else if (value is Char) { ilg.EmitChar((char)value); ilg.Emit(OpCodes.Box, typeof(char)); } else if (value is Type) { Type t = (Type)value; if (t.IsValueType) { ilg.EmitType(t); } else { //ilg.EmitString(Compiler.DestubClassName(((Type)value).FullName)); ilg.EmitString(((Type)value).FullName); ilg.EmitCall(Compiler.Method_RT_classForName); } } else if (value is Symbol) { Symbol sym = (Symbol)value; if (sym.Namespace == null) { ilg.EmitNull(); } else { ilg.EmitString(sym.Namespace); } ilg.EmitString(sym.Name); ilg.EmitCall(Compiler.Method_Symbol_intern2); } else if (value is Keyword) { Keyword keyword = (Keyword)value; if (keyword.Namespace == null) { ilg.EmitNull(); } else { ilg.EmitString(keyword.Namespace); } ilg.EmitString(keyword.Name); ilg.EmitCall(Compiler.Method_RT_keyword); } else if (value is Var) { Var var = (Var)value; ilg.EmitString(var.Namespace.Name.ToString()); ilg.EmitString(var.Symbol.Name.ToString()); ilg.EmitCall(Compiler.Method_RT_var2); } else if (value is IType) { IPersistentVector fields = (IPersistentVector)Reflector.InvokeStaticMethod(value.GetType(), "getBasis", Type.EmptyTypes); for (ISeq s = RT.seq(fields); s != null; s = s.next()) { Symbol field = (Symbol)s.first(); Type k = Compiler.TagType(Compiler.TagOf(field)); object val = Reflector.GetInstanceFieldOrProperty(value, Compiler.munge(field.Name)); EmitValue(val, ilg); if (k.IsPrimitive) { ilg.Emit(OpCodes.Castclass, k); } } ConstructorInfo cinfo = value.GetType().GetConstructors()[0]; ilg.EmitNew(cinfo); } else if (value is IRecord) { //MethodInfo[] minfos = value.GetType().GetMethods(BindingFlags.Static | BindingFlags.Public); EmitValue(PersistentArrayMap.create((IDictionary)value), ilg); MethodInfo createMI = value.GetType().GetMethod("create", BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Standard, new Type[] { typeof(IPersistentMap) }, null); ilg.EmitCall(createMI); } else if (value is IPersistentMap) { IPersistentMap map = (IPersistentMap)value; List <object> entries = new List <object>(map.count() * 2); foreach (IMapEntry entry in map) { entries.Add(entry.key()); entries.Add(entry.val()); } EmitListAsObjectArray(entries, ilg); ilg.EmitCall(Compiler.Method_RT_map); } else if (value is IPersistentVector) { IPersistentVector args = (IPersistentVector)value; if (args.count() <= Tuple.MAX_SIZE) { for (int i = 0; i < args.count(); i++) { EmitValue(args.nth(i), ilg); } ilg.Emit(OpCodes.Call, Compiler.Methods_CreateTuple[args.count()]); } else { EmitListAsObjectArray(value, ilg); ilg.EmitCall(Compiler.Method_RT_vector); } } else if (value is PersistentHashSet) { ISeq vs = RT.seq(value); if (vs == null) { ilg.EmitFieldGet(Compiler.Method_PersistentHashSet_EMPTY); } else { EmitListAsObjectArray(vs, ilg); ilg.EmitCall(Compiler.Method_PersistentHashSet_create); } } else if (value is ISeq || value is IPersistentList) { EmitListAsObjectArray(value, ilg); ilg.EmitCall(Compiler.Method_PersistentList_create); } else if (value is Regex) { ilg.EmitString(((Regex)value).ToString()); ilg.EmitNew(Compiler.Ctor_Regex_1); } else { string cs = null; try { cs = RT.printString(value); } catch (Exception) { throw new InvalidOperationException(String.Format("Can't embed object in code, maybe print-dup not defined: {0}", value)); } if (cs.Length == 0) { throw new InvalidOperationException(String.Format("Can't embed unreadable object in code: " + value)); } if (cs.StartsWith("#<")) { throw new InvalidOperationException(String.Format("Can't embed unreadable object in code: " + cs)); } ilg.EmitString(cs); ilg.EmitCall(Compiler.Method_RT_readString); partial = false; } if (partial) { if (value is IObj && RT.count(((IObj)value).meta()) > 0) { ilg.Emit(OpCodes.Castclass, typeof(IObj)); Object m = ((IObj)value).meta(); EmitValue(Compiler.ElideMeta(m), ilg); ilg.Emit(OpCodes.Castclass, typeof(IPersistentMap)); ilg.Emit(OpCodes.Callvirt, Compiler.Method_IObj_withMeta); } } }
/// <summary> /// Callers use this to check if they should be logging. /// </summary> static internal bool IsEnabled(Keyword flag, Level level) { return(EventProvider.IsEnabled(flag, level)); }
internal void EmitKeyword(CljILGen ilg, Keyword kw) { int i = (int)Keywords.valAt(kw); EmitConstant(ilg, i, kw); }
public Dynamic.IKeyword GetKeyword(string categoryUriToLookIn, string keywordName) { //Create filter to retrieve all keywords in a taxonomy CompositeFilter compFilter = new CompositeFilter(); compFilter.DepthFiltering(DepthFilter.UnlimitedDepth, DepthFilter.FilterUp); compFilter.DepthFiltering(DepthFilter.UnlimitedDepth, DepthFilter.FilterDown); //Get keywords in taxonomy (hierarchically) IEnumerable <Keyword> taxonomy = null; try { //Ugly way to see if a taxonomy exists. Alternative is to loop through all taxonomys in Tridion and check if the categoryUriToLookIn exists... taxonomy = TaxonomyFactory.GetTaxonomyKeywords(categoryUriToLookIn, compFilter, new TaxonomyHierarchyFormatter()).KeywordChildren.Cast <Keyword>(); } catch (Exception) { //TODO: Trace return(null); } //Search in taxonomy Keyword foundKeyword = null; foreach (var currentKeyword in taxonomy) { string currentKeywordName = currentKeyword.KeywordName; if (currentKeywordName != keywordName) { foundKeyword = recursive(currentKeyword.KeywordChildren.Cast <Keyword>().ToList(), keywordName); } else { foundKeyword = currentKeyword; } if (foundKeyword != null) { Dynamic.Keyword returnKeyword = new Dynamic.Keyword(); Keyword par = foundKeyword.ParentKeyword; do { Dynamic.Keyword newParentKeyword = new Dynamic.Keyword(); newParentKeyword.Id = par.KeywordUri; newParentKeyword.TaxonomyId = par.TaxonomyUri; newParentKeyword.Title = par.KeywordName; returnKeyword.ParentKeywords.Add(newParentKeyword); //Add the parentkeyword to the list par = par.ParentKeyword; } while (par != null); //Add remaining properties to the returnKeyword returnKeyword.Id = foundKeyword.KeywordUri; returnKeyword.TaxonomyId = foundKeyword.TaxonomyUri; returnKeyword.Title = foundKeyword.KeywordName; return(returnKeyword); } } return(null); }
//(case* expr shift mask default map<minhash, [test then]> table-type test-type skip-check?) //prepared by case macro and presumed correct //case macro binds actual expr in let so expr is always a local, //no need to worry about multiple evaluation public Expr Parse(ParserContext pcon, object frm) { ISeq form = (ISeq)frm; if (pcon.Rhc == RHC.Eval) { return(Compiler.Analyze(pcon, RT.list(RT.list(Compiler.FnOnceSym, PersistentVector.EMPTY, form)), "case__" + RT.nextID())); } PersistentVector args = PersistentVector.create(form.next()); object exprForm = args.nth(0); int shift = Util.ConvertToInt(args.nth(1)); int mask = Util.ConvertToInt(args.nth(2)); object defaultForm = args.nth(3); IPersistentMap caseMap = (IPersistentMap)args.nth(4); Keyword switchType = (Keyword)args.nth(5); Keyword testType = (Keyword)args.nth(6); IPersistentSet skipCheck = RT.count(args) < 8 ? null : (IPersistentSet)args.nth(7); ISeq keys = RT.keys(caseMap); int low = Util.ConvertToInt(RT.first(keys)); int high = Util.ConvertToInt(RT.nth(keys, RT.count(keys) - 1)); LocalBindingExpr testexpr = (LocalBindingExpr)Compiler.Analyze(pcon.SetRhc(RHC.Expression), exprForm); SortedDictionary <int, Expr> tests = new SortedDictionary <int, Expr>(); Dictionary <int, Expr> thens = new Dictionary <int, Expr>(); foreach (IMapEntry me in caseMap) { int minhash = Util.ConvertToInt(me.key()); object pair = me.val(); // [test-val then-expr] object first = RT.first(pair); Expr testExpr = testType == _intKey ? NumberExpr.Parse(Util.ConvertToInt(first)) : (first == null ? Compiler.NilExprInstance : new ConstantExpr(first)); tests[minhash] = testExpr; Expr thenExpr; thenExpr = Compiler.Analyze(pcon, RT.second(pair)); thens[minhash] = thenExpr; } Expr defaultExpr; defaultExpr = Compiler.Analyze(pcon, defaultForm); return(new CaseExpr( (IPersistentMap)Compiler.SourceSpanVar.deref(), testexpr, shift, mask, low, high, defaultExpr, tests, thens, switchType, testType, skipCheck)); }
private void SetValue(Keyword kw, object value) { switch (kw) { case Keyword.UserID: this.userId = (string)value; return; case Keyword.Password: this.password = (string)value; return; case Keyword.Server: this.server = (string)value; return; case Keyword.Port: this.port = ConvertToUInt(value); return; case Keyword.UseUsageAdvisor: this.useUsageAdvisor = ConvertToBool(value); return; case Keyword.CharacterSet: this.charSet = (string)value; return; case Keyword.Compress: this.compress = ConvertToBool(value); return; case Keyword.PipeName: this.pipeName = (string)value; return; case Keyword.Logging: this.logging = ConvertToBool(value); return; case Keyword.OldSyntax: this.oldSyntax = ConvertToBool(value); if (this.clearing) { break; } Logger.LogWarning("Use Old Syntax is now obsolete. Please see documentation"); return; case Keyword.SharedMemoryName: this.sharedMemName = (string)value; return; case Keyword.AllowBatch: this.allowBatch = ConvertToBool(value); return; case Keyword.ConvertZeroDatetime: this.convertZeroDatetime = ConvertToBool(value); return; case Keyword.PersistSecurityInfo: this.persistSI = ConvertToBool(value); return; case Keyword.Database: this.database = (string)value; return; case Keyword.ConnectionTimeout: this.connectionTimeout = ConvertToUInt(value); return; case Keyword.Pooling: this.pooling = ConvertToBool(value); return; case Keyword.MinimumPoolSize: this.minPoolSize = ConvertToUInt(value); return; case Keyword.MaximumPoolSize: this.maxPoolSize = ConvertToUInt(value); return; case Keyword.ConnectionLifetime: this.connectionLifetime = ConvertToUInt(value); return; case Keyword.DriverType: this.driverType = ConvertToDriverType(value); return; case Keyword.Protocol: this.protocol = ConvertToProtocol(value); return; case Keyword.ConnectionReset: this.connectionReset = ConvertToBool(value); return; case Keyword.AllowZeroDatetime: this.allowZeroDatetime = ConvertToBool(value); return; case Keyword.UsePerformanceMonitor: this.usePerfMon = ConvertToBool(value); return; case Keyword.ProcedureCacheSize: this.procCacheSize = ConvertToUInt(value); return; case Keyword.IgnorePrepare: this.ignorePrepare = ConvertToBool(value); return; case Keyword.UseSSL: this.useSSL = ConvertToBool(value); return; case Keyword.UseProcedureBodies: this.useProcedureBodies = ConvertToBool(value); return; case Keyword.AutoEnlist: this.autoEnlist = ConvertToBool(value); return; case Keyword.RespectBinaryFlags: this.respectBinaryFlags = ConvertToBool(value); return; case Keyword.TreatBlobsAsUTF8: this.treatBlobsAsUTF8 = ConvertToBool(value); return; case Keyword.BlobAsUTF8IncludePattern: this.blobAsUtf8IncludePattern = (string)value; return; case Keyword.BlobAsUTF8ExcludePattern: this.blobAsUtf8ExcludePattern = (string)value; return; case Keyword.DefaultCommandTimeout: this.defaultCommandTimeout = ConvertToUInt(value); return; case Keyword.TreatTinyAsBoolean: this.treatTinyAsBoolean = ConvertToBool(value); return; case Keyword.AllowUserVariables: this.allowUserVariables = ConvertToBool(value); return; case Keyword.InteractiveSession: this.interactiveSession = ConvertToBool(value); return; case Keyword.FunctionsReturnString: this.functionsReturnString = ConvertToBool(value); break; default: return; } }
/// <summary> /// Implementation of <see cref="IWorkflowScript.OnWorkflowScriptExecute" />. /// <seealso cref="IWorkflowScript" /> /// </summary> /// <param name="app"></param> /// <param name="args"></param> public void OnWorkflowScriptExecute(Hyland.Unity.Application app, Hyland.Unity.WorkflowEventArgs args) { try { app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Info, string.Format("{0} - Start Script - [{1}]", DateTime.Now.ToString(DateTimeFormat), ScriptName)); // Initialize global settings IntializeScript(ref app, ref args); //access Config Item for OnBase User string gUSER = ""; if (app.Configuration.TryGetValue("OnBaseUser", out gUSER)) { } //access Config Item for OnBase Password string gPASS = ""; if (app.Configuration.TryGetValue("OnBasePassword", out gPASS)) { } /* COMMENT THIS SECTION OUT WHEN MOVING TO PROD */ //access Config Item for OnBase UAT ODBC string gUATODBC = ""; if (app.Configuration.TryGetValue("OnBaseUAT", out gUATODBC)) { } //access Config Item for OnBase PROD ODBC string gPRODODBC = ""; if (app.Configuration.TryGetValue("OnBasePROD", out gPRODODBC)) { } LCID = args.Queue.LifeCycle.ID; app.Diagnostics.Write(LCID.ToString()); string connectionString = string.Format("DSN={0};Uid={1};Pwd={2};", gUATODBC, gUSER, gPASS); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("Connection string: {0}", connectionString)); StringBuilder strSql = new StringBuilder(); strSql.Append(@"SELECT hsi.useraccount.username AS USERNAME"); strSql.Append(@" FROM hsi.useraccount inner join hsi.itemlcxuser "); strSql.Append(@" ON hsi.useraccount.usernum = hsi.itemlcxuser.usernum "); strSql.Append(@" WHERE hsi.itemlcxuser.itemnum = '"); strSql.Append(_currentDocument.ID); strSql.Append(@"' AND hsi.itemlcxuser.lcnum = '"); strSql.Append(LCID); strSql.Append(@"'"); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("Sql Query: {0}", strSql.ToString())); using (OdbcConnection con = new OdbcConnection(connectionString)) { try { con.Open(); using (OdbcCommand command = new OdbcCommand(strSql.ToString(), con)) using (OdbcDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { string strUN = ""; reader.Read(); strUN = reader["USERNAME"].ToString(); Keyword kwdUN = null; if (!String.IsNullOrEmpty(strUN)) { KeywordType kwtUN = app.Core.KeywordTypes.Find(gSaveToUserName); if (kwtUN != null) { kwdUN = CreateKeywordHelper(kwtUN, strUN); } } using (DocumentLock documentLock = _currentDocument.LockDocument()) { // Ensure lock was obtained if (documentLock.Status != DocumentLockStatus.LockObtained) { throw new Exception("Document lock not obtained"); } // Create keyword modifier object to hold keyword changes KeywordModifier keyModifier = _currentDocument.CreateKeywordModifier(); // Add update keyword call to keyword modifier object //Note Overloads available for use //(I.E.): keyModifier.AddKeyword(keywordTypeName,keywordValue) if (kwdUN != null) { keyModifier.AddKeyword(kwdUN); } // Apply keyword change to the document keyModifier.ApplyChanges(); string output = String.Format("Keyword: '{0}' Value: '{1}', {3}added to Document {2}.", gSaveToUserName, strUN, _currentDocument.ID, Environment.NewLine); //Output the results to the OnBase Diagnostics Console app.Diagnostics.WriteIf(Hyland.Unity.Diagnostics.DiagnosticsLevel.Verbose, output); documentLock.Release(); } } else { throw new Exception(string.Format("No records found in database for DH {0} and LCID ='{1}'", _currentDocument.ID, LCID)); } } } catch (Exception ex) { // Handle exceptions and log to Diagnostics Console and document history HandleException(ex, ref app, ref args); } finally { // Log script execution end app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Info, string.Format("End Script - [{0}]", ScriptName)); } } } catch (InvalidProgramException ex) { app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Error, string.Format("Invalid Program Exception: {0}", ex.Message)); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Error, string.Format("Stack Trace: {0}", ex.StackTrace)); args.ScriptResult = false; } catch (UnityAPIException ex) { app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Error, string.Format("Unity API Exception: {0}", ex.Message)); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Error, string.Format("Stack Trace: {0}", ex.StackTrace)); args.ScriptResult = false; } catch (Exception ex) { app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Error, string.Format("General Exception: {0}", ex.Message)); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Error, string.Format("Stack Trace: {0}", ex.StackTrace)); args.ScriptResult = false; } finally { app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Info, string.Format("End Script - [{0}]", ScriptName)); } }
public async Task EditDetailsAsync(MediaDetailsInputModel inputModel, string userId, string rootPath) { var media = this.mediaRepository.All() .Include(x => x.Genres) .ThenInclude(x => x.Genre) .Include(x => x.Keywords) .Include(x => x.Images) .FirstOrDefault(x => x.Id == inputModel.Id); bool isAdd = false; // check if the type we try to add create exists if (media == null) { isAdd = true; string qualifiedName = $"CinemaHub.Data.Models.{inputModel.MediaType}, CinemaHub.Data.Models, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"; try { var type = Type.GetType(qualifiedName); media = (Media)Activator.CreateInstance(type); } catch (Exception ex) { throw new Exception($"{inputModel.MediaType} does not exist"); } } // if the media exists replace all its fields, if it does not set the fields media.Title = inputModel.Title ?? media.Title; media.Overview = inputModel.Overview ?? media.Overview; media.IsDetailFull = true; media.Budget = inputModel.Budget; media.Language = inputModel.Language ?? media.Language; media.Runtime = inputModel.Runtime; media.YoutubeTrailerUrl = inputModel.YoutubeTrailerUrl ?? media.YoutubeTrailerUrl; media.ReleaseDate = inputModel.ReleaseDate; var genres = inputModel.Genres.Split(new string[] { ", ", "&" }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim()) .ToList(); var genresDb = media.Genres.ToList(); // Remove all genres which are not in the inputModel's genres and ignore all which are foreach (var genre in genresDb) { if (!genres.Contains(genre.Genre.Name)) { media.Genres.Remove(genre); continue; } genres.Remove(genre.Genre.Name); } // Add all the remaining genres which remained in [genres] foreach (var genre in genres) { var genreDb = this.genreRepository.All().FirstOrDefault(x => x.Name == genre); if (genreDb != null) { media.Genres.Add( new MediaGenre() { Media = media, Genre = genreDb, }); } } // If there are no keywords everything will be removed var keywords = inputModel.Keywords != null ? Newtonsoft.Json.JsonConvert.DeserializeObject <List <KeywordDTO> >(inputModel.Keywords) : new List <KeywordDTO>(); var dbKeywordsIds = media.Keywords.Select(x => x.KeywordId).ToList(); // if [keyword.Id] is 0 it does not exist. foreach (var keyword in keywords) { if (keyword.Id == 0) { var keywordDb = new Keyword() { Name = keyword.Value }; await this.keywordRepository.AddAsync(keywordDb); media.Keywords.Add(new MediaKeyword() { Keyword = keywordDb, Media = media, }); continue; } if (!dbKeywordsIds.Contains(keyword.Id)) { media.Keywords.Add(new MediaKeyword() { KeywordId = keyword.Id, Media = media, }); } dbKeywordsIds.Remove(keyword.Id); // Keywords which are removed from [dbKeywordsIds] won't be deleted } // Delete all the keywords which have remained in [dbKeywordsIds] foreach (var id in dbKeywordsIds) { var mediaKeyword = media.Keywords.FirstOrDefault(x => x.KeywordId == id); this.mediaKeywordRepository.Delete(mediaKeyword); } // Add/Replaces image poster var image = inputModel.PosterImageFile; if (image != null) { try { var mediaImage = await this.DownloadPosterImage(image, rootPath, media); var posterImage = media.Images.FirstOrDefault(x => x.ImageType == ImageType.Poster); if (posterImage != null) { media.Images.Remove(posterImage); } media.Images.Add(mediaImage); } catch (Exception ex) { throw new Exception(ex.Message); } } // [isAdd] is set to true if [inputModel.Id] is null (creating new media) if (isAdd) { await this.mediaRepository.AddAsync(media); } await this.mediaRepository.SaveChangesAsync(); }
public async Task TestKeywordGetSingle() { Keyword keyword = await TMDbClient.GetKeywordAsync(IdHelper.AgentKeyword); await Verify(keyword); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> public void Run(AdWordsUser user) { // Get the TrafficEstimatorService. TrafficEstimatorService trafficEstimatorService = (TrafficEstimatorService)user.GetService( AdWordsService.v201406.TrafficEstimatorService); // Create keywords. Up to 2000 keywords can be passed in a single request. Keyword keyword1 = new Keyword(); keyword1.text = "mars cruise"; keyword1.matchType = KeywordMatchType.BROAD; Keyword keyword2 = new Keyword(); keyword2.text = "cheap cruise"; keyword2.matchType = KeywordMatchType.PHRASE; Keyword keyword3 = new Keyword(); keyword3.text = "cruise"; keyword3.matchType = KeywordMatchType.EXACT; Keyword[] keywords = new Keyword[] { keyword1, keyword2, keyword3 }; // Create a keyword estimate request for each keyword. List <KeywordEstimateRequest> keywordEstimateRequests = new List <KeywordEstimateRequest>(); foreach (Keyword keyword in keywords) { KeywordEstimateRequest keywordEstimateRequest = new KeywordEstimateRequest(); keywordEstimateRequest.keyword = keyword; keywordEstimateRequests.Add(keywordEstimateRequest); } // Create negative keywords. Keyword negativeKeyword1 = new Keyword(); negativeKeyword1.text = "moon walk"; negativeKeyword1.matchType = KeywordMatchType.BROAD; KeywordEstimateRequest negativeKeywordEstimateRequest = new KeywordEstimateRequest(); negativeKeywordEstimateRequest.keyword = negativeKeyword1; negativeKeywordEstimateRequest.isNegative = true; keywordEstimateRequests.Add(negativeKeywordEstimateRequest); // Create ad group estimate requests. AdGroupEstimateRequest adGroupEstimateRequest = new AdGroupEstimateRequest(); adGroupEstimateRequest.keywordEstimateRequests = keywordEstimateRequests.ToArray(); adGroupEstimateRequest.maxCpc = new Money(); adGroupEstimateRequest.maxCpc.microAmount = 1000000; // Create campaign estimate requests. CampaignEstimateRequest campaignEstimateRequest = new CampaignEstimateRequest(); campaignEstimateRequest.adGroupEstimateRequests = new AdGroupEstimateRequest[] { adGroupEstimateRequest }; // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html // for a detailed list of country codes. Location countryCriterion = new Location(); countryCriterion.id = 2840; //US // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html // for a detailed list of language codes. Language languageCriterion = new Language(); languageCriterion.id = 1000; //en campaignEstimateRequest.criteria = new Criterion[] { countryCriterion, languageCriterion }; // Create the selector. TrafficEstimatorSelector selector = new TrafficEstimatorSelector(); selector.campaignEstimateRequests = new CampaignEstimateRequest[] { campaignEstimateRequest }; try { // Get traffic estimates. TrafficEstimatorResult result = trafficEstimatorService.get(selector); // Display traffic estimates. if (result != null && result.campaignEstimates != null && result.campaignEstimates.Length > 0) { CampaignEstimate campaignEstimate = result.campaignEstimates[0]; if (campaignEstimate.adGroupEstimates != null && campaignEstimate.adGroupEstimates.Length > 0) { AdGroupEstimate adGroupEstimate = campaignEstimate.adGroupEstimates[0]; if (adGroupEstimate.keywordEstimates != null) { for (int i = 0; i < adGroupEstimate.keywordEstimates.Length; i++) { Keyword keyword = keywordEstimateRequests[i].keyword; KeywordEstimate keywordEstimate = adGroupEstimate.keywordEstimates[i]; if (keywordEstimateRequests[i].isNegative) { continue; } // Find the mean of the min and max values. long meanAverageCpc = (keywordEstimate.min.averageCpc.microAmount + keywordEstimate.max.averageCpc.microAmount) / 2; double meanAveragePosition = (keywordEstimate.min.averagePosition + keywordEstimate.max.averagePosition) / 2; float meanClicks = (keywordEstimate.min.clicksPerDay + keywordEstimate.max.clicksPerDay) / 2; long meanTotalCost = (keywordEstimate.min.totalCost.microAmount + keywordEstimate.max.totalCost.microAmount) / 2; Console.WriteLine("Results for the keyword with text = '{0}' and match type = " + "'{1}':", keyword.text, keyword.matchType); Console.WriteLine(" Estimated average CPC: {0}", meanAverageCpc); Console.WriteLine(" Estimated ad position: {0:0.00}", meanAveragePosition); Console.WriteLine(" Estimated daily clicks: {0}", meanClicks); Console.WriteLine(" Estimated daily cost: {0}", meanTotalCost); } } } } else { Console.WriteLine("No traffic estimates were returned.\n"); } } catch (Exception ex) { throw new System.ApplicationException("Failed to retrieve traffic estimates.", ex); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> public void Run(AdWordsUser user) { using (TrafficEstimatorService trafficEstimatorService = (TrafficEstimatorService)user.GetService( AdWordsService.v201806.TrafficEstimatorService)) { // Create keywords. Refer to the TrafficEstimatorService documentation for the maximum // number of keywords that can be passed in a single request. // https://developers.google.com/adwords/api/docs/reference/latest/TrafficEstimatorService Keyword keyword1 = new Keyword { text = "mars cruise", matchType = KeywordMatchType.BROAD }; Keyword keyword2 = new Keyword { text = "cheap cruise", matchType = KeywordMatchType.PHRASE }; Keyword keyword3 = new Keyword { text = "cruise", matchType = KeywordMatchType.EXACT }; Keyword[] keywords = new Keyword[] { keyword1, keyword2, keyword3 }; // Create a keyword estimate request for each keyword. List <KeywordEstimateRequest> keywordEstimateRequests = new List <KeywordEstimateRequest>(); foreach (Keyword keyword in keywords) { KeywordEstimateRequest keywordEstimateRequest = new KeywordEstimateRequest { keyword = keyword }; keywordEstimateRequests.Add(keywordEstimateRequest); } // Create negative keywords. Keyword negativeKeyword1 = new Keyword { text = "moon walk", matchType = KeywordMatchType.BROAD }; KeywordEstimateRequest negativeKeywordEstimateRequest = new KeywordEstimateRequest { keyword = negativeKeyword1, isNegative = true }; keywordEstimateRequests.Add(negativeKeywordEstimateRequest); // Create ad group estimate requests. AdGroupEstimateRequest adGroupEstimateRequest = new AdGroupEstimateRequest { keywordEstimateRequests = keywordEstimateRequests.ToArray(), maxCpc = new Money { microAmount = 1000000 } }; // Create campaign estimate requests. CampaignEstimateRequest campaignEstimateRequest = new CampaignEstimateRequest { adGroupEstimateRequests = new AdGroupEstimateRequest[] { adGroupEstimateRequest } }; // Optional: Set additional criteria for filtering estimates. // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html // for a detailed list of country codes. Location countryCriterion = new Location { id = 2840 //US }; // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html // for a detailed list of language codes. Language languageCriterion = new Language { id = 1000 //en }; campaignEstimateRequest.criteria = new Criterion[] { countryCriterion, languageCriterion }; try { // Create the selector. TrafficEstimatorSelector selector = new TrafficEstimatorSelector() { campaignEstimateRequests = new CampaignEstimateRequest[] { campaignEstimateRequest }, // Optional: Request a list of campaign level estimates segmented by platform. platformEstimateRequested = true }; // Get traffic estimates. TrafficEstimatorResult result = trafficEstimatorService.get(selector); // Display traffic estimates. if (result != null && result.campaignEstimates != null && result.campaignEstimates.Length > 0) { CampaignEstimate campaignEstimate = result.campaignEstimates[0]; // Display the campaign level estimates segmented by platform. if (campaignEstimate.platformEstimates != null) { foreach (PlatformCampaignEstimate platformEstimate in campaignEstimate.platformEstimates) { string platformMessage = string.Format("Results for the platform with ID: " + "{0} and name : {1}.", platformEstimate.platform.id, platformEstimate.platform.platformName); DisplayMeanEstimates(platformMessage, platformEstimate.minEstimate, platformEstimate.maxEstimate); } } // Display the keyword estimates. if (campaignEstimate.adGroupEstimates != null && campaignEstimate.adGroupEstimates.Length > 0) { AdGroupEstimate adGroupEstimate = campaignEstimate.adGroupEstimates[0]; if (adGroupEstimate.keywordEstimates != null) { for (int i = 0; i < adGroupEstimate.keywordEstimates.Length; i++) { Keyword keyword = keywordEstimateRequests[i].keyword; KeywordEstimate keywordEstimate = adGroupEstimate.keywordEstimates[i]; if (keywordEstimateRequests[i].isNegative) { continue; } string kwdMessage = string.Format("Results for the keyword with text = '{0}' " + "and match type = '{1}':", keyword.text, keyword.matchType); DisplayMeanEstimates(kwdMessage, keywordEstimate.min, keywordEstimate.max); } } } } else { Console.WriteLine("No traffic estimates were returned."); } trafficEstimatorService.Close(); } catch (Exception e) { throw new System.ApplicationException("Failed to retrieve traffic estimates.", e); } } }
/// <summary> /// Implementation of <see cref="IWorkflowScript.OnWorkflowScriptExecute" />. /// <seealso cref="IWorkflowScript" /> /// </summary> /// <param name="app"></param> /// <param name="args"></param> public void OnWorkflowScriptExecute(Hyland.Unity.Application app, Hyland.Unity.WorkflowEventArgs args) { try { // Initialize global settings IntializeScript(ref app, ref args); //get and clean LicenseType and Case # keywords for passing to LicEase database KeywordType kwtLicNum = _currentDocument.DocumentType.KeywordRecordTypes.FindKeywordType(gSaveToLicNum); string strLicNum = ""; if (kwtLicNum != null) { KeywordRecord keyRecLicNum = _currentDocument.KeywordRecords.Find(kwtLicNum); if (keyRecLicNum != null) { Keyword kwdLicNum = keyRecLicNum.Keywords.Find(kwtLicNum); if (kwdLicNum != null) { strLicNum = CleanSeedKW(kwdLicNum.ToString()); } } } KeywordType kwtLicenseType = _currentDocument.DocumentType.KeywordRecordTypes.FindKeywordType(gSaveToLicType); string strLicenseType = ""; if (kwtLicenseType != null) { KeywordRecord keyRecLicenseType = _currentDocument.KeywordRecords.Find(kwtLicenseType); if (keyRecLicenseType != null) { Keyword kwdLicenseType = keyRecLicenseType.Keywords.Find(kwtLicenseType); if (kwdLicenseType != null) { strLicenseType = CleanSeedKW(kwdLicenseType.ToString()); } } } KeywordType kwtInspectionDate = _currentDocument.DocumentType.KeywordRecordTypes.FindKeywordType(gSaveToInspectionID); string strInspectionID = ""; if (kwtInspectionDate != null) { KeywordRecord keyRecInspectionDate = _currentDocument.KeywordRecords.Find(kwtInspectionDate); if (keyRecInspectionDate != null) { Keyword kwdInspectionDate = keyRecInspectionDate.Keywords.Find(kwtInspectionDate); if (kwdInspectionDate != null) { strInspectionID = CleanSeedKW(kwdInspectionDate.ToString()); } } } if (strInspectionID == "") { throw new Exception(string.Format("Search keyword {0} is blank.", gSaveToInspectionID)); } if (strLicNum == "") { throw new Exception(string.Format("Search keyword {0} is blank.", gSaveToLicNum)); } if (strLicenseType == "") { throw new Exception(string.Format("Search keyword {0} is blank.", gSaveToLicType)); } //access Config Item for LicEase User string gUSER = ""; if (app.Configuration.TryGetValue("LicEaseUser", out gUSER)) { } //access Config Item for LicEase Password string gPASS = ""; if (app.Configuration.TryGetValue("LicEasePassword", out gPASS)) { } /* COMMENT THIS SECTION OUT WHEN MOVING TO PROD */ //access Config Item for LicEase UAT ODBC string gODBC = ""; if (app.Configuration.TryGetValue("LicEaseUAT", out gODBC)) { } /* UNCOMMENT THIS SECTION WHEN MOVING TO PROD * //access Config Item for LicEase PROD ODBC * string gODBC = ""; * if (app.Configuration.TryGetValue("LicEasePROD", out gODBC)) * { * } */ string connectionString = string.Format("DSN={0};Uid={1};Pwd={2};", gODBC, gUSER, gPASS); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("Connection string: {0}", connectionString)); StringBuilder strSql = new StringBuilder(); strSql.Append(@"select a.insp_nbr, b.key_name, a.insp_vst_id, NVL(b.lic_type,a.lic_type) as lic_type, b.indorg_num, b.file_num, NVL(b.lic_num,a.lic_num) as lic_num, a.visit_num, "); strSql.Append(@" a.visit_date, a.insp_typ_desc, a.disposition_kw, b.city_kw, b.county_kw, b.region_kw, a.inspector_name from (SELECT DISTINCT to_char(insp_hist.insp_nbr) as insp_nbr, "); strSql.Append(@" to_char(insp_vst.insp_vst_id) as insp_vst_id, lic.clnt_cde AS lic_type, lic.xent_id AS indorg_num, lic.lic_nbr AS lic_num, to_char(insp_vst.insp_vst_nbr) AS visit_num, "); strSql.Append(@" to_char(insp_vst.insp_vst_strt_dte) AS visit_date, insp_typ_defn.insp_typ_desc, insp_disp_typ.insp_disp_typ_desc AS disposition_kw, "); strSql.Append(@" stff.frst_nme || '.' || stff.surnme AS inspector_name FROM insp_vst, insp_hist, insp_typ_defn, insp_disp_typ, inspr, stff, lic WHERE insp_hist.insp_hist_id = insp_vst.insp_hist_id and insp_vst.insp_vst_id = '"); strSql.Append(strInspectionID); strSql.Append(@"' AND insp_typ_defn.insp_typ_defn_id = insp_hist.insp_typ_defn_id AND insp_vst.inspr_id = inspr.inspr_id AND stff.stff_oper_id = inspr.stff_oper_id"); strSql.Append(@" AND lic.lic_id = insp_hist.lic_id AND insp_disp_typ.insp_disp_typ_id = insp_hist.insp_disp_typ_id ) a, (SELECT DISTINCT '' as insp_nbr, pri_name.key_nme AS key_name, "); strSql.Append(@" '' as insp_vst_id, lic.clnt_cde AS lic_type, to_char(lic.xent_id) AS indorg_num, to_char(lic.file_nbr) AS file_num, lic.lic_nbr AS lic_num, '' AS visit_num, "); strSql.Append(@" '' AS visit_date, '' as insp_typ_desc, '' AS disposition_kw, addr.addr_cty AS city_kw, cnty.cnty_desc AS county_kw, insp_regn.insp_regn_cde AS region_kw, "); strSql.Append(@" '' AS inspector_name FROM insp_vst, insp_hist, clnt, lic, NAME pri_name, insp_regn, inspr_insp_regn, LINK, addr, cnty WHERE lic.lic_nbr = '"); strSql.Append(strLicNum); strSql.Append(@"' and lic.clnt_cde = '"); strSql.Append(strLicenseType); strSql.Append(@"' AND insp_hist.lic_id = lic.lic_id AND pri_name.ent_nme_typ = 'P' AND pri_name.cur_nme_ind = 'Y' AND LINK.nme_id = pri_name.nme_id AND addr.addr_id = LINK.addr_id "); strSql.Append(@" AND LINK.curr_ind = 'Y' AND LINK.insp_regn_id = inspr_insp_regn.insp_regn_id AND lic.xent_id = pri_name.xent_id AND insp_regn.insp_regn_id = inspr_insp_regn.insp_regn_id AND addr.cnty = cnty.cnty AND lic.clnt_cde = clnt.clnt_cde AND clnt.clnt_cde_prnt = '33' and insp_vst.insp_vst_id = (select max(iv.insp_vst_id) from insp_vst iv, insp_hist ih where iv.insp_hist_id = ih.insp_hist_id and ih.lic_id = lic.lic_id)) b where a.indorg_num = b.indorg_num (+)"); app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Verbose, string.Format("Sql Query: {0}", strSql.ToString())); using (OdbcConnection con = new OdbcConnection(connectionString)) { try { con.Open(); using (OdbcCommand command = new OdbcCommand(strSql.ToString(), con)) using (OdbcDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { string strLicType = ""; //string strInspID = ""; string strLicenseNum = ""; string strFileNum = ""; string strKeyName = ""; //string strDBAName = ""; //string strInDorgNum = ""; string strVisitNum = ""; string strDisposition = ""; string strInspDate = ""; string strCity = ""; string strCounty = ""; string strRegion = ""; string strInspector = ""; string strInspNum = ""; string strSubject = ""; //string strInspType = ""; reader.Read(); strLicType = reader["lic_Type"].ToString(); //strInspID = reader["insp_vst_id"].ToString(); strLicenseNum = reader["lic_Num"].ToString(); strFileNum = reader["file_Num"].ToString(); strKeyName = reader["key_Name"].ToString(); //strDBAName = reader["dba_kw"].ToString(); //strInDorgNum = reader["indorg_num"].ToString(); strVisitNum = reader["visit_Num"].ToString(); strInspDate = reader["visit_date"].ToString(); strDisposition = reader["disposition_kw"].ToString(); strCity = reader["city_kw"].ToString(); strInspector = reader["inspector_name"].ToString(); strInspNum = reader["insp_nbr"].ToString(); strSubject = reader["key_Name"].ToString(); //strInspType = reader["insp_typ"].ToString(); if (reader["county_kw"] != DBNull.Value) { strCounty = reader["county_kw"].ToString(); } else { strCounty = "Not Available"; } if (reader["region_kw"] != DBNull.Value) { strRegion = reader["region_kw"].ToString(); } else { strRegion = "Not Available"; } Keyword kwdLicType = null; if (!String.IsNullOrEmpty(strLicType)) { KeywordType kwtLicType = app.Core.KeywordTypes.Find(gSaveToLicType); if (kwtLicType != null) { kwdLicType = CreateKeywordHelper(kwtLicType, strLicType); } } Keyword kwdLicenseNum = null; if (!String.IsNullOrEmpty(strLicenseNum)) { KeywordType kwtLicenseNum = app.Core.KeywordTypes.Find(gSaveToLicNum); if (kwtLicenseNum != null) { kwdLicenseNum = CreateKeywordHelper(kwtLicenseNum, strLicenseNum); } } Keyword kwdFileNum = null; if (!String.IsNullOrEmpty(strFileNum)) { KeywordType kwtFileNum = app.Core.KeywordTypes.Find(gSaveToFileNum); if (kwtFileNum != null) { kwdFileNum = CreateKeywordHelper(kwtFileNum, strFileNum); } } Keyword kwdKeyName = null; if (!String.IsNullOrEmpty(strKeyName)) { KeywordType kwtKeyName = app.Core.KeywordTypes.Find(gSaveToKeyName); if (kwtKeyName != null) { kwdKeyName = CreateKeywordHelper(kwtKeyName, strKeyName); } } Keyword kwdSubject = null; if (!String.IsNullOrEmpty(strSubject)) { KeywordType kwtSubject = app.Core.KeywordTypes.Find(gSaveToSubject); if (kwtSubject != null) { kwdSubject = CreateKeywordHelper(kwtSubject, strSubject); } } /*Keyword kwdDBAName = null; * if (!String.IsNullOrEmpty(strDBAName)) * { * KeywordType kwtDBAName = app.Core.KeywordTypes.Find(gSaveToDBA); * if (kwtDBAName != null) * kwdDBAName = CreateKeywordHelper(kwtDBAName, strDBAName); * } */ Keyword kwdVisitNum = null; if (!String.IsNullOrEmpty(strVisitNum)) { KeywordType kwtVisitNum = app.Core.KeywordTypes.Find(gSaveToVisitNum); if (kwtVisitNum != null) { kwdVisitNum = CreateKeywordHelper(kwtVisitNum, strVisitNum); } } Keyword kwdDisposition = null; if (!String.IsNullOrEmpty(strDisposition)) { KeywordType kwtDisposition = app.Core.KeywordTypes.Find(gSaveToLicType); if (kwtDisposition != null) { kwdDisposition = CreateKeywordHelper(kwtDisposition, strDisposition); } } Keyword kwdCity = null; if (!String.IsNullOrEmpty(strCity)) { KeywordType kwtCity = app.Core.KeywordTypes.Find(gSaveToCity); if (kwtCity != null) { kwdCity = CreateKeywordHelper(kwtCity, strCity); } } Keyword kwdCounty = null; if (!String.IsNullOrEmpty(strCounty)) { KeywordType kwtCounty = app.Core.KeywordTypes.Find(gSaveToCounty); if (kwtCounty != null) { kwdCounty = CreateKeywordHelper(kwtCounty, strCounty); } } Keyword kwdRegion = null; if (!String.IsNullOrEmpty(strRegion)) { KeywordType kwtRegion = app.Core.KeywordTypes.Find(gSaveToRegion); if (kwtRegion != null) { kwdRegion = CreateKeywordHelper(kwtRegion, strRegion); } } Keyword kwdInspector = null; if (!String.IsNullOrEmpty(strInspector)) { KeywordType kwtInspector = app.Core.KeywordTypes.Find(gSaveToInspectorName); if (kwtInspector != null) { kwdInspector = CreateKeywordHelper(kwtInspector, strInspector); } } Keyword kwdInspectorID = null; if (!String.IsNullOrEmpty(strInspID)) { KeywordType kwtInspNum = app.Core.KeywordTypes.Find(gSaveToInspectionID); if (kwtInspNum != null) { kwdInspectorID = CreateKeywordHelper(kwtInspNum, strInspID); } } Keyword kwdInspTypeDesc = null; if (!String.IsNullOrEmpty(strInspDate)) { KeywordType kwtInspTypeDesc = app.Core.KeywordTypes.Find(gSaveToInspectVisitDate); if (kwtInspTypeDesc != null) { kwdInspTypeDesc = CreateKeywordHelper(kwtInspTypeDesc, strInspDate); } } using (DocumentLock documentLock = _currentDocument.LockDocument()) { // Ensure lock was obtained if (documentLock.Status != DocumentLockStatus.LockObtained) { throw new Exception("Document lock not obtained"); } // Create keyword modifier object to hold keyword changes KeywordModifier keyModifier = _currentDocument.CreateKeywordModifier(); // Add update keyword call to keyword modifier object //Note Overloads available for use //(I.E.): keyModifier.AddKeyword(keywordTypeName,keywordValue) if (kwdLicType != null) { keyModifier.AddKeyword(kwdLicType); } if (kwdLicenseNum != null) { keyModifier.AddKeyword(kwdLicenseNum); } if (kwdInspectorID != null) { keyModifier.AddKeyword(kwdInspectorID); } if (kwdFileNum != null) { keyModifier.AddKeyword(kwdFileNum); } if (kwdKeyName != null) { keyModifier.AddKeyword(kwdKeyName); } //if (kwdDBAName != null) keyModifier.AddKeyword(kwdDBAName); if (kwdVisitNum != null) { keyModifier.AddKeyword(kwdVisitNum); } if (kwdDisposition != null) { keyModifier.AddKeyword(kwdDisposition); } if (kwdCity != null) { keyModifier.AddKeyword(kwdCity); } if (kwdCounty != null) { keyModifier.AddKeyword(kwdCounty); } if (kwdRegion != null) { keyModifier.AddKeyword(kwdRegion); } if (kwdInspector != null) { keyModifier.AddKeyword(kwdInspector); } if (kwdInspTypeDesc != null) { keyModifier.AddKeyword(kwdInspTypeDesc); } if (kwdSubject != null) { keyModifier.AddKeyword(kwdSubject); } // Apply keyword change to the document keyModifier.ApplyChanges(); string output = String.Format("Keyword: '{0}' Value: '{1}', {29}Keyword: '{2}' Value: '{3}', {29}Keyword: '{4}' Value: '{5}', {29}Keyword: '{6}' Value: '{7}'," + "{29}Keyword: '{8}' Value: '{9}', {29}Keyword: '{10}' Value: '{11}', {29}Keyword: '{12}' Value: '{13}', {29}Keyword: '{14}' Value: '{15}', {29}Keyword: '{16}' Value: '{17}'," + "{29}Keyword: '{18}' Value: '{19}', {29}Keyword: '{20}' Value: '{21}', {29}Keyword: '{22}' Value: '{23}', {29}Keyword: '{24}' Value: '{25}', {29}Keyword: '{26}' Value: '{27}'," + "{29}Keyword: '{28}' Value: '{29}', {29}Keyword: '{30}' Value: '{31}', {29}added to Document {28}.", gSaveToLicNum, strLicNum, gSaveToLicType, strLicType, gSaveToInspectionID, strInspID, gSaveToFileNum, strFileNum, gSaveToKeyName, strKeyName, gSaveToSubject, strSubject, gSaveToDBA, "not being returned by query", gSaveToVisitNum, strVisitNum, gSaveToDisposition, strDisposition, gSaveToCity, strCity, gSaveToCounty, strCounty, gSaveToRegion, strRegion, gSaveToInspectorName, strInspector, gSaveToInspectVisitDate, strInspDate, _currentDocument.ID, Environment.NewLine); //Output the results to the OnBase Diagnostics Console app.Diagnostics.WriteIf(Hyland.Unity.Diagnostics.DiagnosticsLevel.Verbose, output); documentLock.Release(); } } else { throw new Exception(string.Format("No records found in database")); } } } catch (Exception ex) { throw new ApplicationException("Error during database operations!", ex); } finally { if (con.State == ConnectionState.Open) { con.Close(); } } } } catch (Exception ex) { // Handle exceptions and log to Diagnostics Console and document history HandleException(ex, ref app, ref args); } finally { // Log script execution end app.Diagnostics.WriteIf(Diagnostics.DiagnosticsLevel.Info, string.Format("End Script - [{0}]", ScriptName)); } }