public void ShouldParseVariableInString() { var props = new PropertyValues(); props["var"] = "value"; var parser = new ProjectFilePropertyExpressionParser(props); AssertParseStringResult(parser, "'$(var)'", "value"); }
private static void SetSelectionItems(ListBox listBox, PropertyValues propertyValues) { if (propertyValues == null) { return; } foreach (var item in propertyValues) { listBox.SelectedItems.Add(item); } }
public void ShouldParseCondition() { var props = new PropertyValues(); props["var"] = "value"; var parser = new ProjectFilePropertyExpressionParser(props); AssertParseConditionResult(parser, " '$(var)' == 'value' ", true); AssertParseConditionResult(parser, " '$(var)' == 'valu' ", false); AssertParseConditionResult(parser, " '$(var) ' == 'value' ", false); }
public void WhenICompareTheObjectWithTheObject(string leftKey, string rightKey) { var left = ScenarioContext.Current[leftKey]; var right = ScenarioContext.Current[rightKey]; var leftProperties = new PropertyValues(left); var rightProperties = new PropertyValues(right); ScenarioContext.Current.Set(leftProperties.Compare(rightProperties).Where(r => !r.IsSameResult)); }
public WebPartEntity(WebPartDefinition definition) { _id = definition.Id; _hidden = definition.WebPart.Hidden; _subtitle = definition.WebPart.Subtitle; _title = definition.WebPart.Title; _titleurl = definition.WebPart.TitleUrl; _zoneindex = definition.WebPart.ZoneIndex; _properties = definition.WebPart.Properties; }
/// <summary> /// Sets the property value for a list /// </summary> /// <param name="clientContext">Client context</param> /// <param name="props">Property values</param> /// <param name="matterName">Matter name</param> /// <param name="propertyList">Property list</param> internal static void SetPropertyValueForList(ClientContext clientContext, PropertyValues props, string matterName, Dictionary<string, string> propertyList) { List list = clientContext.Web.Lists.GetByTitle(matterName); foreach (var item in propertyList) { props[item.Key] = item.Value; list.RootFolder.Update(); } clientContext.ExecuteQuery(); }
private EntityEventArgs CreateArgs(DbEntityEntry item, EntityState state) { PropertyValues originalValues = null; PropertyValues currentValues = null; if (state == EntityState.Modified && !(item.State == EntityState.Detached)) { originalValues = new PropertyValues(item.OriginalValues); currentValues = new PropertyValues(item.CurrentValues); } var args = new EntityEventArgs(state, originalValues, currentValues); return args; }
private static void SetSelectionItems(ListBox listBox, PropertyValues propertyValues) { if (propertyValues == null) { return; } foreach (var item in propertyValues) { if (!listBox.SelectedItems.Contains(item) && item.Inactive) { listBox.Items.Add(item); } listBox.SelectedItems.Add(item); } }
private static bool CSOMWebPartPropertiesValidation(string sourceContent, PropertyValues properties) { int scount = 0; int tcount = 0; XmlDocument sDoc = new XmlDocument(); sDoc.LoadXml(sourceContent); XmlNodeList sProps = sDoc.GetElementsByTagName("property"); string[] ignoreProperties = { "xmldefinition", "height", "width" }; if (sProps.Count != 0) { foreach (XmlNode xnSource in sProps) { string saName = xnSource.Attributes["name"].InnerText.ToString(); string saType = xnSource.Attributes["type"].InnerText.ToString(); string saText = xnSource.InnerText; if (!ignoreProperties.Contains(saName.ToLower())) { scount++; foreach (var tVariable in properties.FieldValues) { if (saName == tVariable.Key && saText == Convert.ToString(tVariable.Value)) { tcount++; break; } else if (saName == tVariable.Key) { int position = Convert.ToInt32(tVariable.Value); string sourceText = saText.ToLower().Trim(); bool result = CheckProperty(tVariable.Key, sourceText, position); if (result) { tcount++; } else { return false; } } } } } } else if (sDoc.LastChild.Name == "WebPart") { sProps = sDoc.LastChild.ChildNodes; foreach (XmlNode sProp in sProps) { string speName = sProp.Name; string speText = sProp.InnerText; if (speName.ToLower() != "height" && speName.ToLower() != "width") { scount++; foreach (var pfvalue in properties.FieldValues) { if (speName == pfvalue.Key && speText == Convert.ToString(pfvalue.Value)) { tcount++; break; } else if (speName == pfvalue.Key) { int position = Convert.ToInt32(pfvalue.Value); string sourceText = speName.ToLower().Trim(); bool result = CheckProperty(pfvalue.Key, sourceText, position); if (result) { tcount++; break; } else { return false; } } } } } } if (scount != tcount) { return false; } return true; }
public override void AcceptVisitor(StatementVisitor visitor) { visitor.VisitObjectInitializerExpression(this); PropertyValues.ForEach(nvp => nvp.Value.AcceptVisitor(visitor)); }
public bool UpdateMatterStampedProperties(ClientContext clientContext, MatterDetails matterDetails, Matter matter, PropertyValues matterStampedProperties, bool isEditMode, IConfigurationRoot configuration) { try { if (null != clientContext && null != matter && null != matterDetails && (0 < matterStampedProperties.FieldValues.Count)) { Dictionary <string, string> propertyList = new Dictionary <string, string>(); // Get existing stamped properties string stampedUsers = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyMatterCenterUsers"]); string stampedUserEmails = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyMatterCenterUserEmails"]); string stampedPermissions = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyMatterCenterPermissions"]); string stampedRoles = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyMatterCenterRoles"]); string stampedResponsibleAttorneys = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyResponsibleAttorney"]); string stampedResponsibleAttorneysEmail = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyResponsibleAttorneyEmail"]); string stampedTeamMembers = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyTeamMembers"]); string stampedBlockedUploadUsers = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyBlockedUploadUsers"]); string currentPermissions = string.Join(ServiceConstants.DOLLAR + ServiceConstants.PIPE + ServiceConstants.DOLLAR, matter.Permissions.Where(user => !string.IsNullOrWhiteSpace(user))); string currentRoles = string.Join(ServiceConstants.DOLLAR + ServiceConstants.PIPE + ServiceConstants.DOLLAR, matter.Roles.Where(user => !string.IsNullOrWhiteSpace(user))); string currentBlockedUploadUsers = string.Join(ServiceConstants.SEMICOLON, matterDetails.UploadBlockedUsers.Where(user => !string.IsNullOrWhiteSpace(user))); string currentUsers = GetMatterAssignedUsers(matter); string currentUserEmails = SPList.GetMatterAssignedUsersEmail(clientContext, matter); string finalMatterPermissions = string.Concat(stampedPermissions, ServiceConstants.DOLLAR + ServiceConstants.PIPE + ServiceConstants.DOLLAR, currentPermissions); string finalMatterRoles = string.Concat(stampedRoles, ServiceConstants.DOLLAR + ServiceConstants.PIPE + ServiceConstants.DOLLAR, currentRoles); string finalTeamMembers = string.Concat(stampedTeamMembers, ServiceConstants.SEMICOLON, ServiceConstants.SEMICOLON, matterDetails.TeamMembers); string finalMatterCenterUsers = string.Concat(stampedUsers, ServiceConstants.DOLLAR + ServiceConstants.PIPE + ServiceConstants.DOLLAR, currentUsers); string finalBlockedUploadUsers = string.Concat(stampedBlockedUploadUsers, ServiceConstants.SEMICOLON, currentBlockedUploadUsers); //if(stampedUserEmails.LastIndexOf("$|$")>0) //{ // stampedUserEmails = stampedUserEmails.Remove(stampedUserEmails.Length - 3); //} string finalMatterCenterUserEmails = string.Concat(stampedUserEmails, ServiceConstants.DOLLAR + ServiceConstants.PIPE + ServiceConstants.DOLLAR, currentUserEmails); string finalResponsibleAttorneysEmail = ""; string finalResponsibleAttorneys = ""; if (matterDetails.ResponsibleAttorneyEmail != null) { finalResponsibleAttorneysEmail = string.IsNullOrWhiteSpace(stampedResponsibleAttorneysEmail) || isEditMode ? matterDetails.ResponsibleAttorneyEmail : string.Concat(stampedResponsibleAttorneysEmail, ServiceConstants.SEMICOLON, matterDetails.ResponsibleAttorneyEmail); finalResponsibleAttorneys = string.IsNullOrWhiteSpace(stampedResponsibleAttorneys) || isEditMode ? matterDetails.ResponsibleAttorney : string.Concat(stampedResponsibleAttorneys, ServiceConstants.SEMICOLON, matterDetails.ResponsibleAttorney); } else { finalResponsibleAttorneysEmail = stampedResponsibleAttorneysEmail; finalResponsibleAttorneys = stampedResponsibleAttorneys; } propertyList.Add(configuration["Matter:StampedPropertyResponsibleAttorney"], WebUtility.HtmlEncode(finalResponsibleAttorneys)); propertyList.Add(configuration["Matter:StampedPropertyResponsibleAttorneyEmail"], WebUtility.HtmlEncode(finalResponsibleAttorneysEmail)); propertyList.Add(configuration["Matter:StampedPropertyTeamMembers"], WebUtility.HtmlEncode(finalTeamMembers)); propertyList.Add(configuration["Matter:StampedPropertyBlockedUploadUsers"], WebUtility.HtmlEncode(finalBlockedUploadUsers)); propertyList.Add(configuration["Matter:StampedPropertyMatterCenterRoles"], WebUtility.HtmlEncode(finalMatterRoles)); propertyList.Add(configuration["Matter:StampedPropertyMatterCenterPermissions"], WebUtility.HtmlEncode(finalMatterPermissions)); propertyList.Add(configuration["Matter:StampedPropertyMatterCenterUsers"], WebUtility.HtmlEncode(finalMatterCenterUsers)); propertyList.Add(configuration["Matter:StampedPropertyMatterCenterUserEmails"], WebUtility.HtmlEncode(finalMatterCenterUserEmails)); SPList.SetPropertBagValuesForList(clientContext, matterStampedProperties, matter.Name, propertyList); return(true); } } catch (Exception) { throw; //// This will transfer control to catch block of parent function. } return(false); }
public void setUpGame() { //setup properties PropertyValues value = new PropertyValues(); value.setUpProperties(); //this.setUpProperties(); //add players this.setUpPlayers(); }
private static void AddListViewWebpart( ClientContext ctx, PublishingPageWebPart wp, Microsoft.SharePoint.Client.WebParts.WebPartDefinition definition, PropertyValues webPartProperties, TokenParser parser) { string defaultViewDisplayName = parser.ParseString(wp.DefaultViewDisplayName); if (!String.IsNullOrEmpty(defaultViewDisplayName)) { string listUrl = webPartProperties.FieldValues["ListUrl"].ToString(); ctx.Load(definition, d => d.Id); // Id of the hidden view which gets automatically created ctx.ExecuteQuery(); Guid viewId = definition.Id; List list = ctx.Web.GetListByUrl(listUrl); Microsoft.SharePoint.Client.View viewCreatedFromWebpart = list.Views.GetById(viewId); ctx.Load(viewCreatedFromWebpart); Microsoft.SharePoint.Client.View viewCreatedFromList = list.Views.GetByTitle(defaultViewDisplayName); ctx.Load( viewCreatedFromList, v => v.ViewFields, v => v.ListViewXml, v => v.ViewQuery, v => v.ViewData, v => v.ViewJoins, v => v.ViewProjectedFields, v => v.Paged, v => v.RowLimit); ctx.ExecuteQuery(); //need to copy the same View definition to the new View added by the Webpart manager viewCreatedFromWebpart.ViewQuery = viewCreatedFromList.ViewQuery; viewCreatedFromWebpart.ViewData = viewCreatedFromList.ViewData; viewCreatedFromWebpart.ViewJoins = viewCreatedFromList.ViewJoins; viewCreatedFromWebpart.ViewProjectedFields = viewCreatedFromList.ViewProjectedFields; viewCreatedFromWebpart.Paged = viewCreatedFromList.Paged; viewCreatedFromWebpart.RowLimit = viewCreatedFromList.RowLimit; viewCreatedFromWebpart.ViewFields.RemoveAll(); foreach (var field in viewCreatedFromList.ViewFields) { viewCreatedFromWebpart.ViewFields.Add(field); } if (webPartProperties.FieldValues.ContainsKey("JSLink") && webPartProperties.FieldValues["JSLink"] != null) { viewCreatedFromWebpart.JSLink = webPartProperties.FieldValues["JSLink"].ToString(); } viewCreatedFromWebpart.Update(); ctx.ExecuteQuery(); } }
/// <summary> /// 新建对象 /// </summary> private ObjectVersion CreateMfObj(Vault mfVault, int typeId, int classId, string title, PropertyValues oPropValues = null) { if (oPropValues == null) { oPropValues = new PropertyValues(); } //名称(*) var oPropValueTitle = new PropertyValue(); oPropValueTitle.PropertyDef = 0; oPropValueTitle.TypedValue.SetValue(MFDataType.MFDatatypeText, title); oPropValues.Add(-1, oPropValueTitle); //是否为单文档(*) var oPropValueSingle = new PropertyValue(); oPropValueSingle.PropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefSingleFileObject; oPropValueSingle.TypedValue.SetValue(MFDataType.MFDatatypeBoolean, false); oPropValues.Add(-1, oPropValueSingle); //类别(*) var oPropValueClass = new PropertyValue(); oPropValueClass.PropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefClass; oPropValueClass.TypedValue.SetValue(MFDataType.MFDatatypeLookup, classId); oPropValues.Add(-1, oPropValueClass); //创建 var oObjVnAndProps = mfVault.ObjectOperations.CreateNewObject(typeId, oPropValues); return(mfVault.ObjectOperations.CheckIn(oObjVnAndProps.ObjVer)); }
public SPOPropertyBag(SPOWeb web, PropertyValues properties) { _web = web; _pb = properties; }
protected virtual void DeployProperty(object modelHost, PropertyValues properties, PropertyDefinition propertyDefinition) { var currentValue = properties.FieldValues.ContainsKey(propertyDefinition.Key) ? properties[propertyDefinition.Key] : null; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentValue, ObjectType = typeof(object), ObjectDefinition = propertyDefinition, ModelHost = modelHost }); if (currentValue == null) { properties[propertyDefinition.Key] = propertyDefinition.Value; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = propertyDefinition.Value, ObjectType = typeof(object), ObjectDefinition = propertyDefinition, ModelHost = modelHost }); } else { if (propertyDefinition.Overwrite) { properties[propertyDefinition.Key] = propertyDefinition.Value; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = propertyDefinition.Value, ObjectType = typeof(object), ObjectDefinition = propertyDefinition, ModelHost = modelHost }); } else { InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = propertyDefinition.Value, ObjectType = typeof(object), ObjectDefinition = propertyDefinition, ModelHost = modelHost }); } } }
public SPOPropertyBag(SPOFolder folder, PropertyValues properties) { _folder = folder; _pb = properties; }
public void PropertyValuesContainer() { PropertyValues properties = new PropertyValues(); properties.Add("key1", "oleg"); Assert.AreEqual(1, properties.GetCodes().Count); Assert.AreEqual(1, properties.GetValues("key1").Count); Assert.AreEqual("oleg", properties.GetValues("key1")[0]); Assert.AreEqual(0, properties.GetValues("key2").Count); properties.Add("key1", "shuruev"); properties.Add("key2", "hello"); Assert.AreEqual(2, properties.GetCodes().Count); Assert.AreEqual(2, properties.GetValues("key1").Count); Assert.AreEqual("oleg", properties.GetValues("key1")[0]); Assert.AreEqual("shuruev", properties.GetValues("key1")[1]); Assert.AreEqual(1, properties.GetValues("key2").Count); Assert.AreEqual("hello", properties.GetValues("key2")[0]); properties.Clear("key1"); properties.Clear("key3"); Assert.AreEqual(1, properties.GetCodes().Count); Assert.AreEqual(1, properties.GetValues("key2").Count); Assert.AreEqual("hello", properties.GetValues("key2")[0]); foreach (string word in this.emptyWords) { TestHelper.Throws(delegate { properties.Add(word, "hello"); }); TestHelper.Throws(delegate { properties.Add("key1", word); }); } }
public void PropertyOperations() { PropertyValues properties = new PropertyValues(); properties.Add("Package", "zip"); properties.Add("Keywords", "production"); properties.Add("Keywords", "application"); database.SetProperties(EntityType.Project, 10, properties); properties = database.GetProperties(EntityType.Project, 10); Assert.AreEqual(2, properties.GetCodes().Count); Assert.AreEqual(1, properties.GetValues("Package").Count); Assert.AreEqual("zip", properties.GetValues("Package")[0]); Assert.AreEqual(2, properties.GetValues("Keywords").Count); Assert.AreEqual("application", properties.GetValues("Keywords")[0]); Assert.AreEqual("production", properties.GetValues("Keywords")[1]); properties = new PropertyValues(); properties.Add("Package", "zip"); properties.Add("Package", "msi"); properties.Add("Keywords", "service"); properties.Add("Status", "beta"); database.SetProperties(EntityType.Project, 10, properties); properties = database.GetProperties(EntityType.Project, 10); Assert.AreEqual(3, properties.GetCodes().Count); Assert.AreEqual(2, properties.GetValues("Package").Count); Assert.AreEqual("msi", properties.GetValues("Package")[0]); Assert.AreEqual("zip", properties.GetValues("Package")[1]); Assert.AreEqual(1, properties.GetValues("Keywords").Count); Assert.AreEqual("service", properties.GetValues("Keywords")[0]); Assert.AreEqual(1, properties.GetValues("Status").Count); Assert.AreEqual("beta", properties.GetValues("Status")[0]); properties = new PropertyValues(); database.SetProperties(EntityType.Project, 10, properties); properties = database.GetProperties(EntityType.Project, 10); Assert.AreEqual(0, properties.GetCodes().Count); }
private PropertyValues QueryPropertyValues(string propertyName) { var res = new PropertyValues(); var assetType = connector.MetaModel.GetAssetType(propertyName); var nameDef = assetType.GetAttributeDefinition(Entity.NameProperty); IAttributeDefinition inactiveDef; var query = new Query(assetType); query.Selection.Add(nameDef); if(assetType.TryGetAttributeDefinition("Inactive", out inactiveDef)) { var filter = new FilterTerm(inactiveDef); filter.Equal("False"); query.Filter = filter; } query.OrderBy.MajorSort(assetType.DefaultOrderBy, OrderBy.Order.Ascending); res.Add(new ValueId()); foreach(var asset in connector.Services.Retrieve(query).Assets) { var name = asset.GetAttribute(nameDef).Value as string; res.Add(new ValueId(asset.Oid, name)); } return res; }
/// <summary> /// Установить значение smart-свойства. /// </summary> /// <param name="property">smart-свойство.</param> /// <param name="value">Значение smart-свойства.</param> public void SetValue(SmartProperty property, object value) { PropertyValues.SetValue(this, property, value); }
public SPOPropertyBag(SPOWebPart webPart, PropertyValues properties) { _webPart = webPart; _pb = properties; }
/// <summary> /// Установить значение smart-свойства. /// </summary> /// <param name="key">Ключ для записи smart-свойства.</param> /// <param name="value">Значение smart-свойства.</param> public void SetValue(SmartPropertyKey key, object value) { PropertyValues.SetValue(this, key.Property, value); }
public static EntityEntry Refresh(this EntityEntry tracking, RefreshConflict refreshMode) { switch (refreshMode) { case RefreshConflict.StoreWins: { //当实体被删除时,重新加载设置追踪状态为Detached //当实体被更新时,重新加载设置追踪状态为Unchanged tracking.Reload(); break; } case RefreshConflict.ClientWins: { PropertyValues databaseValues = tracking.GetDatabaseValues(); if (databaseValues == null) { //当实体被删除时,设置追踪状态为Detached,当然此时客户端无所谓获胜 tracking.State = EntityState.Detached; } else { //当实体被更新时,刷新数据库原始值 tracking.OriginalValues.SetValues(databaseValues); } break; } case RefreshConflict.MergeClientAndStore: { PropertyValues databaseValues = tracking.GetDatabaseValues(); if (databaseValues == null) { /*当实体被删除时,设置追踪状态为Detached,当然此时客户端没有合并的数据 * 并设置追踪状态为Detached */ tracking.State = EntityState.Detached; } else { //当实体被更新时,刷新数据库原始值 PropertyValues originalValues = tracking.OriginalValues.Clone(); tracking.OriginalValues.SetValues(databaseValues); //如果数据库中对于属性有不同的值保留数据库中的值 #if SelfDefine databaseValues.PropertyNames // Navigation properties are not included. .Where(property => !object.Equals(originalValues[property], databaseValues[property])) .ForEach(property => tracking.Property(property).IsModified = false); #else databaseValues.Properties .Where(property => !object.Equals(originalValues[property.Name], databaseValues[property.Name])) .ToList() .ForEach(property => tracking.Property(property.Name).IsModified = false); #endif } break; } } return(tracking); }
private PropertyValues QueryPropertyValues(string propertyName) { var res = new PropertyValues(); var assetType = connector.MetaModel.GetAssetType(propertyName); IAttributeDefinition nameDef = null; if (propertyName == "Member") { nameDef = assetType.GetAttributeDefinition("Nickname"); } else { nameDef = assetType.GetAttributeDefinition("Name"); } IAttributeDefinition inactiveDef; assetType.TryGetAttributeDefinition("Inactive", out inactiveDef); var query = new Query(assetType); query.Selection.Add(nameDef); if (inactiveDef != null) { query.Selection.Add(inactiveDef); } /* if(assetType.TryGetAttributeDefinition("Inactive", out inactiveDef)) { var filter = new FilterTerm(inactiveDef); filter.Equal("False"); query.Filter = filter; } */ query.OrderBy.MajorSort(assetType.DefaultOrderBy, OrderBy.Order.Ascending); res.Add(new ValueId()); // which is the aim of this? having a blank item at the begining of the combo? foreach(var asset in connector.Services.Retrieve(query).Assets) { var name = asset.GetAttribute(nameDef).Value as string; var inactive = false; if (inactiveDef != null) { inactive = (bool)asset.GetAttribute(inactiveDef).Value; } res.Add(new ValueId(asset.Oid, name, inactive)); } return res; }
public void SetUp() { Props = new PropertyValues(); Parser = new ProjectFilePropertyExpressionParser(Props); }
public static void CreateNewDocumentWithNewACL() { LogIntoVault(); //Prerequisites for creating an object in mfiles; //Type of object E.g. 0 is for document //PropertyValues //Source files if the object's type is document or any other type that can have documents var properties = new PropertyValues(); //Class 0 -> Sınıflandırılmamış Doküman var classProperty = new PropertyValue(); classProperty.PropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefClass; //Simply 100 classProperty.TypedValue.SetValue(MFDataType.MFDatatypeLookup, 0); properties.Add(0, classProperty); //Name or Title -> İsim veya başlık var nameProperty = new PropertyValue(); nameProperty.PropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefNameOrTitle; //Simply 0 nameProperty.TypedValue.SetValue(MFDataType.MFDatatypeText, "SampleTextFile"); properties.Add(0, nameProperty); //File from fileSystem var sourceObjectFile = new SourceObjectFile(); sourceObjectFile.Title = "SampleTextFile"; sourceObjectFile.SourceFilePath = "SampleTextFile.txt"; sourceObjectFile.Extension = "txt"; //Create New ACL var accessControlList = new AccessControlList(); accessControlList.IsFullyAuthoritative = true; //Create Component var aclComponent = new AccessControlListComponent(); //Create Entry var aclEntryKey = new AccessControlEntryKey(); aclEntryKey.SetUserOrGroupID(1, true); //Create Data (Permissions for Entry) var aclData = new AccessControlEntryData(); aclData.DeletePermission = MFPermission.MFPermissionNotSet; aclData.ReadPermission = MFPermission.MFPermissionAllow; aclData.EditPermission = MFPermission.MFPermissionNotSet; aclData.AttachObjectsPermission = MFPermission.MFPermissionAllow; aclData.ChangePermissionsPermission = MFPermission.MFPermissionNotSet; //Set Entry Key, Data aclComponent.AccessControlEntries.Add(aclEntryKey, aclData); //Add to ACL accessControlList.CustomComponent = aclComponent; var namedACLAdmin = new NamedACLAdmin(); var namedACL = new NamedACL(); namedACL.AccessControlList = accessControlList; namedACL.Name = "NewACL" + Guid.NewGuid().ToString().Substring(7); namedACLAdmin.NamedACL = namedACL; //Add ACL TO Server var newCreatedACL = loggedInVault.NamedACLOperations.AddNamedACLAdmin(namedACLAdmin); //Use newly Added ACL loggedInVault.ObjectOperations.CreateNewSFDObject( 0 , properties , sourceObjectFile , true , newCreatedACL.NamedACL.AccessControlList); }
internal static TAutoHistory AutoHistory <TAutoHistory>(this EntityEntry entry, Func <TAutoHistory> createHistoryFactory) where TAutoHistory : AutoHistory { var history = createHistoryFactory(); history.TableName = entry.Metadata.GetTableName(); // Get the mapped properties for the entity type. // (include shadow properties, not include navigations & references) var properties = entry.Properties; var formatting = AutoHistoryOptions.Instance.JsonSerializerSettings.Formatting; var jsonSerializer = AutoHistoryOptions.Instance.JsonSerializer; var json = new JObject(); switch (entry.State) { case EntityState.Added: foreach (var prop in properties) { if (prop.Metadata.IsKey() || prop.Metadata.IsForeignKey()) { continue; } json[prop.Metadata.Name] = prop.CurrentValue != null ? JToken.FromObject(prop.CurrentValue, jsonSerializer) : JValue.CreateNull(); } // REVIEW: what's the best way to set the RowId? history.RowId = "0"; history.Kind = EntityState.Added; history.Changed = json.ToString(formatting); break; case EntityState.Modified: var bef = new JObject(); var aft = new JObject(); PropertyValues databaseValues = null; foreach (var prop in properties) { if (prop.IsModified) { if (prop.OriginalValue != null) { if (!prop.OriginalValue.Equals(prop.CurrentValue)) { bef[prop.Metadata.Name] = JToken.FromObject(prop.OriginalValue, jsonSerializer); } else { databaseValues = databaseValues ?? entry.GetDatabaseValues(); var originalValue = databaseValues.GetValue <object>(prop.Metadata.Name); bef[prop.Metadata.Name] = originalValue != null ? JToken.FromObject(originalValue, jsonSerializer) : JValue.CreateNull(); } } else { bef[prop.Metadata.Name] = JValue.CreateNull(); } aft[prop.Metadata.Name] = prop.CurrentValue != null ? JToken.FromObject(prop.CurrentValue, jsonSerializer) : JValue.CreateNull(); } } json["before"] = bef; json["after"] = aft; history.RowId = entry.PrimaryKey(); history.Kind = EntityState.Modified; history.Changed = json.ToString(formatting); break; case EntityState.Deleted: foreach (var prop in properties) { json[prop.Metadata.Name] = prop.OriginalValue != null ? JToken.FromObject(prop.OriginalValue, jsonSerializer) : JValue.CreateNull(); } history.RowId = entry.PrimaryKey(); history.Kind = EntityState.Deleted; history.Changed = json.ToString(formatting); break; case EntityState.Detached: case EntityState.Unchanged: default: throw new NotSupportedException("AutoHistory only support Deleted and Modified entity."); } return(history); }
private static bool ArePublishingFeaturesActivated(PropertyValues props) { bool activated = false; if (bool.TryParse(props.GetPropertyAsString(PublishingFeatureActivated), out activated)) { } return activated; }
/// <summary> /// Sets the values of this object by reading values from another <see cref="PropertyValues" /> /// object. /// </summary> /// <remarks> /// <para> /// The other object must be based on the same type as this object, or a type derived /// from the type for this object. /// </para> /// <para> /// See <see href="https://aka.ms/efcore-docs-entity-entries">Accessing tracked entities in EF Core</see> for more information and /// examples. /// </para> /// </remarks> /// <param name="propertyValues">The object from which values should be copied.</param> public abstract void SetValues(PropertyValues propertyValues);
public DocumentOperation(StateEnvironment stateEnvironment) { vault = stateEnvironment.Vault; objver = stateEnvironment.ObjVer; try { var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location); SignaturePicturePath = string.Empty; var spp = config.AppSettings.Settings["SignaturePicturePath"]; if (spp != null) { SignaturePicturePath = spp.Value; } var files = vault.ObjectFileOperations.GetFiles(objver); filepath = Path.GetTempFileName(); foreach (ObjectFile objectFile in files) { vault.ObjectFileOperations.DownloadFile(objectFile.ID, objectFile.Version, filepath); break; } var sc = new SearchCondition(); sc.ConditionType = MFConditionType.MFConditionTypeEqual; sc.Expression.DataStatusValueType = MFStatusType.MFStatusTypeObjectTypeID; sc.TypedValue.SetValueToLookup(new Lookup { Item = vault.GetMetadataStructureItemIDByAlias( MFMetadataStructureItem.MFMetadataStructureItemObjectType, MfilesAliasConfig.ObjProject) }); var sr = vault.ObjectSearchOperations.SearchForObjectsByCondition(sc, false).ObjectVersions; if (sr.Count < 1) { Writelog(string.Format("DocumentOperation- can't find project object in the vault <{0}>--", vault.Name)); } foreach (ObjectVersion objectVersion in sr) { pvs = vault.ObjectPropertyOperations.GetProperties(objectVersion.ObjVer); Project = new ProjectInMfiles { PropProjName = pvs.SearchForPropertyByAlias(vault, MfilesAliasConfig.PropProjName, true).GetValueAsLocalizedText(), PropProjNum = pvs.SearchForPropertyByAlias(vault, MfilesAliasConfig.PropProjNum, true).GetValueAsLocalizedText(), PropDescription = pvs.SearchForPropertyByAlias(vault, MfilesAliasConfig.PropDescription, true).GetValueAsLocalizedText(), PropProprietorUnit = pvs.SearchForPropertyByAlias(vault, MfilesAliasConfig.PropProprietorUnit, true).GetValueAsLocalizedText(), PropSupervisorUnit = pvs.SearchForPropertyByAlias(vault, MfilesAliasConfig.PropSupervisorUnit, true).GetValueAsLocalizedText(), PropDesignUnit = pvs.SearchForPropertyByAlias(vault, MfilesAliasConfig.PropDesignUnit, true).GetValueAsLocalizedText(), PropStartDate = pvs.SearchForPropertyByAlias(vault, MfilesAliasConfig.PropStartDate, true).GetValueAsLocalizedText(), Deadline = pvs.SearchForProperty((int)MFBuiltInPropertyDef.MFBuiltInPropertyDefDeadline) .GetValueAsLocalizedText(), }; break; } pvs = vault.ObjectPropertyOperations.GetProperties(objver); app = new Application(); object unknow = Type.Missing; doc = app.Documents.Open(filepath, ref unknow, false, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow); table = doc.Tables[doc.Tables.Count]; } catch (Exception ex) { Writelog(string.Format("DocumentOperation-- vault={0},type={1},id={2},version={3},CurrentUserID={4},StateID={5},DisplayID={6},{7}", vault.Name, objver.Type, objver.ID, objver.Version, stateEnvironment.CurrentUserID, stateEnvironment.StateID, stateEnvironment.DisplayID, ex.Message)); } }
public void CreateChequeTest(StateEnvironment env) { var Vault = env.ObjVerEx.Vault; var oCurrObjVals = Vault.ObjectPropertyOperations.GetProperties(env.ObjVerEx.ObjVer); var VendorID = SearchPropertyValue(oCurrObjVals, Vendor_PD); List <InvoiceValue> InvoiceValues = new List <InvoiceValue>(); InvoiceValues.Add(new InvoiceValue() { PropertyID = Date_PD, TypedValue = SearchPropertyValue(oCurrObjVals, InvoiceDate_PD) }); InvoiceValues.Add(new InvoiceValue() { PropertyID = InvoiceNumber_PD, TypedValue = SearchPropertyValue(oCurrObjVals, InvoiceNumber_PD) }); InvoiceValues.Add(new InvoiceValue() { PropertyID = Vendor_PD, TypedValue = VendorID }); List <ObjVerEx> InvoiceObjVers = SearchForObjects(env, Invoice_CD, InvoiceValues); if (InvoiceObjVers != null) { InvoiceValues = new List <InvoiceValue>(); InvoiceValues.Add(new InvoiceValue() { PropertyID = Vendor_PD, TypedValue = VendorID }); InvoiceValues.Add(new InvoiceValue() { PropertyID = Date_PD, TypedValue = SearchPropertyValue(oCurrObjVals, ChequeDate_PD) }); InvoiceValues.Add(new InvoiceValue() { PropertyID = ChequeNumber_PD, TypedValue = SearchPropertyValue(oCurrObjVals, ChequeNumber_PD) }); InvoiceValues.Add(new InvoiceValue() { PropertyID = Amount_PD, TypedValue = SearchPropertyValue(oCurrObjVals, ChequeAmount_PD) }); List <ObjVerEx> ChequeObjVers = SearchForObjects(env, Cheque_CD, InvoiceValues); ObjVer oCheque; var propertyValues = new PropertyValues(); if (ChequeObjVers != null) { oCheque = Vault.ObjectOperations.CheckOut(ChequeObjVers[0].ObjID).ObjVer; } else { var classPropertyValue = new PropertyValue() { PropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefClass }; classPropertyValue.Value.SetValue(MFDataType.MFDatatypeLookup, Vault.ClassOperations.GetObjectClass(Cheque_CD).ID); propertyValues.Add(-1, classPropertyValue); propertyValues.Add(-1, GetPropertyValue(oCurrObjVals, ChequeNumber_PD)); propertyValues.Add(-1, GetPropertyValue(oCurrObjVals, Date_PD, ChequeDate_PD)); propertyValues.Add(-1, GetPropertyValue(oCurrObjVals, Amount_PD, ChequeAmount_PD)); propertyValues.Add(-1, GetPropertyValue(oCurrObjVals, Vendor_PD)); ObjectVersionAndProperties ppts = Vault.ObjectOperations.CreateNewObject(Cheque_OT, propertyValues); oCheque = ppts.ObjVer; } var ChequeProps = Vault.ObjectPropertyOperations.GetProperties(oCheque); Lookups PaidInvoices = ChequeProps.SearchForProperty(PaidInvoices_PD).TypedValue.GetValueAsLookups(); bool FoundInvoice = false; foreach (Lookup PaidInvoicesItem in PaidInvoices) { if (PaidInvoicesItem.Item == InvoiceObjVers[0].ObjVer.ID) { FoundInvoice = true; break; } } if (!FoundInvoice) { var NewInvoice = new Lookup(); NewInvoice.ObjectType = InvoiceObjVers[0].ObjVer.Type; NewInvoice.Item = InvoiceObjVers[0].ObjVer.ID; NewInvoice.DisplayValue = InvoiceObjVers[0].Title; PaidInvoices.Add(-1, NewInvoice); var PaidIvc = new PropertyValue() { PropertyDef = PaidInvoices_PD //oCurrObjVals.SearchForProperty(PaidInvoices_PD).PropertyDef }; PaidIvc.Value.SetValueToMultiSelectLookup(PaidInvoices); Vault.ObjectPropertyOperations.SetProperty(oCheque, PaidIvc); } env.ObjVerEx.Vault.ObjectOperations.CheckIn(oCheque); } env.ObjVerEx.SetWorkflowState(SagePaymentWorkFlow, Processed_State); env.ObjVerEx.SaveProperties(); }
public void UpdateUserPermissionsForMatter(MatterInformationVM matterInformation, IConfigurationRoot configuration, System.Security.SecureString securePassword) { var matter = matterInformation.Matter; var matterDetails = matterInformation.MatterDetails; var client = matterInformation.Client; int listItemId = -1; string loggedInUserName = ""; bool isEditMode = matterInformation.EditMode; ClientContext clientContext = null; IEnumerable <RoleAssignment> userPermissionOnLibrary = null; //GenericResponseVM genericResponse = null; try { clientContext = new ClientContext(matterInformation.Client.Url); clientContext.Credentials = new SharePointOnlineCredentials(configuration["General:AdminUserName"], securePassword); //if (null != matter.Conflict && !string.IsNullOrWhiteSpace(matter.Conflict.Identified)) //{ // if (Convert.ToBoolean(matter.Conflict.Identified, System.Globalization.CultureInfo.InvariantCulture)) // { // genericResponse = CheckSecurityGroupInTeamMembers(clientContext, matter, matterInformation.UserIds); // } //} //else //{ // //genericResponse = string.Format(System.Globalization.CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputConflictIdentifiedCode, TextConstants.IncorrectInputConflictIdentifiedMessage); // return; //} //if (genericResponse == null) //{ PropertyValues matterStampedProperties = SPList.GetListProperties(clientContext, matter.Name); loggedInUserName = SPList.GetLoggedInUserDetails(clientContext).Name; // Get matter library current permissions userPermissionOnLibrary = SPList.FetchUserPermissionForLibrary(clientContext, matter.Name); string originalMatterName = SPList.GetMatterName(clientContext, matter.Name); listItemId = SPList.RetrieveItemId(clientContext, "Site Pages", originalMatterName); List <string> usersToRemove = RetrieveMatterUsers(userPermissionOnLibrary); bool hasFullPermission = CheckFullPermissionInAssignList(matter.AssignUserNames, matter.Permissions, loggedInUserName); List <string> listExists = MatterAssociatedLists(clientContext, matter.Name); AssignRemoveFullControl(clientContext, matter, loggedInUserName, listItemId, listExists, true, hasFullPermission); bool result = false; if (listExists.Contains(matter.Name)) { result = UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name, -1, isEditMode); } if (listExists.Contains(matter.Name + configuration["Matter:OneNoteLibrarySuffix"])) { result = UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name + configuration["Matter:OneNoteLibrarySuffix"], -1, isEditMode); } if (listExists.Contains(matter.Name + configuration["Matter:CalendarNameSuffix"])) { result = UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name + configuration["Matter:CalendarNameSuffix"], -1, isEditMode); } if (listExists.Contains(matter.Name + configuration["Matter:TaskNameSuffix"])) { result = UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name + configuration["Matter:TaskNameSuffix"], -1, isEditMode); } if (0 <= listItemId) { result = UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, true, "Site Pages", listItemId, isEditMode); } // Update matter metadata result = UpdateMatterStampedProperties(clientContext, matterDetails, matter, matterStampedProperties, isEditMode, configuration); //} } catch (Exception ex) { MatterRevertList matterRevertListObject = new MatterRevertList() { MatterLibrary = matter.Name, MatterOneNoteLibrary = matter.Name + configuration["Matter:OneNoteLibrarySuffix"], MatterCalendar = matter.Name + configuration["Matter:CalendarNameSuffix"], MatterTask = matter.Name + configuration["Matter:TaskNameSuffix"], MatterSitePages = "Site Pages" }; RevertMatterUpdates(client, matter, clientContext, matterRevertListObject, loggedInUserName, userPermissionOnLibrary, listItemId, isEditMode); } //return ServiceUtility.GenericResponse("9999999", "Error in updating matter information"); }
private void button2_Click(object sender, EventArgs e, Vault currVault, MFilesClientApplication mFilesApp) { OpenFileDialog openFile = new OpenFileDialog(); openFile.Filter = "XML Files (*.xml) | *.xml"; if (openFile.ShowDialog() == DialogResult.OK) { //open XML file XElement inputFile = XElement.Load(openFile.FileName); IEnumerable <XElement> inputxml = from el in inputFile.Element("Payables").Elements() select el; //loop through items int count = 0; foreach (XElement payable in inputxml) { //Check that a check has been cut in Yardi. if (payable.Element("Details").Element("Detail").Elements("CheckNumber").Any()) { string checkNumber = payable.Element("Details").Element("Detail").Element("CheckNumber").Value; //MessageBox.Show(checkNumber); //Find Invoice in mFiles //pull invoices using search conditions var searchConditions = new SearchConditions(); //is it not deleted var isNotDeleted = new SearchCondition(); isNotDeleted.Expression.DataStatusValueType = MFStatusType.MFStatusTypeDeleted; isNotDeleted.Expression.DataStatusValueDataFunction = MFDataFunction.MFDataFunctionNoOp; isNotDeleted.ConditionType = MFConditionType.MFConditionTypeNotEqual; isNotDeleted.TypedValue.SetValue(MFDataType.MFDatatypeBoolean, true); searchConditions.Add(-1, isNotDeleted); //is it part of the Invoice workflow var isInvoice = new SearchCondition(); isInvoice.Expression.DataPropertyValuePropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefWorkflow; isInvoice.ConditionType = MFConditionType.MFConditionTypeEqual; isInvoice.TypedValue.SetValue(MFDataType.MFDatatypeLookup, Properties.Settings.Default.invoiceWorkflow); searchConditions.Add(-1, isInvoice); //is it in the payment processing state var isAccounting = new SearchCondition(); isAccounting.Expression.DataPropertyValuePropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefState; isAccounting.ConditionType = MFConditionType.MFConditionTypeEqual; isAccounting.TypedValue.SetValue(MFDataType.MFDatatypeLookup, Properties.Settings.Default.stateProcessing); searchConditions.Add(-1, isAccounting); //is it the correct payable var isPayable = new SearchCondition(); isPayable.Expression.DataPropertyValuePropertyDef = Properties.Settings.Default.propInvoiceNumber; isPayable.ConditionType = MFConditionType.MFConditionTypeEqual; isPayable.TypedValue.SetValue(MFDataType.MFDatatypeText, payable.Element("InvoiceNumber").Value); searchConditions.Add(-1, isPayable); //Perform search var invoices = currVault.ObjectSearchOperations.SearchForObjectsByConditions(searchConditions, MFSearchFlags.MFSearchFlagNone, false); foreach (ObjectVersion invoice in invoices) { var propValues = new PropertyValues(); var currPropertyValue = new PropertyValue(); propValues = currVault.ObjectPropertyOperations.GetProperties(invoice.ObjVer); //currPropertyValue = propValues.SearchForProperty(Properties.Settings.Default.propCheckNumber); count++; propValues.SearchForProperty(Properties.Settings.Default.propCheckNumber).TypedValue.SetValue(MFDataType.MFDatatypeText, checkNumber); //change workflow state propValues.SearchForProperty((int)MFBuiltInPropertyDef.MFBuiltInPropertyDefState).TypedValue.SetValue(MFDataType.MFDatatypeLookup, Properties.Settings.Default.stateComplete); currVault.ObjectPropertyOperations.SetAllProperties(invoice.ObjVer, true, propValues); } } } MessageBox.Show(count.ToString() + " Invoices update in mFiles!"); } }
private static void AddListViewWebpart( ClientContext ctx, PublishingPageWebPart wp, Microsoft.SharePoint.Client.WebParts.WebPartDefinition definition, PropertyValues webPartProperties) { string defaultViewDisplayName = wp.DefaultViewDisplayName; if (!String.IsNullOrEmpty(defaultViewDisplayName)) { string listUrl = webPartProperties.FieldValues["ListUrl"].ToString(); ctx.Load(definition, d => d.Id); // Id of the hidden view which gets automatically created ctx.ExecuteQuery(); Guid viewId = definition.Id; List list = ctx.Web.GetListByUrl(listUrl); Microsoft.SharePoint.Client.View viewCreatedFromWebpart = list.Views.GetById(viewId); ctx.Load(viewCreatedFromWebpart); Microsoft.SharePoint.Client.View viewCreatedFromList = list.Views.GetByTitle(defaultViewDisplayName); ctx.Load( viewCreatedFromList, v => v.ViewFields, v => v.ListViewXml, v => v.ViewQuery, v => v.ViewData, v => v.ViewJoins, v => v.ViewProjectedFields); ctx.ExecuteQuery(); //need to copy the same View definition to the new View added by the Webpart manager viewCreatedFromWebpart.ViewQuery = viewCreatedFromList.ViewQuery; viewCreatedFromWebpart.ViewData = viewCreatedFromList.ViewData; viewCreatedFromWebpart.ViewJoins = viewCreatedFromList.ViewJoins; viewCreatedFromWebpart.ViewProjectedFields = viewCreatedFromList.ViewProjectedFields; viewCreatedFromWebpart.ViewFields.RemoveAll(); foreach (var field in viewCreatedFromList.ViewFields) { viewCreatedFromWebpart.ViewFields.Add(field); } //need to set the JSLink to the new View added by the Webpart manager. //This is because there's no way to change the BaseViewID property of the new View, //and we needed to do that because the custom JSLink was bound to a specific BaseViewID (overrideCtx.BaseViewID = 3;) //The work around to this is to add the JSLink to the specific new View created when you add the xsltViewWebpart to the page //and remove the "overrideCtx.BaseViewID = 3;" from the JSLink file //that way, the JSLink will be executed only for this View, that is only used in the xsltViewWebpart, //so the effect is the same that bind the JSLink to the BaseViewID if (webPartProperties.FieldValues.ContainsKey("JSLink") && webPartProperties.FieldValues["JSLink"] != null) { viewCreatedFromWebpart.JSLink = webPartProperties.FieldValues["JSLink"].ToString(); } viewCreatedFromWebpart.Update(); ctx.ExecuteQuery(); } }
public void CreateNewDetails(ObjVerEx objVer, List <ObjVerEx> objPOs) { List <ObjVerEx> objInvoices = FindObjects(objVer.Vault, InvoiceDetail_CD, Invoice_PD, MFDataType.MFDatatypeLookup, objVer.ID.ToString()); var nextNo = objInvoices.Count; foreach (var objPO in objPOs) { var propertyValues = new PropertyValues(); //set class var classPropertyValue = new PropertyValue() { PropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefClass }; classPropertyValue.Value.SetValue(MFDataType.MFDatatypeLookup, objVer.Vault.ClassOperations.GetObjectClass(InvoiceDetail_CD).ID); propertyValues.Add(-1, classPropertyValue); // set Name or Title var TitleProperties = objVer.Vault.ObjectPropertyOperations.GetProperties(objVer.ObjVer, true); var propTitle = TitleProperties.SearchForProperty((int)MFBuiltInPropertyDef.MFBuiltInPropertyDefNameOrTitle); var nameOrTitlePropertyValue = new PropertyValue() { PropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefNameOrTitle }; var DisplayValue = propTitle.TypedValue.DisplayValue + " - Line " + (++nextNo).ToString(); nameOrTitlePropertyValue.Value.SetValue(propTitle.TypedValue.DataType, DisplayValue); propertyValues.Add(-1, nameOrTitlePropertyValue); // set Invoice var NewInvoiceLookup = new Lookup() { ObjectType = objVer.ObjVer.Type, Item = objVer.ObjVer.ID, DisplayValue = TitleProperties.SearchForProperty(InvoiceName_PD).TypedValue.DisplayValue }; var newInvoice = new PropertyValue() { PropertyDef = Invoice_PD.ID //1058 }; newInvoice.Value.SetValue(MFDataType.MFDatatypeLookup, NewInvoiceLookup); propertyValues.Add(-1, newInvoice); // set PODetail var NewPOLookup = new Lookup() { ObjectType = objPO.ObjVer.Type, Item = objPO.ObjVer.ID, DisplayValue = objPO.Title }; var newPO = new PropertyValue() { PropertyDef = PurchaseOrderDetail_PD.ID //1177 }; newPO.Value.SetValue(MFDataType.MFDatatypeLookup, NewPOLookup); //propertyValues.Add(-1, newPO); PropertyValues PO = objVer.Vault.ObjectPropertyOperations.GetProperties(objPO.ObjVer); propertyValues.Add(-1, GetPropertyValue(objVer.Vault, PO, POLine_PD, InvoiceLineNumber_PD)); propertyValues.Add(-1, GetPropertyValue(objVer.Vault, PO, POItem_PD, ItemNumber_PD)); //propertyValues.Add(-1, GetPropertyValue(objVer.Vault, PO, OrderedQty_PD, Quantity_PD)); propertyValues.Add(-1, GetPropertyValue(objVer.Vault, PO, UnitPrice_PD, UnitPrice_PD)); propertyValues.Add(-1, GetPropertyValue(objVer.Vault, PO, GLAccount_PD, GLAccount_PD)); ObjectVersionAndProperties ppts = objVer.Vault.ObjectOperations.CreateNewObject(InvoiceDetail_OT, propertyValues); objVer.Vault.ObjectOperations.CheckIn(ppts.ObjVer); } }
/// <summary> /// Возвратить значение smart-свойства. /// </summary> /// <param name="property">smart-свойство.</param> /// <returns>Значение smart-свойства.</returns> /// <exception cref="SmartPropertyException" /> public object GetValue(SmartProperty property) { return(PropertyValues.GetValue(this, property)); }
/// <summary> /// Удалить значение smart-свойства из глобальной таблицы значений свойств. /// </summary> /// <param name="property">smart-свойство.</param> public void ResetValue(SmartProperty property) { PropertyValues.ResetValue(this, property); }
/// <summary> /// Checks the PageTransformation XML data to know which properties need to be kept for the given web part and collects their values /// </summary> /// <param name="properties">Properties collection retrieved when we loaded the web part</param> /// <param name="webPartType">Type of the web part</param> /// <param name="webPartXml">Web part XML</param> /// <returns>Collection of the requested property/value pairs</returns> public Dictionary <string, string> Properties(PropertyValues properties, string webPartType, string webPartXml) { Dictionary <string, string> propertiesToKeep = new Dictionary <string, string>(); List <Property> propertiesToRetrieve = this.pageTransformation.BaseWebPart.Properties.ToList <Property>(); var webPartProperties = this.pageTransformation.WebParts.Where(p => p.Type.Equals(webPartType, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (webPartProperties != null && webPartProperties.Properties != null) { foreach (var p in webPartProperties.Properties.ToList <Property>()) { if (!propertiesToRetrieve.Contains(p)) { propertiesToRetrieve.Add(p); } } } if (string.IsNullOrEmpty(webPartXml)) { if (webPartType == WebParts.Client) { // Special case since we don't know upfront which properties are relevant here...so let's take them all foreach (var prop in properties.FieldValues) { if (!propertiesToKeep.ContainsKey(prop.Key)) { propertiesToKeep.Add(prop.Key, prop.Value != null ? prop.Value.ToString() : ""); } } } else { // Special case where we did not have export rights for the web part XML, assume this is a V3 web part foreach (var property in propertiesToRetrieve) { if (!string.IsNullOrEmpty(property.Name) && properties.FieldValues.ContainsKey(property.Name)) { if (!propertiesToKeep.ContainsKey(property.Name)) { propertiesToKeep.Add(property.Name, properties[property.Name] != null ? properties[property.Name].ToString() : ""); } } } } } else { var xml = XElement.Parse(webPartXml); var xmlns = xml.XPathSelectElement("*").GetDefaultNamespace(); if (xmlns.NamespaceName.Equals("http://schemas.microsoft.com/WebPart/v3", StringComparison.InvariantCultureIgnoreCase)) { if (webPartType == WebParts.Client) { // Special case since we don't know upfront which properties are relevant here...so let's take them all foreach (var prop in properties.FieldValues) { if (!propertiesToKeep.ContainsKey(prop.Key)) { propertiesToKeep.Add(prop.Key, prop.Value != null ? prop.Value.ToString() : ""); } } } else { // the retrieved properties are sufficient foreach (var property in propertiesToRetrieve) { if (!string.IsNullOrEmpty(property.Name) && properties.FieldValues.ContainsKey(property.Name)) { if (!propertiesToKeep.ContainsKey(property.Name)) { propertiesToKeep.Add(property.Name, properties[property.Name] != null ? properties[property.Name].ToString() : ""); } } } } } else if (xmlns.NamespaceName.Equals("http://schemas.microsoft.com/WebPart/v2", StringComparison.InvariantCultureIgnoreCase)) { foreach (var property in propertiesToRetrieve) { if (!string.IsNullOrEmpty(property.Name)) { if (properties.FieldValues.ContainsKey(property.Name)) { if (!propertiesToKeep.ContainsKey(property.Name)) { propertiesToKeep.Add(property.Name, properties[property.Name] != null ? properties[property.Name].ToString() : ""); } } else { // check XMl for property var v2Element = xml.Descendants(xmlns + property.Name).FirstOrDefault(); if (v2Element != null) { if (!propertiesToKeep.ContainsKey(property.Name)) { propertiesToKeep.Add(property.Name, v2Element.Value); } } // Some properties do have their own namespace defined if (webPartType == WebParts.SimpleForm && property.Name.Equals("Content", StringComparison.InvariantCultureIgnoreCase)) { // Load using the http://schemas.microsoft.com/WebPart/v2/SimpleForm namespace XNamespace xmlcontentns = "http://schemas.microsoft.com/WebPart/v2/SimpleForm"; v2Element = xml.Descendants(xmlcontentns + property.Name).FirstOrDefault(); if (v2Element != null) { if (!propertiesToKeep.ContainsKey(property.Name)) { propertiesToKeep.Add(property.Name, v2Element.Value); } } } else if (webPartType == WebParts.ContentEditor) { if (property.Name.Equals("ContentLink", StringComparison.InvariantCultureIgnoreCase) || property.Name.Equals("Content", StringComparison.InvariantCultureIgnoreCase) || property.Name.Equals("PartStorage", StringComparison.InvariantCultureIgnoreCase)) { XNamespace xmlcontentns = "http://schemas.microsoft.com/WebPart/v2/ContentEditor"; v2Element = xml.Descendants(xmlcontentns + property.Name).FirstOrDefault(); if (v2Element != null) { if (!propertiesToKeep.ContainsKey(property.Name)) { propertiesToKeep.Add(property.Name, v2Element.Value); } } } } else if (webPartType == WebParts.Xml) { if (property.Name.Equals("XMLLink", StringComparison.InvariantCultureIgnoreCase) || property.Name.Equals("XML", StringComparison.InvariantCultureIgnoreCase) || property.Name.Equals("XSLLink", StringComparison.InvariantCultureIgnoreCase) || property.Name.Equals("XSL", StringComparison.InvariantCultureIgnoreCase) || property.Name.Equals("PartStorage", StringComparison.InvariantCultureIgnoreCase)) { XNamespace xmlcontentns = "http://schemas.microsoft.com/WebPart/v2/Xml"; v2Element = xml.Descendants(xmlcontentns + property.Name).FirstOrDefault(); if (v2Element != null) { if (!propertiesToKeep.ContainsKey(property.Name)) { propertiesToKeep.Add(property.Name, v2Element.Value); } } } } else if (webPartType == WebParts.SiteDocuments) { if (property.Name.Equals("UserControlledNavigation", StringComparison.InvariantCultureIgnoreCase) || property.Name.Equals("ShowMemberships", StringComparison.InvariantCultureIgnoreCase) || property.Name.Equals("UserTabs", StringComparison.InvariantCultureIgnoreCase)) { XNamespace xmlcontentns = "urn:schemas-microsoft-com:sharepoint:portal:sitedocumentswebpart"; v2Element = xml.Descendants(xmlcontentns + property.Name).FirstOrDefault(); if (v2Element != null) { if (!propertiesToKeep.ContainsKey(property.Name)) { propertiesToKeep.Add(property.Name, v2Element.Value); } } } } } } } } } return(propertiesToKeep); }
protected override void DoApplyChanges(TreeNodeAdv node, Control editor) { var lstEditor = (ListBox) editor; var values = new PropertyValues(lstEditor.SelectedItems); SetValue(node, values); }
public static string GetSecureNoticeNew(EventHandlerEnvironment env) //程序划图片表格 { var rpd = new ReportPrintData(); Writelog(env.Vault.Name + env.Input + "GetSecureNotice : 查询条件"); try { var input = JsonConvert.DeserializeObject <ReportInput>(env.Input); #region search issuenotice var conditions = new SearchConditions(); { var condition = new SearchCondition { ConditionType = MFConditionType.MFConditionTypeEqual, Expression = { DataStatusValueType = MFStatusType.MFStatusTypeObjectTypeID } }; condition.TypedValue.SetValueToLookup(new Lookup { Item = OtSecureAdjustNotice.ID }); // Writelog("OtSecureAdjustNotice=" + OtSecureAdjustNotice.ID); conditions.Add(-1, condition); } { var sc = new SearchCondition { ConditionType = MFConditionType.MFConditionTypeNotEqual, Expression = { DataStatusValueType = MFStatusType.MFStatusTypeDeleted } }; sc.TypedValue.SetValue(MFDataType.MFDatatypeBoolean, true); conditions.Add(-1, sc); } { var condition = new SearchCondition { ConditionType = MFConditionType.MFConditionTypeGreaterThanOrEqual, Expression = { DataPropertyValuePropertyDef = PropCheckDate.ID } }; // Writelog("PropCheckDate=" + PropCheckDate.ID); condition.TypedValue.SetValue(MFDataType.MFDatatypeDate, input.StartDate); conditions.Add(-1, condition); } { var condition = new SearchCondition { ConditionType = MFConditionType.MFConditionTypeLessThanOrEqual, Expression = { DataPropertyValuePropertyDef = PropCheckDate.ID } }; condition.TypedValue.SetValue(MFDataType.MFDatatypeDate, input.EndDate); conditions.Add(-1, condition); } if (input.Principal != 0) { var condition = new SearchCondition(); // Writelog("PropPrincipal=" + PropPrincipal.ID); condition.ConditionType = MFConditionType.MFConditionTypeEqual; condition.Expression.DataPropertyValuePropertyDef = PropPrincipal.ID; condition.TypedValue.SetValueToLookup(new Lookup { Item = input.Principal }); conditions.Add(-1, condition); } if (input.Receiver != 0) { var condition = new SearchCondition(); // Writelog("PropSecureReceiver=" + PropSecureReceiver.ID); condition.ConditionType = MFConditionType.MFConditionTypeEqual; condition.Expression.DataPropertyValuePropertyDef = PropSecureReceiver.ID; condition.TypedValue.SetValueToLookup(new Lookup { Item = input.Receiver }); conditions.Add(-1, condition); } ObjectVersions allwork = env.Vault.ObjectSearchOperations.SearchForObjectsByConditionsEx(conditions, MFSearchFlags.MFSearchFlagNone, false, 0, 0).GetAsObjectVersions(); #endregion search issuenotice // Writelog("allwork=" + allwork.Count); string templatefile = GetTemplateFile(env); try { object oMissing = Missing.Value; object objWhat = WdGoToItem.wdGoToPage; object objWhich = WdGoToDirection.wdGoToLast; var app = new Application(); object unknow = Type.Missing; // var msocoding = MsoEncoding.msoEncodingSimplifiedChineseGB18030; Document doc = app.Documents.Open(templatefile, ref unknow, false, ref unknow, ref unknow, ref unknow, // ref unknow, ref unknow, ref unknow, ref unknow, msocoding, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow); int issueindex = 0;//问题唯一序号,跨页接续 int tableindex = 1; string temppath = Path.GetTempPath(); doc.Content.Copy(); Writelog(String.Format("vault:{0},conditions{1},results:{2}", env.Vault.Name, env.Input, allwork.Count)); int rowpos = 1;//问题填写位置,每页刷新 bool newpage = false; foreach (ObjectVersion objectVersion in allwork) { // Writelog("debug info aaaa"); if (newpage) { newpage = false; // Writelog("debug info bbbb"); object nothing = Missing.Value; Paragraph para = doc.Content.Paragraphs.Add(ref nothing); object pBreak = (int)WdBreakType.wdSectionBreakNextPage; para.Range.InsertBreak(ref pBreak); // Writelog("debug info bbbb1111"); app.Selection.GoTo(ref objWhat, ref objWhich, ref unknow, ref unknow); // Writelog("debug info dddd"); app.Selection.Paste(); // Writelog("debug info ffff"); tableindex++; rowpos = 1; } PropertyValues onepvs = env.Vault.ObjectPropertyOperations.GetProperties(objectVersion.ObjVer); issueindex++; string issuename = env.Vault.Name; // Writelog("debug info 6666"); doc.Tables[tableindex].Cell(4, 2).Range.Text = issuename; // Writelog("debug info 7777"); int rowindex = 6 + rowpos; string secureissuename = onepvs.SearchForProperty(PropIssueCategory).GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(rowindex, 1).Range.Text = issueindex.ToString(CultureInfo.InvariantCulture); doc.Tables[tableindex].Cell(rowindex, 2).Range.Text = secureissuename; doc.Tables[tableindex].Cell(rowindex, 3).Range.Text = onepvs.SearchForProperty(PropSecureIssues.ID).GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(rowindex, 4).Range.Text = onepvs.SearchForProperty(PropAdjustMeasure.ID).GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(rowindex, 5).Range.Text = onepvs.SearchForProperty(PropPrincipal.ID) .GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(rowindex, 6).Range.Text = onepvs.SearchForProperty(PropSecureReceiver.ID) .GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(rowindex, 7).Range.Text = onepvs.SearchForProperty(PropAdjustMan.ID) .GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(rowindex, 8).Range.Text = onepvs.SearchForProperty(PropFuChaRen.ID) .GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(rowindex, 9).Range.Text = onepvs.SearchForProperty(PropCountercheckDescription.ID) .GetValueAsLocalizedText(); // Writelog(string.Format("表 {0}, 行 {1},序号 {2}, 行号 {3}",tableindex,rowindex,issueindex,rowpos)); if (rowpos++ >= 10) { newpage = true; } } int index = 0; foreach (ObjectVersion objectVersion in allwork) { PropertyValues onepvs = env.Vault.ObjectPropertyOperations.GetProperties(objectVersion.ObjVer); object nothing = Missing.Value; Paragraph para = doc.Content.Paragraphs.Add(ref nothing); object pBreak = (int)WdBreakType.wdSectionBreakNextPage; para.Range.InsertBreak(ref pBreak); app.Selection.GoTo(ref objWhat, ref objWhich, ref unknow, ref unknow); app.Selection.PageSetup.Orientation = WdOrientation.wdOrientPortrait; Range range = app.Selection.Range; Table table = app.Selection.Tables.Add(range, 7, 1, ref oMissing, ref oMissing); table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleDouble; table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; table.Cell(1, 1).Split(1, 2); for (int i = 2; i <= 3; i++) { table.Cell(i, 1).Split(1, 4); } //Writelog("debug info 888111"); //app.Selection.TypeText("序号:" + page); //Writelog("debug info 999000 v1"); table.Cell(1, 1).Range.Text = "序号:"; table.Cell(1, 2).Range.Text = (++index).ToString(CultureInfo.InvariantCulture); //table.Cell(1, 3).Range.Text = "存在问题:"; //table.Cell(1, 4).Range.Text = // onepvs.SearchForProperty(PropSecureIssues.ID).GetValueAsLocalizedText(); //Writelog("debug info 1111 v1-" + tableindex); //table.Cell(rowindex, 1).Range.Text = "检查负责人:"; table.Cell(2, 1).Range.Text = "检查日期:"; //table.Cell(2, 2).Range.Text = // onepvs.SearchForProperty(PropPrincipal.ID) // .GetValueAsLocalizedText(); table.Cell(2, 2).Range.Text = onepvs.SearchForProperty(PropCheckDate.ID) .GetValueAsLocalizedText(); //Writelog("debug info 222 v1-" + tableindex); //table.Cell(rowindex, 1).Range.Text = "接收人 :"; //table.Cell(rowindex++, 3).Range.Text = "整改人:"; //table.Cell(3, 2).Range.Text = // onepvs.SearchForProperty(PropSecureReceiver.ID) // .GetValueAsLocalizedText(); //table.Cell(3, 4).Range.Text = // onepvs.SearchForProperty(PropAdjustMan.ID) // .GetValueAsLocalizedText(); // Writelog("debug info 333 v1-" + tableindex); table.Cell(2, 3).Range.Text = "整改期限 :"; table.Cell(3, 3).Range.Text = "整改次数:"; table.Cell(2, 4).Range.Text = onepvs.SearchForProperty(PropZhengGaiQiXin.ID) .GetValueAsLocalizedText(); table.Cell(3, 4).Range.Text = onepvs.SearchForProperty(PropRectificationCount.ID) .GetValueAsLocalizedText(); //Writelog("debug info 444 v1-" + tableindex); //table.Cell(rowindex, 1).Range.Text = "复查人 :"; table.Cell(3, 1).Range.Text = "复查日期:"; //table.Cell(5, 2).Range.Text = // onepvs.SearchForProperty(PropFuChaRen.ID) // .GetValueAsLocalizedText(); table.Cell(3, 2).Range.Text = onepvs.SearchForProperty(PropReviewDate.ID) .GetValueAsLocalizedText(); // Writelog("debug info 555 v1-" + tableindex); // int rowindex = 2; table.Cell(4, 1).Range.Text = "整改前照片:"; table.Cell(6, 1).Range.Text = "复查照片:"; ObjectFiles files = env.Vault.ObjectFileOperations.GetFiles(objectVersion.ObjVer); int picrow = 5; // Writelog("before 000000000000"); foreach (ObjectFile objectFile in files) { string apicture = temppath + objectFile.GetNameForFileSystem(); env.Vault.ObjectFileOperations.DownloadFile(objectFile.ID, objectFile.Version, apicture); object linkToFile = false; object saveWithDocument = true; object anchor = table.Cell(picrow, 1).Range; InlineShape insh = doc.InlineShapes.AddPicture(apicture, ref linkToFile, ref saveWithDocument, ref anchor); insh.Height = 259; insh.Width = 416; picrow += 2; if (picrow > 7) { break; } } } doc.Close(); app.Quit(); } catch (Exception ex) { Writelog(ex.Message); } var pvs = new PropertyValues(); var pv = new PropertyValue { PropertyDef = 0 }; pv.Value.SetValue(MFDataType.MFDatatypeText, "securenoticereport"); pvs.Add(-1, pv); pv.PropertyDef = 100; pv.Value.SetValueToLookup(new Lookup { Item = ClassSecureReport }); pvs.Add(-1, pv); var file = new SourceObjectFile { Title = "report", SourceFilePath = templatefile, Extension = "docx" }; try { ObjectVersionAndProperties t = env.Vault.ObjectOperations.CreateNewSFDObject(0, pvs, file, true); ObjectFiles f = env.Vault.ObjectFileOperations.GetFiles(t.ObjVer); rpd.Objid = t.ObjVer.ID; rpd.Objtype = t.ObjVer.Type; rpd.Objversion = t.ObjVer.Version; rpd.Fileid = f[1].FileVer.ID; rpd.Fileversion = f[1].FileVer.Version; } catch (Exception ex) { Writelog("getsecurenotice - create object :" + ex.Message); } } catch (Exception ex) { Writelog(env.Input + "GetSecureNotice error:" + ex.Message); } var ret = JsonConvert.SerializeObject(rpd, Formatting.None); Writelog("GetSecureNotice ok return:" + ret); return(ret); }
//Export Button private void button1_Click(object sender, EventArgs e, Vault currVault, MFilesClientApplication mFilesApp) { //MessageBox.Show(currVault.Name); SaveFileDialog saveFile = new SaveFileDialog(); saveFile.Filter = "XML Files (*.xml)|*.xml"; if (saveFile.ShowDialog() == DialogResult.OK) { //pull invoices using search conditions var searchConditions = new SearchConditions(); //is it not deleted var isNotDeleted = new SearchCondition(); isNotDeleted.Expression.DataStatusValueType = MFStatusType.MFStatusTypeDeleted; isNotDeleted.Expression.DataStatusValueDataFunction = MFDataFunction.MFDataFunctionNoOp; isNotDeleted.ConditionType = MFConditionType.MFConditionTypeNotEqual; isNotDeleted.TypedValue.SetValue(MFDataType.MFDatatypeBoolean, true); searchConditions.Add(-1, isNotDeleted); //is it part of the Invoice workflow var isInvoice = new SearchCondition(); isInvoice.Expression.DataPropertyValuePropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefWorkflow; isInvoice.ConditionType = MFConditionType.MFConditionTypeEqual; isInvoice.TypedValue.SetValue(MFDataType.MFDatatypeLookup, Properties.Settings.Default.invoiceWorkflow); searchConditions.Add(-1, isInvoice); //is it in the accounting state var isAccounting = new SearchCondition(); isAccounting.Expression.DataPropertyValuePropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefState; isAccounting.ConditionType = MFConditionType.MFConditionTypeEqual; isAccounting.TypedValue.SetValue(MFDataType.MFDatatypeLookup, Properties.Settings.Default.stateAccounting); searchConditions.Add(-1, isAccounting); //Perform search var invoices = currVault.ObjectSearchOperations.SearchForObjectsByConditions(searchConditions, MFSearchFlags.MFSearchFlagNone, false); //start output file XElement output = new XElement("YsiTran"); XElement payables = new XElement("Payables"); //get post month var postMonthForm = new PostMonth(); postMonthForm.ShowDialog(); //loop through invoices collecting at import workflow state, build XML file from the inside out. int count = 0; foreach (ObjectVersion invoice in invoices) { XElement payable = new XElement("Payable"); double totalAmount = 0; count++; var propValues = new PropertyValues(); var currPropertyValue = new PropertyValue(); var objLedger = new ObjectVersion(); propValues = currVault.ObjectPropertyOperations.GetProperties(invoice.ObjVer); XElement details = new XElement("Details"); //Get Ledger Entry reference currPropertyValue = propValues.SearchForProperty(Properties.Settings.Default.propLedgerEntry); if (currPropertyValue.TypedValue.DataType == MFDataType.MFDatatypeMultiSelectLookup) { var lookups = new Lookups(); lookups = currPropertyValue.TypedValue.GetValueAsLookups(); int i = 0; foreach (Lookup lookup in lookups) { XElement detail = new XElement("Detail"); var propDef = new PropertyDef(); propDef = currVault.PropertyDefOperations.GetPropertyDef(currPropertyValue.PropertyDef); var valListObjType = new ObjType(); valListObjType = currVault.ValueListOperations.GetValueList(propDef.ValueList); if (valListObjType.RealObjectType) { i++; //Get Ledgery Entry Object var objDetail = new ObjVer(); objDetail.SetIDs(valListObjType.ID, lookup.Item, lookup.Version); var detailValues = new PropertyValues(); var detailValue = new PropertyValue(); detailValues = currVault.ObjectPropertyOperations.GetProperties(objDetail); //MessageBox.Show(i.ToString()); //Get Account detailValue = detailValues.SearchForProperty(Properties.Settings.Default.propAccount); if (detailValue.TypedValue.DataType == MFDataType.MFDatatypeMultiSelectLookup) { Lookup lookupAccount = new Lookup(); lookupAccount = detailValue.TypedValue.GetValueAsLookup(); propDef = currVault.PropertyDefOperations.GetPropertyDef(detailValue.PropertyDef); valListObjType = currVault.ValueListOperations.GetValueList(propDef.ValueList); if (valListObjType.RealObjectType) { //Get Account Number var objAccount = new ObjVer(); objAccount.SetIDs(valListObjType.ID, lookupAccount.Item, lookupAccount.Version); var accountValues = new PropertyValues(); var accountValue = new PropertyValue(); accountValues = currVault.ObjectPropertyOperations.GetProperties(objAccount); accountValue = accountValues.SearchForProperty(Properties.Settings.Default.propGLCode); XElement account = new XElement("AccountId"); account.SetValue(accountValue.GetValueAsLocalizedText()); detail.Add(account); } } //get Description-Notes detailValue = detailValues.SearchForProperty(Properties.Settings.Default.propDescription); XElement notes = new XElement("Notes"); notes.SetValue(detailValue.GetValueAsLocalizedText()); detail.Add(notes); //get Amount detailValue = detailValues.SearchForProperty(Properties.Settings.Default.propGLAmount); XElement amount = new XElement("Amount"); amount.SetValue(detailValue.GetValueAsLocalizedText()); detail.Add(amount); totalAmount += Convert.ToDouble(detailValue.GetValueAsLocalizedText()); } XElement propertyID = new XElement("PropertyId"); detail.Add(propertyID); details.Add(detail); } } //Get Property ID currPropertyValue = propValues.SearchForProperty(Properties.Settings.Default.propProperty); if (currPropertyValue.TypedValue.DataType == MFDataType.MFDatatypeMultiSelectLookup) { //Getlookup of property to find object var lookup = new Lookup(); lookup = currPropertyValue.TypedValue.GetValueAsLookup(); var propDef = new PropertyDef(); propDef = currVault.PropertyDefOperations.GetPropertyDef(currPropertyValue.PropertyDef); var valListObjType = new ObjType(); valListObjType = currVault.ValueListOperations.GetValueList(propDef.ValueList); if (valListObjType.RealObjectType) { //Get property ID var objProperty = new ObjVer(); objProperty.SetIDs(valListObjType.ID, lookup.Item, lookup.Version); var propertyValues = new PropertyValues(); var propertyValue = new PropertyValue(); propertyValues = currVault.ObjectPropertyOperations.GetProperties(objProperty); propertyValue = propertyValues.SearchForProperty(Properties.Settings.Default.propPropertyID); IEnumerable <XElement> ieDetails = from el in details.Elements() select el; //loop through items foreach (XElement detail in ieDetails) { //Check that a check has been cut in Yardi. if (detail.Elements("PropertyId").Any()) { detail.Element("PropertyId").SetValue(propertyValue.GetValueAsLocalizedText()); } } } } //Get Vendor ID currPropertyValue = propValues.SearchForProperty(Properties.Settings.Default.propVendor); if (currPropertyValue.TypedValue.DataType == MFDataType.MFDatatypeMultiSelectLookup) { //Getlookup of vendor to find object var lookup = new Lookup(); lookup = currPropertyValue.TypedValue.GetValueAsLookup(); var propDef = new PropertyDef(); propDef = currVault.PropertyDefOperations.GetPropertyDef(currPropertyValue.PropertyDef); var valListObjType = new ObjType(); valListObjType = currVault.ValueListOperations.GetValueList(propDef.ValueList); if (valListObjType.RealObjectType) { //Get Vendor ID var objProperty = new ObjVer(); objProperty.SetIDs(valListObjType.ID, lookup.Item, lookup.Version); var vendorValues = new PropertyValues(); var vendorValue = new PropertyValue(); vendorValues = currVault.ObjectPropertyOperations.GetProperties(objProperty); vendorValue = vendorValues.SearchForProperty(Properties.Settings.Default.propYardiCode); XElement propertyID = new XElement("PersonId"); propertyID.SetValue(vendorValue.GetValueAsLocalizedText()); payable.Add(propertyID); } } // Add details to payable payable.Add(details); //Add Post Month XElement postMonth = new XElement("PostMonth"); postMonth.SetValue(postMonthForm.StrPostMonth); payable.Add(postMonth); //Get link to object XElement link = new XElement("Notes"); string strLink = "m-files://show/" + Properties.Settings.Default.vaultGUID + "/" + invoice.ObjVer.Type.ToString() + "-" + invoice.ObjVer.ID.ToString(); link.SetValue(strLink); payable.Add(link); //get Invoice Number currPropertyValue = propValues.SearchForProperty(Properties.Settings.Default.propInvoiceNumber); XElement invoiceNumber = new XElement("InvoiceNumber"); invoiceNumber.SetValue(currPropertyValue.GetValueAsLocalizedText()); payable.Add(invoiceNumber); //get Invoice date currPropertyValue = propValues.SearchForProperty(Properties.Settings.Default.propInvoiceDate); XElement invoiceDate = new XElement("InvoiceDate"); invoiceDate.SetValue(currPropertyValue.GetValueAsLocalizedText()); payable.Add(invoiceDate); //get Due Date currPropertyValue = propValues.SearchForProperty(Properties.Settings.Default.propDueDate); XElement dueDate = new XElement("DueDate"); dueDate.SetValue(currPropertyValue.GetValueAsLocalizedText()); payable.Add(dueDate); //Set Expense Type XElement expenseType = new XElement("ExpenseType"); expenseType.SetValue("Contract"); payable.Add(expenseType); //Set Total XElement total = new XElement("TotalAmount"); total.SetValue(totalAmount.ToString()); payables.Add(payable); //change workflow state propValues.SearchForProperty((int)MFBuiltInPropertyDef.MFBuiltInPropertyDefState).TypedValue.SetValue(MFDataType.MFDatatypeLookup, Properties.Settings.Default.stateProcessing); currVault.ObjectPropertyOperations.SetAllProperties(invoice.ObjVer, true, propValues); } output.Add(payables); output.Save(saveFile.FileName); MessageBox.Show(count.ToString() + " Files Exported!"); } }
/// <summary> /// Updates the matter stamped properties with new details for user permissions. /// </summary> /// <param name="clientContext">ClientContext object</param> /// <param name="matterDetails">MatterDetails object</param> /// <param name="matter">Matter object</param> /// <param name="matterStampedProperties">Matter stamped properties</param> /// <param name="isEditMode">Page opened in edit mode</param> /// <returns>Status of operation</returns> internal static string UpdateMatterStampedProperties(ClientContext clientContext, MatterDetails matterDetails, Matter matter, PropertyValues matterStampedProperties, bool isEditMode) { string result = ConstantStrings.FALSE; try { if (null != clientContext && null != matter && null != matterDetails && (0 < matterStampedProperties.FieldValues.Count)) { Dictionary<string, string> propertyList = new Dictionary<string, string>(); // Get existing stamped properties string stampedUsers = GetStampPropertyValue(matterStampedProperties.FieldValues, ServiceConstantStrings.StampedPropertyMatterCenterUsers); string stampedPermissions = GetStampPropertyValue(matterStampedProperties.FieldValues, ServiceConstantStrings.StampedPropertyMatterCenterPermissions); string stampedRoles = GetStampPropertyValue(matterStampedProperties.FieldValues, ServiceConstantStrings.StampedPropertyMatterCenterRoles); string stampedResponsibleAttorneys = GetStampPropertyValue(matterStampedProperties.FieldValues, ServiceConstantStrings.StampedPropertyResponsibleAttorney); string stampedTeamMembers = GetStampPropertyValue(matterStampedProperties.FieldValues, ServiceConstantStrings.StampedPropertyTeamMembers); string stampedBlockedUploadUsers = GetStampPropertyValue(matterStampedProperties.FieldValues, ServiceConstantStrings.StampedPropertyBlockedUploadUsers); string currentPermissions = string.Join(ConstantStrings.DOLLAR + ConstantStrings.Pipe + ConstantStrings.DOLLAR, matter.Permissions.Where(user => !string.IsNullOrWhiteSpace(user))); string currentRoles = string.Join(ConstantStrings.DOLLAR + ConstantStrings.Pipe + ConstantStrings.DOLLAR, matter.Roles.Where(user => !string.IsNullOrWhiteSpace(user))); string currentBlockedUploadUsers = string.Join(ConstantStrings.Semicolon, matterDetails.UploadBlockedUsers.Where(user => !string.IsNullOrWhiteSpace(user))); string currentUsers = GetMatterAssignedUsers(matter); string finalMatterPermissions = string.IsNullOrWhiteSpace(stampedPermissions) || isEditMode ? currentPermissions : string.Concat(stampedPermissions, ConstantStrings.DOLLAR + ConstantStrings.Pipe + ConstantStrings.DOLLAR, currentPermissions); string finalMatterRoles = string.IsNullOrWhiteSpace(stampedRoles) || isEditMode ? currentRoles : string.Concat(stampedRoles, ConstantStrings.DOLLAR + ConstantStrings.Pipe + ConstantStrings.DOLLAR, currentRoles); string finalResponsibleAttorneys = string.IsNullOrWhiteSpace(stampedResponsibleAttorneys) || isEditMode ? matterDetails.ResponsibleAttorney : string.Concat(stampedResponsibleAttorneys, ConstantStrings.Semicolon, matterDetails.ResponsibleAttorney); string finalTeamMembers = string.IsNullOrWhiteSpace(stampedTeamMembers) || isEditMode ? matterDetails.TeamMembers : string.Concat(stampedTeamMembers, ConstantStrings.Semicolon, matterDetails.TeamMembers); string finalMatterCenterUsers = string.IsNullOrWhiteSpace(stampedUsers) || isEditMode ? currentUsers : string.Concat(stampedUsers, ConstantStrings.DOLLAR + ConstantStrings.Pipe + ConstantStrings.DOLLAR, currentUsers); string finalBlockedUploadUsers = string.IsNullOrWhiteSpace(stampedBlockedUploadUsers) || isEditMode ? currentBlockedUploadUsers : string.Concat(stampedBlockedUploadUsers, ConstantStrings.Semicolon, currentBlockedUploadUsers); propertyList.Add(ServiceConstantStrings.StampedPropertyResponsibleAttorney, Encoder.HtmlEncode(finalResponsibleAttorneys)); propertyList.Add(ServiceConstantStrings.StampedPropertyTeamMembers, Encoder.HtmlEncode(finalTeamMembers)); propertyList.Add(ServiceConstantStrings.StampedPropertyBlockedUploadUsers, Encoder.HtmlEncode(finalBlockedUploadUsers)); propertyList.Add(ServiceConstantStrings.StampedPropertyMatterCenterRoles, Encoder.HtmlEncode(finalMatterRoles)); propertyList.Add(ServiceConstantStrings.StampedPropertyMatterCenterPermissions, Encoder.HtmlEncode(finalMatterPermissions)); propertyList.Add(ServiceConstantStrings.StampedPropertyMatterCenterUsers, Encoder.HtmlEncode(finalMatterCenterUsers)); Lists.SetPropertBagValuesForList(clientContext, matterStampedProperties, matter.Name, propertyList); result = ConstantStrings.TRUE; } } catch (Exception) { throw; //// This will transfer control to catch block of parent function. } return result; }
public bool UpdateMatterStampedProperties(ClientContext clientContext, MatterDetails matterDetails, Matter matter, PropertyValues matterStampedProperties, bool isEditMode, IConfigurationRoot configuration) { try { if (null != clientContext && null != matter && null != matterDetails && (0 < matterStampedProperties.FieldValues.Count)) { Dictionary<string, string> propertyList = new Dictionary<string, string>(); // Get existing stamped properties string stampedUsers = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyMatterCenterUsers"]); string stampedUserEmails = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyMatterCenterUserEmails"]); string stampedPermissions = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyMatterCenterPermissions"]); string stampedRoles = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyMatterCenterRoles"]); string stampedResponsibleAttorneys = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyResponsibleAttorney"]); string stampedResponsibleAttorneysEmail = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyResponsibleAttorneyEmail"]); string stampedTeamMembers = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyTeamMembers"]); string stampedBlockedUploadUsers = GetStampPropertyValue(matterStampedProperties.FieldValues, configuration["Matter:StampedPropertyBlockedUploadUsers"]); string currentPermissions = string.Join(ServiceConstants.DOLLAR + ServiceConstants.PIPE + ServiceConstants.DOLLAR, matter.Permissions.Where(user => !string.IsNullOrWhiteSpace(user))); string currentRoles = string.Join(ServiceConstants.DOLLAR + ServiceConstants.PIPE + ServiceConstants.DOLLAR, matter.Roles.Where(user => !string.IsNullOrWhiteSpace(user))); string currentBlockedUploadUsers = string.Join(ServiceConstants.SEMICOLON, matterDetails.UploadBlockedUsers.Where(user => !string.IsNullOrWhiteSpace(user))); string currentUsers = GetMatterAssignedUsers(matter); string currentUserEmails = SPList.GetMatterAssignedUsersEmail(clientContext, matter); string finalMatterPermissions = string.Concat(stampedPermissions, ServiceConstants.DOLLAR + ServiceConstants.PIPE + ServiceConstants.DOLLAR, currentPermissions); string finalMatterRoles = string.Concat(stampedRoles, ServiceConstants.DOLLAR + ServiceConstants.PIPE + ServiceConstants.DOLLAR, currentRoles); string finalTeamMembers = string.Concat(stampedTeamMembers, ServiceConstants.SEMICOLON, ServiceConstants.SEMICOLON, matterDetails.TeamMembers); string finalMatterCenterUsers = string.Concat(stampedUsers, ServiceConstants.DOLLAR + ServiceConstants.PIPE + ServiceConstants.DOLLAR, currentUsers); string finalBlockedUploadUsers = string.Concat(stampedBlockedUploadUsers, ServiceConstants.SEMICOLON, currentBlockedUploadUsers); //if(stampedUserEmails.LastIndexOf("$|$")>0) //{ // stampedUserEmails = stampedUserEmails.Remove(stampedUserEmails.Length - 3); //} string finalMatterCenterUserEmails = string.Concat(stampedUserEmails, ServiceConstants.DOLLAR + ServiceConstants.PIPE + ServiceConstants.DOLLAR, currentUserEmails); string finalResponsibleAttorneysEmail = ""; string finalResponsibleAttorneys = ""; if (matterDetails.ResponsibleAttorneyEmail!=null) { finalResponsibleAttorneysEmail = string.IsNullOrWhiteSpace(stampedResponsibleAttorneysEmail) || isEditMode ? matterDetails.ResponsibleAttorneyEmail : string.Concat(stampedResponsibleAttorneysEmail, ServiceConstants.SEMICOLON, matterDetails.ResponsibleAttorneyEmail); finalResponsibleAttorneys = string.IsNullOrWhiteSpace(stampedResponsibleAttorneys) || isEditMode ? matterDetails.ResponsibleAttorney : string.Concat(stampedResponsibleAttorneys, ServiceConstants.SEMICOLON, matterDetails.ResponsibleAttorney); } else { finalResponsibleAttorneysEmail = stampedResponsibleAttorneysEmail; finalResponsibleAttorneys = stampedResponsibleAttorneys; } propertyList.Add(configuration["Matter:StampedPropertyResponsibleAttorney"], WebUtility.HtmlEncode(finalResponsibleAttorneys)); propertyList.Add(configuration["Matter:StampedPropertyResponsibleAttorneyEmail"], WebUtility.HtmlEncode(finalResponsibleAttorneysEmail)); propertyList.Add(configuration["Matter:StampedPropertyTeamMembers"], WebUtility.HtmlEncode(finalTeamMembers)); propertyList.Add(configuration["Matter:StampedPropertyBlockedUploadUsers"], WebUtility.HtmlEncode(finalBlockedUploadUsers)); propertyList.Add(configuration["Matter:StampedPropertyMatterCenterRoles"], WebUtility.HtmlEncode(finalMatterRoles)); propertyList.Add(configuration["Matter:StampedPropertyMatterCenterPermissions"], WebUtility.HtmlEncode(finalMatterPermissions)); propertyList.Add(configuration["Matter:StampedPropertyMatterCenterUsers"], WebUtility.HtmlEncode(finalMatterCenterUsers)); propertyList.Add(configuration["Matter:StampedPropertyMatterCenterUserEmails"], WebUtility.HtmlEncode(finalMatterCenterUserEmails)); SPList.SetPropertBagValuesForList(clientContext, matterStampedProperties, matter.Name, propertyList); return true; } } catch (Exception) { throw; //// This will transfer control to catch block of parent function. } return false; }
private static bool CSOMWebPartPropertiesValidation(string sourceContent, PropertyValues properties) { int scount = 0; int tcount = 0; XmlDocument sDoc = new XmlDocument(); sDoc.LoadXml(sourceContent); XmlNodeList sProps = sDoc.GetElementsByTagName("property"); string[] ignoreProperties = { "xmldefinition", "height", "width" }; if (sProps.Count != 0) { foreach (XmlNode xnSource in sProps) { string saName = xnSource.Attributes["name"].InnerText.ToString(); string saType = xnSource.Attributes["type"].InnerText.ToString(); string saText = xnSource.InnerText; if (!ignoreProperties.Contains(saName.ToLower())) { scount++; foreach (var tVariable in properties.FieldValues) { if (saName == tVariable.Key && saText == Convert.ToString(tVariable.Value)) { tcount++; break; } else if (saName == tVariable.Key) { int position = Convert.ToInt32(tVariable.Value); string sourceText = saText.ToLower().Trim(); bool result = CheckProperty(tVariable.Key, sourceText, position); if (result) { tcount++; } else { return(false); } } } } } } else if (sDoc.LastChild.Name == "WebPart") { sProps = sDoc.LastChild.ChildNodes; foreach (XmlNode sProp in sProps) { string speName = sProp.Name; string speText = sProp.InnerText; if (speName.ToLower() != "height" && speName.ToLower() != "width") { scount++; foreach (var pfvalue in properties.FieldValues) { if (speName == pfvalue.Key && speText == Convert.ToString(pfvalue.Value)) { tcount++; break; } else if (speName == pfvalue.Key) { int position = Convert.ToInt32(pfvalue.Value); string sourceText = speName.ToLower().Trim(); bool result = CheckProperty(pfvalue.Key, sourceText, position); if (result) { tcount++; break; } else { return(false); } } } } } } if (scount != tcount) { return(false); } return(true); }
/// <summary> /// Get's the type of the web part by detecting if from the available properties /// </summary> /// <param name="properties">Web part properties to analyze</param> /// <returns>Type of the web part as fully qualified name</returns> public string GetTypeFromProperties(PropertyValues properties) { // Check for XSLTListView web part string[] xsltWebPart = new string[] { "ListUrl", "ListId", "Xsl", "JSLink", "ShowTimelineIfAvailable" }; if (CheckWebPartProperties(xsltWebPart, properties)) { return(WebParts.XsltListView); } // Check for ListView web part string[] listWebPart = new string[] { "ListViewXml", "ListName", "ListId", "ViewContentTypeId", "PageType" }; if (CheckWebPartProperties(listWebPart, properties)) { return(WebParts.ListView); } // check for Media web part string[] mediaWebPart = new string[] { "AutoPlay", "MediaSource", "Loop", "IsPreviewImageSourceOverridenForVideoSet", "PreviewImageSource" }; if (CheckWebPartProperties(mediaWebPart, properties)) { return(WebParts.Media); } // check for SlideShow web part string[] slideShowWebPart = new string[] { "LibraryGuid", "Layout", "Speed", "ShowToolbar", "ViewGuid" }; if (CheckWebPartProperties(slideShowWebPart, properties)) { return(WebParts.PictureLibrarySlideshow); } // check for Chart web part string[] chartWebPart = new string[] { "ConnectionPointEnabled", "ChartXml", "DataBindingsString", "DesignerChartTheme" }; if (CheckWebPartProperties(chartWebPart, properties)) { return(WebParts.Chart); } // check for Site Members web part string[] membersWebPart = new string[] { "NumberLimit", "DisplayType", "MembershipGroupId", "Toolbar" }; if (CheckWebPartProperties(membersWebPart, properties)) { return(WebParts.Members); } // check for Silverlight web part string[] silverlightWebPart = new string[] { "MinRuntimeVersion", "WindowlessMode", "CustomInitParameters", "Url", "ApplicationXml" }; if (CheckWebPartProperties(silverlightWebPart, properties)) { return(WebParts.Silverlight); } // check for Add-in Part web part string[] addinPartWebPart = new string[] { "FeatureId", "ProductWebId", "ProductId" }; if (CheckWebPartProperties(addinPartWebPart, properties)) { return(WebParts.Client); } // check for Script Editor web part string[] scriptEditorWebPart = new string[] { "Content" }; if (CheckWebPartProperties(scriptEditorWebPart, properties)) { return(WebParts.ScriptEditor); } // This needs to be last, but we still pages with sandbox user code web parts on them string[] sandboxWebPart = new string[] { "CatalogIconImageUrl", "AllowEdit", "TitleIconImageUrl", "ExportMode" }; if (CheckWebPartProperties(sandboxWebPart, properties)) { return(WebParts.SPUserCode); } return("NonExportable_Unidentified"); }
public void ReturnsCorrectValueListItems_OneInvalid() { // IDs used. var propertyDefId = 1234; var valueListId = 123; // Mock the property definition operations object. var propertyDefinitionsMock = new Mock <VaultPropertyDefOperations>(); propertyDefinitionsMock.Setup(m => m.GetPropertyDef(It.IsAny <int>())) .Returns((int propertyDef) => { // Ensure that the property definition Id is correct. Assert.AreEqual(propertyDefId, propertyDef); // Return a property definition that is not based on a value list. return(new PropertyDef() { ID = propertyDefId, DataType = MFDataType.MFDatatypeMultiSelectLookup, BasedOnValueList = true, ValueList = valueListId }); }) .Verifiable(); // Mock the value list item operations object. var valueListItemsMock = new Mock <VaultValueListItemOperations>(); valueListItemsMock.Setup(m => m.GetValueListItemByID(It.IsAny <int>(), It.IsAny <int>())) .Returns((int vlid, int vliid) => { // Did we get the right list and item ids? Assert.AreEqual(valueListId, vlid); if (vliid == 456) { throw new COMException(); } // Return an undeleted item. return(Mock.Of <ValueListItem> ( i => i.ID == vliid && i.ValueListID == valueListId && i.Deleted == false )); }); // Mock the object type operations object. var objectTypeOperationsMock = new Mock <VaultObjectTypeOperations>(); objectTypeOperationsMock.Setup(m => m.GetObjectType(It.IsAny <int>())) .Returns((int objectTypeId) => { return(new ObjType() { ID = 101 }); }); // Mock the vault. var vaultMock = this.GetVaultMock(); vaultMock.Setup(m => m.PropertyDefOperations).Returns(propertyDefinitionsMock.Object); vaultMock.Setup(m => m.ValueListItemOperations).Returns(valueListItemsMock.Object); vaultMock.Setup(m => m.ObjectTypeOperations).Returns(objectTypeOperationsMock.Object); // Set up the data for the ObjVerEx. var objVer = new ObjVer(); objVer.SetIDs(0, 1, 1); var objectVersionMock = new Mock <ObjectVersion>(); objectVersionMock.SetupGet(m => m.ObjVer) .Returns(objVer); var properties = new PropertyValues(); { var pv = new PropertyValue(); pv.PropertyDef = propertyDefId; pv.TypedValue.SetValue(MFDataType.MFDatatypeMultiSelectLookup, new object[] { 123, 456, 789 }); properties.Add(1, pv); } // Create the ObjVerEx. var objVerEx = new Common.ObjVerEx(vaultMock.Object, objectVersionMock.Object, properties); // Use the method. var items = objVerEx.GetPropertyAsValueListItems(propertyDefId); Assert.IsNotNull(items); Assert.AreEqual(2, items.Count); Assert.AreEqual(123, items[0].ID); Assert.AreEqual(789, items[1].ID); Assert.IsFalse(items[0].Deleted); Assert.IsFalse(items[1].Deleted); }
protected virtual void DeployProperty(object modelHost, PropertyValues properties, PropertyDefinition property) { var currentValue = properties.FieldValues.ContainsKey(property.Key) ? properties[property.Key] : null; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentValue, ObjectType = typeof(object), ObjectDefinition = property, ModelHost = modelHost }); if (currentValue == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new property"); properties[property.Key] = property.Value; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = property.Value, ObjectType = typeof(object), ObjectDefinition = property, ModelHost = modelHost }); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing property"); if (property.Overwrite) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Overwrite = true. Overwriting property."); properties[property.Key] = property.Value; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = property.Value, ObjectType = typeof(object), ObjectDefinition = property, ModelHost = modelHost }); } else { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Overwrite = false. Skipping property."); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentValue, ObjectType = typeof(object), ObjectDefinition = property, ModelHost = modelHost }); } } }
public void ReturnsEmptyCollectionIfPropertyNotInCollection() { // IDs used. var propertyDefId = 1234; var valueListId = 123; // Mock the property definition operations object. var propertyDefinitionsMock = new Mock <VaultPropertyDefOperations>(); propertyDefinitionsMock.Setup(m => m.GetPropertyDef(It.IsAny <int>())) .Returns((int propertyDef) => { // Ensure that the property definition Id is correct. Assert.AreEqual(propertyDefId, propertyDef); // Return a property definition that is not based on a value list. return(new PropertyDef() { ID = propertyDefId, DataType = MFDataType.MFDatatypeMultiSelectLookup, BasedOnValueList = true, ValueList = valueListId }); }) .Verifiable(); // Mock the object type operations object. var objectTypeOperationsMock = new Mock <VaultObjectTypeOperations>(); objectTypeOperationsMock.Setup(m => m.GetObjectType(It.IsAny <int>())) .Returns((int objectTypeId) => { return(new ObjType() { ID = 101 }); }); // Mock the vault. var vaultMock = this.GetVaultMock(); vaultMock.Setup(m => m.PropertyDefOperations).Returns(propertyDefinitionsMock.Object); vaultMock.Setup(m => m.ObjectTypeOperations).Returns(objectTypeOperationsMock.Object); // Set up the data for the ObjVerEx. var objVer = new ObjVer(); objVer.SetIDs(0, 1, 1); var objectVersionMock = new Mock <ObjectVersion>(); objectVersionMock.SetupGet(m => m.ObjVer) .Returns(objVer); var properties = new PropertyValues(); // Create the ObjVerEx. var objVerEx = new Common.ObjVerEx(vaultMock.Object, objectVersionMock.Object, properties); // Use the method. var items = objVerEx.GetPropertyAsValueListItems(propertyDefId); Assert.IsNotNull(items); Assert.AreEqual(0, items.Count); }
public void CreateWorkitem() { const string type = "Story"; const string title = "Story Name"; const string description = "Story description"; const string projectToken = "Scope:0"; const string externalFieldName = "FieldName"; const string externalId = "externalId"; const string externalSystemName = "External System Name"; const string priorityId = "Priority:12"; const string owners = "Onwer_1,Owners_2"; var memberAssetType = new TestAssetType("Member"); var projectAssetType = new TestAssetType("Project"); var priorityAssetType = new TestAssetType("Priority"); var storyAttributes = new Dictionary<string, IAttributeDefinition> { {"Owners", new TestAttributeDefinition(memberAssetType, true, false, false)}, }; var storyAssetType = new TestAssetType("Story", storyAttributes); var source = TestValueId.Create(externalSystemName, "Source", 333); var sources = new PropertyValues(new List<ValueId> { source }); var assetStory = new Asset(storyAssetType); var ownersAssets = new AssetList { new Asset(new TestOid(new TestAssetType("Member"), 1, null)), new Asset(new TestOid(new TestAssetType("Member"), 2, null)), }; var queryResult = new QueryResult(ownersAssets, 2, null); Expect.Call(_mockMetaModel.GetAssetType("Scope")).Return(projectAssetType); Expect.Call(_mockQueryBuilder.QueryPropertyValues(VersionOneProcessor.WorkitemSourceType)).Return(sources); Expect.Call(_mockMetaModel.GetAssetType("Story")).Return(storyAssetType); Expect.Call(_mockServices.New(storyAssetType, Oid.Null)).Return(assetStory); Expect.Call(_mockMetaModel.GetAssetType("Member")).Return(memberAssetType); Expect.Call(_mockServices.Retrieve(null)).IgnoreArguments().Return(queryResult); Expect.Call(_mockMetaModel.GetAssetType("Priority")).Return(priorityAssetType); Expect.Call(() => _mockServices.Save(assetStory)); Expect.Call(_mockMetaModel.GetAssetType("Story")).Return(storyAssetType); Expect.Call(_mockQueryBuilder.Query("Story", new FilterTerm(null))).IgnoreArguments().Return(new AssetList { assetStory }); Expect.Call(_mockQueryBuilder.ListPropertyValues).Return(null); Expect.Call(_mockQueryBuilder.TypeResolver).Return(null); _repository.ReplayAll(); _processor.CreateWorkitem(type, title, description, projectToken, externalFieldName, externalId, externalSystemName, priorityId, owners); _repository.VerifyAll(); }
internal static TAutoHistory AutoHistory <TAutoHistory>(this EntityEntry entry, Func <TAutoHistory> createHistoryFactory) where TAutoHistory : AutoHistory { var history = createHistoryFactory(); history.TableName = entry.Metadata.GetTableName(); // Get the mapped properties for the entity type. // (include shadow properties, not include navigations & references) var properties = entry.Properties; dynamic json = new System.Dynamic.ExpandoObject(); switch (entry.State) { case EntityState.Added: foreach (var prop in properties) { if (prop.Metadata.IsKey() || prop.Metadata.IsForeignKey()) { continue; } ((IDictionary <String, Object>)json)[prop.Metadata.Name] = prop.CurrentValue != null ? prop.CurrentValue : null; } // REVIEW: what's the best way to set the RowId? history.RowId = "0"; history.Kind = EntityState.Added; history.Changed = JsonSerializer.Serialize(json); break; case EntityState.Modified: dynamic bef = new System.Dynamic.ExpandoObject(); dynamic aft = new System.Dynamic.ExpandoObject(); PropertyValues databaseValues = null; foreach (var prop in properties) { if (prop.IsModified) { if (prop.OriginalValue != null) { if (!prop.OriginalValue.Equals(prop.CurrentValue)) { ((IDictionary <String, Object>)bef)[prop.Metadata.Name] = prop.OriginalValue; } else { databaseValues = databaseValues ?? entry.GetDatabaseValues(); var originalValue = databaseValues.GetValue <object>(prop.Metadata.Name); ((IDictionary <String, Object>)bef)[prop.Metadata.Name] = originalValue != null ? originalValue : null; } } else { ((IDictionary <String, Object>)bef)[prop.Metadata.Name] = null; } ((IDictionary <String, Object>)aft)[prop.Metadata.Name] = prop.CurrentValue != null ? prop.CurrentValue : null; } } ((IDictionary <String, Object>)json)["before"] = bef; ((IDictionary <String, Object>)json)["after"] = aft; history.RowId = entry.PrimaryKey(); history.Kind = EntityState.Modified; history.Changed = JsonSerializer.Serialize(json); break; case EntityState.Deleted: foreach (var prop in properties) { ((IDictionary <String, Object>)json)[prop.Metadata.Name] = prop.OriginalValue != null ? prop.OriginalValue : null; } history.RowId = entry.PrimaryKey(); history.Kind = EntityState.Deleted; history.Changed = JsonSerializer.Serialize(json); break; case EntityState.Detached: case EntityState.Unchanged: default: throw new NotSupportedException("AutoHistory only support Deleted and Modified entity."); } return(history); }
public ObjectVersion CreateNotice(Vault mfVault, MfTask notice) { var oPropValues = new PropertyValues(); if (!string.IsNullOrEmpty(notice.Content)) { var oPropContent = new PropertyValue { PropertyDef = 41 }; oPropContent.TypedValue.SetValue(MFDataType.MFDatatypeMultiLineText, notice.Content); oPropValues.Add(-1, oPropContent); } if (notice.AssignTo > 0) { var assignTos = new List <int> { notice.AssignTo }; var oPropAssignTo = new PropertyValue { PropertyDef = 44 }; oPropAssignTo.TypedValue.SetValue(MFDataType.MFDatatypeMultiSelectLookup, assignTos.ToArray()); oPropValues.Add(-1, oPropAssignTo); } foreach (MfProperty p in notice.OtherProps) { var type = GetPropDefType(mfVault, p.PropDef); var oPropValue = new PropertyValue { PropertyDef = p.PropDef }; if (type == MFDataType.MFDatatypeLookup) { int val; if (int.TryParse(p.Value, out val)) { oPropValue.TypedValue.SetValue(MFDataType.MFDatatypeLookup, val); oPropValues.Add(-1, oPropValue); } } else if (type == MFDataType.MFDatatypeMultiSelectLookup) { if (!string.IsNullOrEmpty(p.Value)) { var ids = new List <int>(); var vArr = p.Value.Split(new[] { '_' }); foreach (string s in vArr) { int val; if (int.TryParse(s, out val)) { ids.Add(val); } } if (ids.Count > 0) { oPropValue.TypedValue.SetValue(MFDataType.MFDatatypeMultiSelectLookup, ids.ToArray()); oPropValues.Add(-1, oPropValue); } } } else if (type == MFDataType.MFDatatypeText) { oPropValue.TypedValue.SetValue(MFDataType.MFDatatypeText, p.Value); oPropValues.Add(-1, oPropValue); } else if (type == MFDataType.MFDatatypeMultiLineText) { oPropValue.TypedValue.SetValue(MFDataType.MFDatatypeMultiLineText, p.Value); oPropValues.Add(-1, oPropValue); } } //if (notice.OtherPropDef > 0 && notice.OtherPropValue > 0) //{ // var type = GetPropDefType(mfVault, notice.OtherPropDef); // var oPropValue = new PropertyValue // { // PropertyDef = notice.OtherPropDef // }; // if (type == MFDataType.MFDatatypeLookup) // { // oPropValue.TypedValue.SetValue(MFDataType.MFDatatypeLookup, notice.OtherPropValue); // oPropValues.Add(-1, oPropValue); // } // else if (type == MFDataType.MFDatatypeMultiSelectLookup) // { // var ids = new List<int> { notice.OtherPropValue }; // oPropValue.TypedValue.SetValue(MFDataType.MFDatatypeMultiSelectLookup, ids.ToArray()); // oPropValues.Add(-1, oPropValue); // } //} return(CreateMfObj(mfVault, notice.ObjType, notice.ObjClass, notice.Title, oPropValues)); }
/// <summary> /// This method creates a changeset style model for Changes being made to the entity /// This can be used to create audit logs or event queues in conjunction with IEntityOperationEventSink /// </summary> /// <param name="timestamp"></param> /// <param name="entity"></param> /// <param name="operation"></param> /// <param name="currentValues"></param> /// <param name="originalValues"></param> /// <returns></returns> protected string TrackChange(T entity, EntityOperationType operation = EntityOperationType.Unknown, PropertyValues currentValues = null, PropertyValues originalValues = null, byte[] timestamp = null) { bool nonAuditable = typeof(INonAuditable).IsAssignableFrom(typeof(T)); if (nonAuditable.Equals(false)) { //create new AuditLog object AuditLog change = new AuditLog(); try { //define properties in object change.Id = Guid.NewGuid(); change.ObjectId = entity.Id; change.CreatedBy = _caller.Identity == null ? entity.CreatedBy : _caller.Identity.Name; change.CreatedOn = DateTime.UtcNow; if (timestamp == null) { timestamp = new byte[1]; } change.Timestamp = timestamp; //name of service that is being changed change.ServiceName = entity.ToString(); //name of how entity is being changed (Add, Update, Delete) change.MethodName = operation.ToString(); change.ParametersJson = ""; //TODO: update to show parameters of method change.ExceptionJson = ""; //TODO: update to show any exceptions that arise change.ChangedFromJson = (originalValues == null) ? null : JsonConvert.SerializeObject(originalValues.ToObject()); change.ChangedToJson = (currentValues == null) ? null : JsonConvert.SerializeObject(currentValues.ToObject()); //add object to AuditLog data table DbContext.Add(change); DbContext.SaveChanges(); } catch (Exception ex) { throw new EntityOperationException(ex); } //return audit log object as a string return(change.ToString()); } return(new InvalidOperationException().Message); }
public PropertyValues QueryPropertyValues(string propertyName) { var res = new PropertyValues(); IAttributeDefinition nameDef; var query = GetPropertyValuesQuery(propertyName, out nameDef); foreach (var asset in services.Retrieve(query).Assets) { var name = asset.GetAttribute(nameDef).Value as string; res.Add(new ValueId(asset.Oid, name)); } return res; }
/// <summary> /// 给对象添加文件 /// </summary> /// <param name="vault"></param> /// <param name="obj"></param> /// <param name="removeFiles">是否删除现有文件</param> /// <param name="filePath"></param> /// <param name="pvs"></param> /// <returns></returns> public static ObjectVersion AddFiles(Vault vault, ObjectVersion obj, bool removeFiles, string[] filePath, PropertyValues pvs) { if (filePath == null || filePath.Length == 0) { return(null); } var file0 = filePath[0]; var title = Path.GetFileNameWithoutExtension(file0); var extension = Path.GetExtension(file0).TrimStart(new char[] { '.' }); var checkedOut = vault.ObjectOperations.IsCheckedOut(obj.ObjVer.ObjID); var objVersion = obj; if (!checkedOut) { objVersion = vault.ObjectOperations.CheckOut(obj.ObjVer.ObjID); } if (objVersion.SingleFile && objVersion.Files.Count > 0) { var oFileVer = new FileVer { ID = objVersion.Files[1].FileVer.ID, Version = -1 }; //先设置为多文档 vault.ObjectOperations.SetSingleFileObject(objVersion.ObjVer, false); //删除原文件 vault.ObjectFileOperations.RemoveFile(objVersion.ObjVer, oFileVer); //添加新文件 vault.ObjectFileOperations.AddFile(objVersion.ObjVer, title, extension, file0); for (var i = 1; i < filePath.Length; i++) { var title1 = Path.GetFileNameWithoutExtension(filePath[i]); var extension1 = Path.GetExtension(filePath[i]).TrimStart(new char[] { '.' }); vault.ObjectFileOperations.AddFile(objVersion.ObjVer, title1, extension1, filePath[i]); } //还原为单文档 if (filePath.Length == 1) { vault.ObjectOperations.SetSingleFileObject(objVersion.ObjVer, true); } } else { if (removeFiles) { foreach (ObjectFile file in objVersion.Files) { vault.ObjectFileOperations.RemoveFile(objVersion.ObjVer, file.FileVer); } } //添加新文件 vault.ObjectFileOperations.AddFile(objVersion.ObjVer, title, extension, file0); for (var i = 1; i < filePath.Length; i++) { var title1 = Path.GetFileNameWithoutExtension(filePath[i]); var extension1 = Path.GetExtension(filePath[i]).TrimStart(new char[] { '.' }); vault.ObjectFileOperations.AddFile(objVersion.ObjVer, title1, extension1, filePath[i]); } if (removeFiles && filePath.Length == 1) { var singleFilePv = new PropertyValue { PropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefSingleFileObject }; singleFilePv.Value.SetValue(MFDataType.MFDatatypeBoolean, true); if (pvs == null) { objVersion = vault.ObjectPropertyOperations.SetProperty(objVersion.ObjVer, singleFilePv).VersionData; } else { pvs.Add(-1, singleFilePv); } } if (pvs != null) { objVersion = vault.ObjectPropertyOperations.SetProperties(objVersion.ObjVer, pvs).VersionData; } } if (!checkedOut) { obj = vault.ObjectOperations.CheckIn(objVersion.ObjVer); } return(obj); }
/// <summary> /// Sets the value of the specified property. /// </summary> /// <param name="clientContext">Client context</param> /// <param name="props">Property Bag</param> /// <param name="matterName">Name of matter to which property is to be attached</param> /// <param name="propertyList">List of properties</param> public static void SetPropertBagValuesForList(ClientContext clientContext, PropertyValues props, string matterName, Dictionary<string, string> propertyList) { try { if (null != clientContext && !string.IsNullOrWhiteSpace(matterName) && null != props && null != propertyList) { List list = clientContext.Web.Lists.GetByTitle(matterName); foreach (var item in propertyList) { props[item.Key] = item.Value; list.Update(); } clientContext.ExecuteQuery(); } } catch (Exception ex) { throw; } }
public async Task <Note> AddEntityHistoryNoteAsync(PropertyValues oldValues, PropertyValues newValues) { List <HistoryJson> historyJsonList = new(); List <string> IgnoreFieldList = new() { "Created", "Updated" }; NoteType noteType = await _noteTypeService.GetAsync("History"); foreach (var property in newValues.Properties) { if (!IgnoreFieldList.Contains(property.Name)) { string oldPropValue; if (oldValues is not null) { oldPropValue = oldValues[property]?.ToString(); } else { oldPropValue = null; } string newPropValue = newValues[property]?.ToString(); //== null ? "" : newValues[property].ToString(); if (oldPropValue != newPropValue) { HistoryJson record = new(property.Name, oldPropValue, newPropValue); historyJsonList.Add(record); } } } Note note = new() { ChargeId = newValues.GetValue <int>("Id"), History = historyJsonList, NoteTypeId = noteType.Id, OwnerId = newValues.GetValue <string>("OwnerId"), Timestamp = DateTime.UtcNow }; if (historyJsonList.Count > 0) { note = await AddAsync(note); } return(note); } public async Task <Note> AddTagHistoryNoteAsync(int chargeId, Tag tag) { NoteType noteType = await _noteTypeService.GetAsync("Tag"); List <HistoryJson> historyJsonList = new(); HistoryJson record = new("Tag", null, tag.Name); historyJsonList.Add(record); Note note = new() { ChargeId = chargeId, History = historyJsonList, NoteTypeId = noteType.Id, OwnerId = tag.OwnerId, Timestamp = DateTime.UtcNow }; note = await AddAsync(note); return(note); } public async Task <Note> AddRelatedLinkHistoryNoteAsync(int chargeid, string desc, string linkType, string ownerId) { NoteType noteType = await _noteTypeService.GetAsync("Related"); List <HistoryJson> historyJsonList = new(); HistoryJson record = new(linkType, null, desc); historyJsonList.Add(record); Note note = new() { ChargeId = chargeid, History = historyJsonList, NoteTypeId = noteType.Id, OwnerId = ownerId, Timestamp = DateTime.UtcNow }; note = await AddAsync(note); return(note); } public async Task AddChildParentHistoryNoteAsync(Charge child, Charge parent) { // Add Child related link to Parent await AddRelatedLinkHistoryNoteAsync(parent.Id, $"{child.Id}: {child.Title}", "Child", child.OwnerId); // Add Parent related link to Child await AddRelatedLinkHistoryNoteAsync(child.Id, $"{parent.Id}: {parent.Title}", "Parent", child.OwnerId); }
//private int GetObjectTypeId(CsvModel csvModel, Vault vault) //{ // ObjTypes objectTypes = vault.ObjectTypeOperations.GetObjectTypes(); // int objectTypeId = -1; // foreach (ObjType objectType in objectTypes) // { // if (objectType.NameSingular == csvModel.ObjectType) // { // objectTypeId = objectType.ID; // break; // } // Debug.WriteLine(objectType.NameSingular); // } // return objectTypeId; //} //private int GetClassId(CsvModel csvModel, Vault vault) //{ // var allObjectClasses = vault.ClassOperations.GetAllObjectClasses(); // int classId = -1; // foreach (ObjectClass objectClass in allObjectClasses) // { // if (csvModel.Class == objectClass.Name) // { // classId = objectClass.ID; // break; // } // //Debug.WriteLine(string.Format("Id={0}, Name={1}", objectClass.ID, objectClass.Name)); // } // return classId; //} //private ObjectVersionAndProperties GetObjectVersionAndPropertiesAndCheckin(CsvModel csvModel, Vault vault, PropertyValues propertyValues, SourceObjectFiles sourceObjectFiles, int objectTypeId) //{ // if (objectTypeId == -1) // throw new ArgumentException(string.Format("could not find objectType with name '{0}'", csvModel.ObjectType)); // Debug.WriteLine("objectTypeId: " + objectTypeId); // return vault.ObjectOperations.CreateNewObjectEx(objectTypeId, propertyValues, SourceFiles, false, false) // return vault.ObjectOperations.CreateNewObject(objectTypeId, propertyValues, sourceObjectFiles); //} private ObjectVersionAndProperties GetObjectVersionAndProperties(CsvModel csvModel, Vault vault, PropertyValues propertyValues, SourceObjectFiles sourceObjectFiles, int objectTypeId) { if (objectTypeId == -1) throw new ArgumentException(string.Format("could not find objectType with name '{0}'", csvModel.ObjectType)); Debug.WriteLine("objectTypeId: " + objectTypeId); //return vault.ObjectOperations.CreateNewObjectEx(objectTypeId, propertyValues, sourceObjectFiles, false, false); return vault.ObjectOperations.CreateNewObject(objectTypeId, propertyValues, sourceObjectFiles); }
/// <summary> /// Sets the value of the specified property. /// </summary> /// <param name="clientContext">Client context</param> /// <param name="props">Property Bag</param> /// <param name="matterName">Name of matter to which property is to be attached</param> /// <param name="propertyList">List of properties</param> public void SetPropertBagValuesForList(ClientContext clientContext, PropertyValues props, string matterName, Dictionary<string, string> propertyList) { try { if (null != clientContext && !string.IsNullOrWhiteSpace(matterName) && null != props && null != propertyList) { List list = clientContext.Web.Lists.GetByTitle(matterName); foreach (var item in propertyList) { props[item.Key] = item.Value; list.Update(); } clientContext.ExecuteQuery(); } } catch (Exception ex) { customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable); throw; } }