public SearchForCustom(Dictionary<ObjectTypes, String> typeNames, ObjectTypes initialState) : base() { InitializeComponent(); this.typeNames = typeNames; InitializeList(initialState); }
public GravityObject (Vector2 position, Quaternion rotation, ObjectTypes type) : this() { Position = position; Rotation = rotation; Type = type; }
public static bool CheckSecurityForObject(ObjectTypes objectType, int ObjectId, int UserId) { bool isValid = false; if (objectType == ObjectTypes.Project) { Project.ProjectSecurity sec = Project.GetSecurity(ObjectId, UserId); isValid = sec.IsManager || sec.IsExecutiveManager || sec.IsTeamMember || sec.IsSponsor || sec.IsStakeHolder; } else if (objectType == ObjectTypes.Task) { Task.TaskSecurity sec = Task.GetSecurity(ObjectId, UserId); isValid = sec.IsManager || sec.IsRealTaskResource; } else if (objectType == ObjectTypes.ToDo) { ToDo.ToDoSecurity sec = ToDo.GetSecurity(ObjectId, UserId); isValid = sec.IsManager || sec.IsResource || sec.IsCreator; } else if (objectType == ObjectTypes.CalendarEntry) { CalendarEntry.EventSecurity sec = CalendarEntry.GetSecurity(ObjectId, UserId); isValid = sec.IsManager || sec.IsResource; } else if (objectType == ObjectTypes.Document) { Document.DocumentSecurity sec = Document.GetSecurity(ObjectId, UserId); isValid = sec.IsManager || sec.IsResource || sec.IsCreator; } return isValid; }
public static int GetSharingLevel(ObjectTypes ObjectType, int ObjectId) { int UserId = Security.CurrentUser.UserID; int RetVal = -1; switch(ObjectType) { case ObjectTypes.ToDo: RetVal = DBToDo.GetSharingLevel(UserId, ObjectId); break; case ObjectTypes.Task: RetVal = DBTask.GetSharingLevel(UserId, ObjectId); break; case ObjectTypes.CalendarEntry: RetVal = DBEvent.GetSharingLevel(UserId, ObjectId); break; case ObjectTypes.Issue: RetVal = DBIncident.GetSharingLevel(UserId, ObjectId); break; case ObjectTypes.Project: RetVal = DBProject.GetSharingLevel(UserId, ObjectId); break; case ObjectTypes.Document: RetVal = DBDocument.GetSharingLevel(UserId, ObjectId); break; default: RetVal = -1; break; } return RetVal; }
/// <summary> /// generates JSON dataset from sensor data /// </summary> /// <returns></returns> public String GenerateDataJSONOutput(ObjectTypes DataType, String ObjectTypeName, String ObjectName, DateTime StartDateTime, DateTime EndDateTime) { /* Example: * * { label: 'Europe (EU27)', * data: [[1999, 3.0], [2000, 3.9], [2001, 2.0], [2002, 1.2], [2003, 1.3], [2004, 2.5], [2005, 2.0], [2006, 3.1], [2007, 2.9], [2008, 0.9]] * } * * */ StringBuilder Output = new StringBuilder(); Output.Append("{ \"label\": \"" + ObjectName + "\", \"data\": ["); bool firstdataset = true; UInt64 SerializerCounter = 0; // TODO: there should be an appropriate caching algorithm in the sensor data... lock (sensor_data.InMemoryIndex) { foreach (OnDiscAdress ondisc in sensor_data.InMemoryIndex) { if (ondisc.CreationTime >= StartDateTime.Ticks) { if (ondisc.CreationTime <= EndDateTime.Ticks) { XS1_DataObject dataobject = ReadFromCache(ondisc); SerializerCounter++; if (dataobject.Type == DataType) { if (dataobject.TypeName == ObjectTypeName) { if (dataobject.Name == ObjectName) { if (!firstdataset) Output.Append(","); else firstdataset = false; Output.Append("["); Output.Append(dataobject.Timecode.JavaScriptTimestamp()); Output.Append(","); Output.Append(dataobject.Value.ToString().Replace(',', '.')); Output.Append("]"); } } } } } } } Output.Append("]}"); ConsoleOutputLogger_.WriteLineToScreenOnly("Generated JSON Dataset with "+SerializerCounter+" Elements"); return Output.ToString(); }
public XS1_DataObject(String _ServerName, String _Name, ObjectTypes _Type, String _TypeName, DateTime _Timecode, Int32 _XS1ObjectID, Double _Value) { ServerName = _ServerName; Name = _Name; Type = _Type; TypeName = _TypeName; Timecode = _Timecode; XS1ObjectID = _XS1ObjectID; Value = _Value; }
/// <summary> /// WoWObject constructor /// </summary> /// <param name="valuesCount">Number of fields</param> /// <param name="typeId">Object typeid</param> public WoWObject(uint valuesCount, ObjectTypes typeId) { if (m_valuesCount != 0) m_valuesCount = valuesCount; else m_valuesCount = GetValuesCountByObjectType(typeId); m_uint32Values = new uint[m_valuesCount]; m_typeId = typeId; }
public XS1_DataObject(String _ServerName, String _Name, ObjectTypes _Type, String _TypeName, DateTime _Timecode, Int32 _XS1ObjectID, Double _Value, Boolean _IgnoreForAlarming = false) { ServerName = _ServerName; Name = _Name; Type = _Type; TypeName = _TypeName; Timecode = _Timecode; XS1ObjectID = _XS1ObjectID; Value = _Value; IgnoreForAlarming = _IgnoreForAlarming; }
public XS1_DataObject(String _ServerName, String _Name, ObjectTypes _Type, String _TypeName, DateTime _Timecode, Int32 _XS1ObjectID, Double _Value,String OriginalStatement) { ServerName = _ServerName; Name = _Name; Type = _Type; TypeName = _TypeName; Timecode = _Timecode; XS1ObjectID = _XS1ObjectID; Value = _Value; OriginalXS1Statement = OriginalStatement; }
public UserObjectRightCreateViewModel(Model.UserObjectRight userObjectRight, ObjectTypes objectType, SelectList entityList) : base(userObjectRight) { if (userObjectRight.User == null) throw new ArgumentException("User in UserObjectRight cannot be null"); this.ObjectType = objectType; this.Email = userObjectRight.User.Email; this.EntityList = entityList; this.RightName = userObjectRight.Right.DisplayName; }
public static byte[] Render(bool vastScale, DateTime curDate, DateTime startDate, int[] users, ObjectTypes[] objectTypes, List<KeyValuePair<int, int>> highlightedItems, bool generateDataXml, string styleFilePath, int portionX, int portionY, int itemsPerPage, int pageNumber) { startDate = startDate.AddDays((vastScale ? 7 : 21) * portionX); DateTime finishDate = startDate.AddDays(vastScale ? 7 : 21); portionX = 0; GanttView gantt = CreateGanttView(startDate, vastScale, ConvertDayOfWeek(PortalConfig.PortalFirstDayOfWeek), HeaderItemHeight, ItemHeight); if (portionY >= 0) { #region Add data foreach (int userId in users) { Element spanElement = gantt.CreateSpanElement(null, null, null); DataTable table = Calendar.GetResourceUtilization(userId, curDate, startDate, finishDate, new ArrayList(objectTypes), highlightedItems, true, true, true, false); table.AcceptChanges(); for (int i = 0; i < table.Rows.Count; i++) { DataRow row = table.Rows[i]; if (row.RowState != DataRowState.Deleted) { DateTime intervalStart = (DateTime)row["Start"]; DateTime intervalFinish = ((DateTime)row["Finish"]); Calendar.TimeType timeType = (Calendar.TimeType)row["Type"]; bool highlight = (bool)row["Highlight"]; gantt.CreateIntervalElement(spanElement, intervalStart, intervalFinish, null, timeType.ToString(), null); if (highlight) gantt.CreateIntervalElement(spanElement, intervalStart, intervalFinish, null, "Highlight", null); } } } #endregion } return GanttManager.Render(gantt, generateDataXml, styleFilePath, portionX, portionY, PortionWidth, users.Length * ItemHeight, itemsPerPage, pageNumber); }
public XS1_DataObject(String _ServerName, String _Name, ObjectTypes _Type, String _TypeName, DateTime _Timecode, Int32 _XS1ObjectID, Double _Value,String OriginalStatement, Boolean _IgnoreForAlarming = false) { ServerName = _ServerName; Name = _Name; Type = _Type; TypeName = _TypeName; Timecode = _Timecode; XS1ObjectID = _XS1ObjectID; Value = _Value; OriginalXS1Statement = OriginalStatement; Creation = DateTime.Now; IgnoreForAlarming = _IgnoreForAlarming; }
public static void CreateAccountRightsFor(RemoteWebDriver browser, string userEmail, ObjectTypes objectType, string objectName) { browser.FindElementByCssSelector("a[href='/Account']").Click(); var vendorUserRow = browser.FindElementByLinkText(userEmail).FindElement(By.XPath("./ancestor::tr")); vendorUserRow.FindElement(By.CssSelector("a[href^='/Account/Edit']")).Click(); browser.FindElementByCssSelector("a[href^='/AccountRights/Create'][href$='" + Enum.GetName(typeof(ObjectTypes), objectType) + "']").Click(); SiteUtil.SetValueForChosenJQueryControl(browser, "#ObjectId_chzn", objectName); browser.FindElementByCssSelector("form[action^='/AccountRights/Create'] input[type='submit']").Click(); browser.FindElementByCssSelector(".success"); }
/// <summary> /// Makes the auth session. /// </summary> /// <param name="forceCleanup">if set to <c>true</c> [force cleanup].</param> /// <param name="elStorageType">Type of the el storage.</param> /// <param name="objectId">The object id.</param> /// <returns></returns> public static Guid MakeAuthSession(bool forceCleanup, ObjectTypes elStorageType, int objectId) { Guid retVal = Guid.Empty; //Cleanup expiated sessions if (forceCleanup) { CleanupAuthSession(elStorageType); } UserLight currentUser = Security.CurrentUser; if (currentUser == null) throw new Exception("CurrentUser"); return DBCommon.AddGate((int)elStorageType, objectId, currentUser.UserID); }
public ObjectBase AddObject(ObjectTypes Type, string Key, string ContentKey) { if (objectTable.ContainsKey(Key) == false) { switch (Type) { case ObjectTypes.Player: objectTable.Add(Key, new ObjectPlayer(Key, Type, ContentKey, Content)); break; case ObjectTypes.Enemy: objectTable.Add(Key, new ObjectEnemy(Key, Type, ContentKey, Content)); break; case ObjectTypes.Cursor: objectTable.Add(Key, new ObjectCursor(Key, Type, ContentKey, Content)); break; case ObjectTypes.Button: objectTable.Add(Key, new ObjectButton(Key, Type, ContentKey, Content)); break; case ObjectTypes.Weapon: objectTable.Add(Key, new ObjectWeapon(Key, Type, ContentKey, Content)); break; case ObjectTypes.Bullet: objectTable.Add(Key, new ObjectBullet(Key, Type, ContentKey, Content)); break; case ObjectTypes.DebugPoint: objectTable.Add(Key, new ObjectDebugPoint(Key, Type, ContentKey, Content)); break; case ObjectTypes.AchivementShelf: objectTable.Add(Key, new ObjectAchivementShelf(Key, Type, ContentKey, Content)); break; case ObjectTypes.Ground: objectTable.Add(Key, new ObjectGround(Key, Type, ContentKey, Content)); break; case ObjectTypes.EnemySpawner: objectTable.Add(Key, new ObjectEnemySpawner(Key, Type, ContentKey, Content)); break; default: break; } return (ObjectBase)objectTable[Key]; } else { return null; } }
private void InitializeList(ObjectTypes initialState) { AddItemToSearchFor(ObjectTypes.Pool, initialState); AddItemToSearchFor(ObjectTypes.Server, initialState); AddItemToSearchFor(ObjectTypes.DisconnectedServer, initialState); AddItemToSearchFor(ObjectTypes.VM, initialState); AddItemToSearchFor(ObjectTypes.UserTemplate, initialState); AddItemToSearchFor(ObjectTypes.DefaultTemplate, initialState); AddItemToSearchFor(ObjectTypes.Snapshot, initialState); AddItemToSearchFor(ObjectTypes.RemoteSR, initialState); AddItemToSearchFor(ObjectTypes.LocalSR, initialState); AddItemToSearchFor(ObjectTypes.VDI, initialState); AddItemToSearchFor(ObjectTypes.Network, initialState); AddItemToSearchFor(ObjectTypes.Folder, initialState); //AddItemToSearchFor(ObjectTypes.DockerContainer, initialState); // The item check change event only fires before the check state changes // so to reuse the logic we have to pretend that something has changed as the enablement code expects to deal with a new value from the args checkedListBox_ItemCheck(null, new ItemCheckEventArgs(0, checkedListBox.GetItemCheckState(0), checkedListBox.GetItemCheckState(0))); }
/// <summary> /// 下载附件 /// </summary> /// <param name="objectName">附件类型</param> /// <param name="id">附件编号</param> /// <returns>附件信息</returns> public ActionResult DownloadUploadFile(string objectName, int id) { if (CheckSession(false) == false) { return(Json(ResultModelBase.CreateTimeoutModel(), JsonRequestBehavior.AllowGet)); } if (CheckSessionID() == false) { return(Json(ResultModelBase.CreateLogoutModel(), JsonRequestBehavior.AllowGet)); } try { if (id < 0) { UploadFileInfo file = GetUploadFileInSession(id); string fileName = new FileInfo(file.FileName).Name; byte[] fileContent = Convert.FromBase64String(file.FileContent); return(File(fileContent, System.Web.MimeMapping.GetMimeMapping(fileName), fileName)); } else { string filePath = null; UploadFileInfo file = this.fileDao.GetFileByID(objectName, id); filePath = Path.Combine(ObjectTypes.GetFileFolder(objectName), file.GetFileName()); Response.AddHeader("Set-Cookie", "fileDownload=true; path=/"); file.FileName = this.fileManager.GetDownloadFileName(file); return(File(filePath, System.Web.MimeMapping.GetMimeMapping(file.FileName), file.FileName)); } } catch (Exception ex) { NLog.LogManager.GetCurrentClassLogger().Error(ex, ex.Message); } return(null); }
private static void MediaService_Trashed(IMediaService sender, MoveEventArgs <IMedia> e) { var relationService = Current.Services.RelationService; var entityService = Current.Services.EntityService; var textService = Current.Services.TextService; const string relationTypeAlias = Constants.Conventions.RelationTypes.RelateParentMediaFolderOnDeleteAlias; var relationType = relationService.GetRelationTypeByAlias(relationTypeAlias); // check that the relation-type exists, if not, then recreate it if (relationType == null) { var documentObjectType = Constants.ObjectTypes.Document; const string relationTypeName = Constants.Conventions.RelationTypes.RelateParentMediaFolderOnDeleteName; relationType = new RelationType(documentObjectType, documentObjectType, relationTypeAlias, relationTypeName); relationService.Save(relationType); } foreach (var item in e.MoveInfoCollection) { var originalPath = item.OriginalPath.ToDelimitedList(); var originalParentId = originalPath.Count > 2 ? int.Parse(originalPath[originalPath.Count - 2]) : Constants.System.Root; //before we can create this relation, we need to ensure that the original parent still exists which //may not be the case if the encompassing transaction also deleted it when this item was moved to the bin if (entityService.Exists(originalParentId)) { // Add a relation for the item being deleted, so that we can know the original parent for if we need to restore later var relation = new Relation(originalParentId, item.Entity.Id, relationType); relationService.Save(relation); Current.Services.AuditService.Add(AuditType.Delete, item.Entity.CreatorId, item.Entity.Id, ObjectTypes.GetName(UmbracoObjectTypes.Media), string.Format(textService.Localize( "recycleBin/mediaTrashed"), item.Entity.Id, originalParentId)); } } }
/// <summary>Computes equilibrium concentrations for a set of chemical species.</summary> public ErrorCodeType MSXchem_equil(ObjectTypes zone, double[] c) { ErrorCodeType errcode = 0; if (zone == ObjectTypes.LINK) { if (numPipeEquilSpecies > 0) { errcode = EvalPipeEquil(c); } EvalPipeFormulas(c); } if (zone == ObjectTypes.NODE) { if (numTankEquilSpecies > 0) { errcode = EvalTankEquil(c); } EvalTankFormulas(c); } return(errcode); }
/// <summary> /// Sets the current object. /// </summary> /// <param name="objectType">The object type.</param> /// <param name="dataObject">The data object.</param> /// <param name="keepGridData">True if not clearing data when querying partial results</param> /// <param name="retrieveObjectSelection">if set to <c>true</c> the retrieve object selection setting is selected.</param> /// <param name="errorHandler">The error handler.</param> public void SetCurrentObject(string objectType, object dataObject, bool keepGridData, bool retrieveObjectSelection, Action <WitsmlException> errorHandler) { if (!ObjectTypes.IsGrowingDataObject(objectType) || retrieveObjectSelection) { ClearDataTable(); return; } var log131 = dataObject as Witsml131.Log; if (log131 != null) { SetLogData(log131, keepGridData, errorHandler); } var log141 = dataObject as Witsml141.Log; if (log141 != null) { SetLogData(log141, keepGridData, errorHandler); } }
/// <summary> /// Retrieves relationship of the resource /// </summary> private void RetrieveRelations() { if (levelOfStripping <= 0) { return; } List <Relationship> containedResources; using (ZentityContext context = CoreHelper.CreateZentityContext()) { Resource resource = context.Resources .Where(res => res.Id == ResourceUri) .FirstOrDefault(); if (resource == null || !resource.Authorize("Read", context, CoreHelper.GetAuthenticationToken())) { return; } resource.RelationshipsAsSubject.Load(); containedResources = resource.RelationshipsAsSubject.ToList(); foreach (Relationship rel in containedResources) { rel.ObjectReference.Load(); ObjectResourceIds.Add(rel.Object.Id); Type objectType = rel.Object.GetType(); ObjectTypes.Add(objectType); rel.PredicateReference.Load(); RelationUris.Add(rel.Predicate.Name); } } }
private void QueryAndAssertByBopManufacturer(string[] manufacturerNumbers, int expectedRigCount) { var query = manufacturerNumbers .Select(manufacturerNumber => new Rig { Bop = new Bop { Manufacturer = $"{_manufacturerPrefix}-{manufacturerNumber}" } }) .ToList(); // Expected results: expectedRigCount rigs var results = DevKit.Query <RigList, Rig>(query, ObjectTypes.GetObjectType <RigList>(), null, OptionsIn.ReturnElements.All); Assert.AreEqual(expectedRigCount, results.Count); // Since we are filtering on BOP Manufacturer the BOP should contain all of the NameTags and BopComponents results.ForEach(r => { Assert.AreEqual(6, r.Bop.BopComponent.Count); Assert.AreEqual(6, r.Bop.NameTag.Count); }); }
/// <summary> /// Handles the special case. /// </summary> /// <param name="propertyInfo">The property information.</param> /// <param name="elementList">The element list.</param> /// <param name="parentPath">The parent path.</param> /// <param name="elementName">Name of the element.</param> /// <returns>true if the special case was handled, false otherwise</returns> protected override bool HandleSpecialCase(PropertyInfo propertyInfo, List <XElement> elementList, string parentPath, string elementName) { if (HasXmlAnyElement(propertyInfo.PropertyType)) { var propertyValue = Context.PropertyValues.Last(); UpdateXmlAnyElements(elementList, propertyInfo, propertyValue, parentPath); return(true); } if (!IsSpecialCase(propertyInfo)) { return(base.HandleSpecialCase(propertyInfo, elementList, parentPath, elementName)); } var items = Context.PropertyValues.Last() as IEnumerable; var propertyPath = GetPropertyPath(parentPath, propertyInfo.Name); var propertyType = propertyInfo.PropertyType; var args = propertyType.GetGenericArguments(); var childType = args.FirstOrDefault() ?? propertyType.GetElementType(); if (childType != null && childType != typeof(string)) { try { var version = ObjectTypes.GetVersion(childType); var family = ObjectTypes.GetVersion(childType); var validator = Container.Resolve <IRecurringElementValidator>(new ObjectName(childType.Name, family, version)); validator?.Validate(Context.Function, childType, items, elementList); } catch (ContainerException) { Logger.DebugFormat("{0} not configured for type: {1}", typeof(IRecurringElementValidator).Name, childType); } } UpdateArrayElementsWithoutUid(elementList, propertyInfo, items, childType, propertyPath); return(true); }
/// <summary> /// The method called to render the contents of the tree structure /// </summary> /// <param name="id"></param> /// <param name="queryStrings"> /// All of the query string parameters passed from jsTree /// </param> /// <remarks> /// We are allowing an arbitrary number of query strings to be pased in so that developers are able to persist custom data from the front-end /// to the back end to be used in the query for model data. /// </remarks> protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings) { var nodes = new TreeNodeCollection(); var found = id == Constants.System.RootString ? Services.FileService.GetTemplates(-1) : Services.FileService.GetTemplates(int.Parse(id)); nodes.AddRange(found.Select(template => CreateTreeNode( template.Id.ToString(CultureInfo.InvariantCulture), // TODO: Fix parent ID stuff for templates "-1", queryStrings, template.Name, template.IsMasterTemplate ? "icon-newspaper" : "icon-newspaper-alt", template.IsMasterTemplate, null, Udi.Create(ObjectTypes.GetUdiType(Constants.ObjectTypes.TemplateType), template.Key) ))); return(nodes); }
/// <summary> /// Creates the specified object id. /// </summary> /// <param name="ObjectId">The object id.</param> /// <param name="ObjectTypeId">The object type id.</param> /// <param name="Date">The date.</param> /// <param name="RowId">The row id.</param> /// <param name="Value">The value.</param> /// <param name="Comment">The comment.</param> /// <param name="BlockId">The TimeTrackingBlock id.</param> /// <returns></returns> public static int Create(int ObjectId, ObjectTypes ObjectType, DateTime Date, string RowId, double Value, string Comment, int BlockId, double TotalApproved, int OwnerId) { ActualFinancesRow newRow = new ActualFinancesRow(); newRow.CreatorId = Security.CurrentUser.UserID; newRow.ObjectId = ObjectId; newRow.ObjectTypeId = (int)ObjectType; newRow.Date = Date; newRow.RowId = RowId; newRow.Value = Value; newRow.Comment = Comment; newRow.BlockId = BlockId; newRow.TotalApproved = TotalApproved; newRow.OwnerId = OwnerId; newRow.Update(); return(newRow.PrimaryKeyId); }
uint GetValuesCountByObjectType(ObjectTypes typeId) { switch (typeId) { case ObjectTypes.TYPEID_ITEM: return UpdateFieldsLoader.ITEM_END; case ObjectTypes.TYPEID_CONTAINER: return UpdateFieldsLoader.CONTAINER_END; case ObjectTypes.TYPEID_UNIT: return UpdateFieldsLoader.UNIT_END; case ObjectTypes.TYPEID_PLAYER: return UpdateFieldsLoader.PLAYER_END; case ObjectTypes.TYPEID_GAMEOBJECT: return UpdateFieldsLoader.GO_END; case ObjectTypes.TYPEID_DYNAMICOBJECT: return UpdateFieldsLoader.DO_END; case ObjectTypes.TYPEID_CORPSE: return UpdateFieldsLoader.CORPSE_END; default: return 0; } }
public ObjectTypes Parse(string json) { JToken token = JToken.Parse(json); var objectsToken = token.First.First.First.FirstOrDefault(); if (objectsToken is JArray) { /* * Special case - json with an empty array: * { * ""data"": { * ""objects"": [] * } * } */ return(new ObjectTypes()); } // json containing a dictionary: ObjectTypes data = JsonConvert.DeserializeObject <ObjectTypes>(json); return(data); }
public void Witsml131Provider_TypeList() { Witsml131Provider_Witsml131Provider(); { var adapters = GetDataAdapters <IWellboreObject>(_actual.Providers).ToList(); foreach (var x in adapters) { System.Type t = x.DataObjectType; string t_name = ObjectTypes.GetObjectType(t); Debug.WriteLine($"{t.Name} -> {t_name}"); IWellboreObject instance = (IWellboreObject)Activator.CreateInstance(t); Assert.AreEqual(t.Name, instance.GetType().Name); } /* * BhaRun -> bhaRun * CementJob -> cementJob * ConvCore -> convCore * FluidsReport -> fluidsReport * FormationMarker -> formationMarker * Log -> log * Message -> message * MudLog -> mudLog * OpsReport -> opsReport * Rig -> rig * Risk -> risk * SidewallCore -> sidewallCore * SurveyProgram -> surveyProgram * Target -> target * Trajectory -> trajectory * Tubular -> tubular * StandAloneWellboreGeometry -> wbGeometry * WellLog -> wellLog */ } }
private XDocument CreateTemplate(Type type) { var xmlRoot = XmlAttributeCache <XmlRootAttribute> .GetCustomAttribute(type); var xmlType = XmlAttributeCache <XmlTypeAttribute> .GetCustomAttribute(type); var objectType = ObjectTypes.GetObjectType(type); var version = ObjectTypes.GetVersion(type); var attribute = "version"; if (OptionsIn.DataVersion.Version200.Equals(version)) { objectType = objectType.ToPascalCase(); attribute = "schemaVersion"; } else if (typeof(IEnergisticsCollection).IsAssignableFrom(type)) { objectType = ObjectTypes.SingleToPlural(objectType); } XNamespace ns = xmlType?.Namespace ?? xmlRoot.Namespace; var element = new XElement(ns + objectType); element.SetAttributeValue("xmlns", ns); var document = new XDocument(element); CreateTemplate(type, ns, document.Root); // Set version attribute for top level data objects if (document.Root != null && document.Root.Attributes(attribute).Any()) { document.Root.SetAttributeValue(attribute, version); } return(document); }
// Umbraco.Code.MapAll -Alias private static void Map(IEntitySlim source, EntityBasic target, MapperContext context) { target.Icon = MapContentTypeIcon(source); target.Id = source.Id; target.Key = source.Key; target.Name = MapName(source, context); target.ParentId = source.ParentId; target.Path = source.Path; target.Trashed = source.Trashed; target.Udi = Udi.Create(ObjectTypes.GetUdiType(source.NodeObjectType), source.Key); if (source is IContentEntitySlim contentSlim) { source.AdditionalData["ContentTypeAlias"] = contentSlim.ContentTypeAlias; } if (source is IDocumentEntitySlim documentSlim) { source.AdditionalData["IsPublished"] = documentSlim.Published; } if (source is IMediaEntitySlim mediaSlim) { //pass UpdateDate for MediaPicker ListView ordering source.AdditionalData["UpdateDate"] = mediaSlim.UpdateDate; source.AdditionalData["MediaPath"] = mediaSlim.MediaPath; } // NOTE: we're mapping the objects in AdditionalData by object reference here. // it works fine for now, but it's something to keep in mind in the future foreach (var kvp in source.AdditionalData) { target.AdditionalData[kvp.Key] = kvp.Value; } target.AdditionalData.Add("IsContainer", source.IsContainer); }
/// <summary> /// Returns the response for deleting one WITSML data-object to the server. /// </summary> /// <param name="request">he request object encapsulating the method input parameters.</param> /// <returns>A positive value indicates a success; a negative value indicates an error.</returns> public WMLS_DeleteFromStoreResponse WMLS_DeleteFromStore(WMLS_DeleteFromStoreRequest request) { var context = WitsmlOperationContext.Current.Request = request.ToContext(); var version = string.Empty; try { _log.Debug(WebOperationContext.Current.ToLogMessage()); _log.Debug(context); UserAuthorizationProvider.CheckSoapAccess(); WitsmlValidator.ValidateRequest(CapServerProviders); version = WitsmlOperationContext.Current.DataSchemaVersion; var family = ObjectTypes.GetFamily(WitsmlOperationContext.Current.Document.Root); var dataWriter = Container.Resolve <IWitsmlDataProvider>(new ObjectName(context.ObjectType, family, version)); var result = dataWriter.DeleteFromStore(context); var response = new WMLS_DeleteFromStoreResponse((short)result.Code, result.Message); _log.Debug(response.ToLogMessage()); return(response); } catch (ContainerException) { var response = new WMLS_DeleteFromStoreResponse((short)ErrorCodes.DataObjectNotSupported, "WITSML object type not supported: " + context.ObjectType + "; Version: " + version); _log.Error(response.ToLogMessage(_log.IsWarnEnabled)); return(response); } catch (WitsmlException ex) { var response = new WMLS_DeleteFromStoreResponse((short)ex.ErrorCode, ex.Message); _log.Error(response.ToLogMessage(_log.IsWarnEnabled)); return(response); } }
/// <summary> /// Deletes all child objects related to the specified URI. /// </summary> /// <param name="uri">The URI.</param> protected virtual void DeleteAll(EtpUri uri) { var adapters = new List <IWitsmlDataAdapter>(); if (uri.IsRelatedTo(EtpUris.Witsml200) || uri.IsRelatedTo(EtpUris.Eml210)) { // Cascade delete not defined for WITSML 2.0 / ETP return; } if (ObjectTypes.Well.EqualsIgnoreCase(uri.ObjectType)) { adapters.Add(Container.Resolve <IWitsmlDataAdapter>(new ObjectName(ObjectTypes.Wellbore, uri.Version))); } else if (ObjectTypes.Wellbore.EqualsIgnoreCase(uri.ObjectType)) { var exclude = new[] { ObjectTypes.Well, ObjectTypes.Wellbore, ObjectTypes.ChangeLog }; var type = OptionsIn.DataVersion.Version141.Equals(uri.Version) ? typeof(IWitsml141Configuration) : typeof(IWitsml131Configuration); Container .ResolveAll(type) .Cast <IWitsmlDataAdapter>() .Where(x => !exclude.ContainsIgnoreCase(ObjectTypes.GetObjectType(x.DataObjectType))) .ForEach(adapters.Add); } foreach (var adapter in adapters) { var dataObjects = adapter.GetAll(uri); foreach (var dataObject in dataObjects) { adapter.Delete(adapter.GetUri(dataObject)); } } }
private void QueryAndAssertOneBopComponentOneNameTagMultiElements(int expectedRigCount, string bopCompNumber, string nameNumber) { var query = new Rig { Bop = new Bop { BopComponent = new List <BopComponent> { new BopComponent { Uid = $"{_bopPrefix}-{bopCompNumber}", DescComp = $"{_bopPrefix}-{bopCompNumber}" } }, NameTag = new List <NameTag> { new NameTag { Name = $"{_namePrefix}-{nameNumber}", Comment = $"{_namePrefix}-{nameNumber}" } } } }; // Expected Result: expectedRigCount Rigs var results = DevKit.Query <RigList, Rig>(query, ObjectTypes.GetObjectType <RigList>(), null, OptionsIn.ReturnElements.All); Assert.AreEqual(expectedRigCount, results.Count); // Each rig that is returned should have 1 name and 1 BopComponents results.ForEach(r => { Assert.AreEqual(1, r.Bop.NameTag.Count); Assert.AreEqual(1, r.Bop.BopComponent.Count); }); }
public void Initialized(Type t) { if (t.IsPrimitive) { if (t == typeof(int) || t == typeof(uint) || t == typeof(short) || t == typeof(ushort) || t == typeof(byte) || t == typeof(sbyte) || t == typeof(char) || t == typeof(bool)) { ObjectType = ObjectTypes.Integer; Value = 0; ValueLow = 0; } else if (t == typeof(long) || t == typeof(ulong)) { ObjectType = ObjectTypes.Long; Value = 0; ValueLow = 0; } else if (t == typeof(float)) { ObjectType = ObjectTypes.Float; Value = 0; ValueLow = 0; } else if (t == typeof(double)) { ObjectType = ObjectTypes.Double; Value = 0; ValueLow = 0; } else { throw new NotImplementedException(); } } else { this = Null; } }
public static int GetSharingLevel(ObjectTypes ObjectType, int ObjectId) { int UserId = Security.CurrentUser.UserID; int RetVal = -1; switch (ObjectType) { case ObjectTypes.ToDo: RetVal = DBToDo.GetSharingLevel(UserId, ObjectId); break; case ObjectTypes.Task: RetVal = DBTask.GetSharingLevel(UserId, ObjectId); break; case ObjectTypes.CalendarEntry: RetVal = DBEvent.GetSharingLevel(UserId, ObjectId); break; case ObjectTypes.Issue: RetVal = DBIncident.GetSharingLevel(UserId, ObjectId); break; case ObjectTypes.Project: RetVal = DBProject.GetSharingLevel(UserId, ObjectId); break; case ObjectTypes.Document: RetVal = DBDocument.GetSharingLevel(UserId, ObjectId); break; default: RetVal = -1; break; } return(RetVal); }
/// <summary> /// Handles the PutObject message of the Store protocol. /// </summary> /// <param name="header">The message header.</param> /// <param name="putObject">The put object message.</param> protected override void HandlePutObject(MessageHeader header, PutObject putObject) { base.HandlePutObject(header, putObject); var uri = this.CreateAndValidateUri(putObject.DataObject.Resource.Uri, header.MessageId); if (!uri.IsValid) return; if (!this.ValidateUriObjectType(uri, header.MessageId)) return; try { var data = putObject.DataObject.GetString(); if (EtpContentType.Json.EqualsIgnoreCase(uri.ContentType.Format)) { var objectType = uri.IsRelatedTo(EtpUris.Witsml200) || uri.IsRelatedTo(EtpUris.Eml210) ? ObjectTypes.GetObjectType(uri.ObjectType, OptionsIn.DataVersion.Version200.Value) : ObjectTypes.GetObjectGroupType(uri.ObjectType, uri.Version); var instance = Energistics.Common.EtpExtensions.Deserialize(objectType, data); data = WitsmlParser.ToXml(instance); } WitsmlOperationContext.Current.Request = new RequestContext(Functions.PutObject, uri.ObjectType, data, null, null); var dataAdapter = Container.Resolve<IEtpDataProvider>(new ObjectName(uri.ObjectType, uri.GetDataSchemaVersion())); dataAdapter.Put(putObject.DataObject); Acknowledge(header.MessageId); } catch (ContainerException ex) { this.UnsupportedObject(ex, putObject.DataObject.Resource.Uri, header.MessageId); } catch (WitsmlException ex) { ProtocolException((int)EtpErrorCodes.InvalidObject, $"Invalid object: {ex.Message}; Error code: {(int)ex.ErrorCode}", header.MessageId); } }
/// <summary> /// Saves a collection of <see cref="Template"/> objects /// </summary> /// <param name="templates">List of <see cref="Template"/> to save</param> /// <param name="userId">Optional id of the user</param> public void SaveTemplate(IEnumerable <ITemplate> templates, int userId = 0) { var templatesA = templates.ToArray(); using (var scope = ScopeProvider.CreateScope()) { if (scope.Events.DispatchCancelable(SavingTemplate, this, new SaveEventArgs <ITemplate>(templatesA))) { scope.Complete(); return; } foreach (var template in templatesA) { _templateRepository.Save(template); } scope.Events.Dispatch(SavedTemplate, this, new SaveEventArgs <ITemplate>(templatesA, false)); Audit(AuditType.Save, userId, -1, ObjectTypes.GetName(UmbracoObjectTypes.Template)); scope.Complete(); } }
private static QueryScope GetTreeSearchScope() { ObjectTypes types = Search.DefaultObjectTypes(); types |= ObjectTypes.Pool; // They appear as groups anyway without this: but needed because of CA-28021 if (Properties.Settings.Default.DefaultTemplatesVisible) { types |= ObjectTypes.DefaultTemplate; } if (Properties.Settings.Default.UserTemplatesVisible) { types |= ObjectTypes.UserTemplate; } if (Properties.Settings.Default.LocalSRsVisible) { types |= ObjectTypes.LocalSR; } return(new QueryScope(types)); }
/// <summary> /// Parses the specified byte arr. /// </summary> /// <param name="byteArr">The byte arr.</param> /// <returns></returns> public static WebDavAbsolutePath Parse(byte[] byteArr) { WebDavAbsolutePath retVal = null; try { ObjectTypes storageType = ObjectTypes.UNDEFINED; storageType = (ObjectTypes)byteArr[0]; //remove self info byte[] arr = new byte[byteArr.Length - 1]; if (arr.Length > 1) { Array.Copy(byteArr, 1, arr, 0, arr.Length); retVal = CreateInstance(storageType, arr); } } catch (System.Exception) { } return(retVal); }
public static Geometry GetGeometryFromObjectType(ObjectTypes objectType, double a) { switch (objectType) { case ObjectTypes.Dreieck: return(Geometries.GetTriangleGeometry(a)); case ObjectTypes.Kreis: return(new EllipseGeometry(new Rect() { Width = a, Height = a })); case ObjectTypes.Rechteck: return(new RectangleGeometry(new Rect() { Width = a, Height = a })); default: return(null); } }
public void CapServer141Provider_ToXml_Can_Get_Server_Capabilities_For_DeleteFromStore_With_Object_Contraints_For_GrowingObjects() { var capServerObject = GetCapServerObject(); var deleteFromStore = capServerObject.Function.Where(n => n.Name.EndsWith(Functions.DeleteFromStore.ToString())).ToArray(); Assert.IsNotNull(deleteFromStore); deleteFromStore.FirstOrDefault()?.DataObject.ForEach( dataObject => { if (ObjectTypes.IsGrowingDataObject(dataObject.Value)) { if (dataObject.Value == ObjectTypes.Log) { Assert.AreEqual(Properties.Settings.Default.LogMaxDataPointsDelete, dataObject.MaxDataPoints, "MaxDataPoints"); } var propertyNameMaxDataNodeDelete = dataObject.Value.ToPascalCase() + "MaxDataNodesDelete"; Assert.AreEqual(Properties.Settings.Default[propertyNameMaxDataNodeDelete], dataObject.MaxDataNodes, propertyNameMaxDataNodeDelete); } }); }
/// <summary> /// Puts the growing part for a growing object. /// </summary> /// <param name="etpAdapter">The ETP adapter.</param> /// <param name="uri">The growing obejct's URI.</param> /// <param name="contentType">Type of the content.</param> /// <param name="data">The data.</param> public override void PutGrowingPart(IEtpAdapter etpAdapter, EtpUri uri, string contentType, byte[] data) { var dataObject = etpAdapter.CreateDataObject(); dataObject.Data = data; // Convert byte array to TrajectoryStation var trajectoryStationXml = dataObject.GetString(); var tsDocument = WitsmlParser.Parse(trajectoryStationXml); var trajectoryStation = WitsmlParser.Parse <TrajectoryStation>(tsDocument.Root); // Merge TrajectoryStation into the Trajectory if it is not null if (trajectoryStation != null) { // Get the Trajectory for the uri var entity = GetEntity(uri); entity.TrajectoryStation = trajectoryStation.AsList(); var document = WitsmlParser.Parse(WitsmlParser.ToXml(entity)); var parser = new WitsmlQueryParser(document.Root, ObjectTypes.GetObjectType <Trajectory>(), null); UpdateTrajectoryWithStations(parser, entity, uri, true); } }
public IReadOnlyDictionary <Udi, IEnumerable <string> > FindUsages(int id) { if (id == default) { return(new Dictionary <Udi, IEnumerable <string> >()); } var sql = Sql() .Select <ContentTypeDto>(ct => ct.Select(node => node.NodeDto)) .AndSelect <PropertyTypeDto>(pt => Alias(pt.Alias, "ptAlias"), pt => Alias(pt.Name, "ptName")) .From <PropertyTypeDto>() .InnerJoin <ContentTypeDto>().On <ContentTypeDto, PropertyTypeDto>(ct => ct.NodeId, pt => pt.ContentTypeId) .InnerJoin <NodeDto>().On <NodeDto, ContentTypeDto>(n => n.NodeId, ct => ct.NodeId) .Where <PropertyTypeDto>(pt => pt.DataTypeId == id) .OrderBy <NodeDto>(node => node.NodeId) .AndBy <PropertyTypeDto>(pt => pt.Alias); var dtos = Database.FetchOneToMany <ContentTypeReferenceDto>(ct => ct.PropertyTypes, sql); return(dtos.ToDictionary( x => (Udi) new GuidUdi(ObjectTypes.GetUdiType(x.NodeDto.NodeObjectType.Value), x.NodeDto.UniqueId).EnsureClosed(), x => (IEnumerable <string>)x.PropertyTypes.Select(p => p.Alias).ToList())); }
private IEnergisticsCollection GetList(IDataObject entity, EtpUri uri) { if (entity == null) { return(null); } var groupType = ObjectTypes.GetObjectGroupType(uri.ObjectType, WMLSVersion.WITSML131); var property = ObjectTypes.GetObjectTypeListPropertyInfo(uri.ObjectType, uri.Version); var group = Activator.CreateInstance(groupType) as IEnergisticsCollection; var list = Activator.CreateInstance(property.PropertyType) as IList; if (list == null) { return(group); } list.Add(entity); property.SetValue(group, list); return(group); }
/// <summary> /// Saves a <see cref="ILanguage"/> object /// </summary> /// <param name="language"><see cref="ILanguage"/> to save</param> /// <param name="userId">Optional id of the user saving the language</param> public void Save(ILanguage language, int userId = 0) { using (var scope = ScopeProvider.CreateScope()) { // write-lock languages to guard against race conds when dealing with default language scope.WriteLock(Constants.Locks.Languages); // look for cycles - within write-lock if (language.FallbackLanguageId.HasValue) { var languages = _languageRepository.GetMany().ToDictionary(x => x.Id, x => x); if (!languages.ContainsKey(language.FallbackLanguageId.Value)) { throw new InvalidOperationException($"Cannot save language {language.IsoCode} with fallback id={language.FallbackLanguageId.Value} which is not a valid language id."); } if (CreatesCycle(language, languages)) { throw new InvalidOperationException($"Cannot save language {language.IsoCode} with fallback {languages[language.FallbackLanguageId.Value].IsoCode} as it would create a fallback cycle."); } } var saveEventArgs = new SaveEventArgs <ILanguage>(language); if (scope.Events.DispatchCancelable(SavingLanguage, this, saveEventArgs)) { scope.Complete(); return; } _languageRepository.Save(language); saveEventArgs.CanCancel = false; scope.Events.Dispatch(SavedLanguage, this, saveEventArgs); Audit(AuditType.Save, "Save Language", userId, language.Id, ObjectTypes.GetName(UmbracoObjectTypes.Language)); scope.Complete(); } }
private GameObject ReturnObject (ObjectTypes obj) { if (obj == ObjectTypes.Rocket) return _rocket; else if (obj == ObjectTypes.BlackHole) return _blackHole; else if (obj == ObjectTypes.Rocky) return _rocky; else if (obj == ObjectTypes.Rocky2) return _rocky2; else if (obj == ObjectTypes.GasGiant) return _gasGiant; else if (obj == ObjectTypes.EndPlanet) return _endPlanet; else if (obj == ObjectTypes.StartPlanet) return _startPlanet; else if (obj == ObjectTypes.Beyonce) return _beyonce; else if (obj == ObjectTypes.ButtHole) return _buttHole; else if (obj == ObjectTypes.LonelyPlanet) return _lonelyPlanet; else if (obj == ObjectTypes.SeaGod) return _seaGod; else if (obj == ObjectTypes.Son) return _son; else if (obj == ObjectTypes.WormIn) return _wormIn; else if (obj == ObjectTypes.WormOut) return _wormOut; else if (obj == ObjectTypes.BigAsteroid) return _bigAsteroid; else if (obj == ObjectTypes.SmallAsteroid) return _smallAsteroid; return null; }
/// <summary> /// Create a new UserObjectRight /// </summary> /// <param name="userId">Id of the user to create right for</param> /// <param name="objectType">The type of entity to create a right for</param> /// <exception cref="NotImplementedException">NotImplementedException if ObjectType is unhandled</exception> /// <returns>UserObjectRightCreateViewModel</returns> public ActionResult Create(int userId, ObjectTypes objectType) { using (var context = dataContextFactory.CreateByUser()) { UserObjectRight userObjectRight = NewUserObjectRight(objectType); SelectList objectList = null; Model.Right right = null; switch(objectType) { case ObjectTypes.Vendor: objectList = (from v in context.Vendors select v).ToSelectList(x => x.ObjectId, x => x.Name); right = (from x in context.Rights where x.RightId == Model.VendorAdmin.Id select x).FirstOrDefault(); break; case ObjectTypes.Customer: objectList = (from c in context.Customers select c).ToSelectList(x => x.ObjectId, x => x.Name); right = (from x in context.Rights where x.RightId == Model.EditEntityMembers.Id select x).FirstOrDefault(); break; case ObjectTypes.License: objectList = (from l in context.Licenses select new {Id = l.ObjectId, Name = l.Sku.SkuCode}).ToSelectList(x => x.Id, x => x.Name); right = (from x in context.Rights where x.RightId == Model.EditLicenseInfo.Id select x).FirstOrDefault(); break; default: throw new NotImplementedException("ObjectType not known"); } userObjectRight.User = (from x in context.Users where x.UserId == userId select x).FirstOrDefault(); userObjectRight.UserId = userId; userObjectRight.Right = right; userObjectRight.RightId = right.RightId; var viewModel = new UserObjectRightCreateViewModel(userObjectRight, objectType, objectList); viewModel.UseLocalReferrerAsRedirectUrl(Request); return View(viewModel); } }
/// <summary> /// Saves a <see cref="ILanguage"/> object /// </summary> /// <param name="language"><see cref="ILanguage"/> to save</param> /// <param name="userId">Optional id of the user saving the language</param> public void Save(ILanguage language, int userId = Cms.Core.Constants.Security.SuperUserId) { using (var scope = ScopeProvider.CreateScope()) { // write-lock languages to guard against race conds when dealing with default language scope.WriteLock(Cms.Core.Constants.Locks.Languages); // look for cycles - within write-lock if (language.FallbackLanguageId.HasValue) { var languages = _languageRepository.GetMany().ToDictionary(x => x.Id, x => x); if (!languages.ContainsKey(language.FallbackLanguageId.Value)) { throw new InvalidOperationException($"Cannot save language {language.IsoCode} with fallback id={language.FallbackLanguageId.Value} which is not a valid language id."); } if (CreatesCycle(language, languages)) { throw new InvalidOperationException($"Cannot save language {language.IsoCode} with fallback {languages[language.FallbackLanguageId.Value].IsoCode} as it would create a fallback cycle."); } } EventMessages eventMessages = EventMessagesFactory.Get(); var savingNotification = new LanguageSavingNotification(language, eventMessages); if (scope.Notifications.PublishCancelable(savingNotification)) { scope.Complete(); return; } _languageRepository.Save(language); scope.Notifications.Publish(new LanguageSavedNotification(language, eventMessages).WithStateFrom(savingNotification)); Audit(AuditType.Save, "Save Language", userId, language.Id, ObjectTypes.GetName(UmbracoObjectTypes.Language)); scope.Complete(); } }
//defaulted moveable object, no velocity //overload that instantiates the BoundingBox; MUST USE COLLISION PROCESSOR public ScreenModel(Game1 GameRefArg, Model SentModel, Vector3 ModelPosition) { GameRef = GameRefArg; Position = ModelPosition; MyModel = SentModel; //Gets the object type attribute from the List<object> DataFromProcessor=(List<object>)MyModel.Tag; CollisionType = (ObjectTypes)DataFromProcessor[0]; //only allocates space when the bounding box must be checked; //otherwise, then use the sphere to check if (CollisionType == ObjectTypes.Box) { //gets box data from the content //Does not check for exception in this case, because this method should be used on models that go through the processor BoundingBox Temp = (BoundingBox)DataFromProcessor[1]; //adds the Position Vector to the Vectors that control the shape of the bounding box //-----> because Vectors aren't as "free floating" in programing as they are in math LocalBox = new BoundingBox(Temp.Min + Position, Temp.Max + Position); //allocates current data from the default spot...but these values will change based on a direction/velocity vector MinVect = LocalBox.Min; MaxVect = LocalBox.Max; MovingBox = new BoundingBox(MinVect, MaxVect); } //case for if this model is a room if (CollisionType == ObjectTypes.Room) { ListOfWalls = (List<Plane>)DataFromProcessor[1]; } //allocates the other related objects if the bool is set to true Moveable = true; //Can be picked up by the user PickUpable = true; //default velocity as a unit vector...Remember: an object stays at rest until it is acted upon by another force! Velocity = Vector3.Zero; //used so any object can have it's bounding box drawn...should be removed later if memory needs to be saved buffers = new BoundingBoxBuffers(this.MovingBox, GameRef); }
/// <summary> /// Deletes a <see cref="ILanguage"/> by removing it (but not its usages) from the db /// </summary> /// <param name="language"><see cref="ILanguage"/> to delete</param> /// <param name="userId">Optional id of the user deleting the language</param> public void Delete(ILanguage language, int userId = 0) { using (var scope = ScopeProvider.CreateScope()) { // write-lock languages to guard against race conds when dealing with default language scope.WriteLock(Constants.Locks.Languages); var deleteEventArgs = new DeleteEventArgs <ILanguage>(language); if (scope.Events.DispatchCancelable(DeletingLanguage, this, deleteEventArgs)) { scope.Complete(); return; } // NOTE: Other than the fall-back language, there aren't any other constraints in the db, so possible references aren't deleted _languageRepository.Delete(language); deleteEventArgs.CanCancel = false; scope.Events.Dispatch(DeletedLanguage, this, deleteEventArgs); Audit(AuditType.Delete, "Delete Language", userId, language.Id, ObjectTypes.GetName(UmbracoObjectTypes.Language)); scope.Complete(); } }
/// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- internal void TS_GetNonSupportedDataType(out ObjectTypes unSupported, object currentValue, CheckType checkType) { if (currentValue == null) ThrowMe(checkType, TestCaseCurrentStep + ": ValueAsObect == null, can't determine what datatype is unsupported without know the current valid datatype"); ObjectTypes ot = Get_ObjectTypes(currentValue); unSupported = ObjectTypes.Unknown; ObjectTypes[] supportedForDataType = SupportedType(currentValue); do { unSupported = (ObjectTypes)Helpers.RandomValue(0, Convert.ToInt32(ObjectTypes.Last, CultureInfo.CurrentCulture)); } while (!Array.IndexOf(supportedForDataType, unSupported).Equals(-1)); Comment("Datatype of existing object is " + ot + ", returning datatype of " + unSupported); m_TestStep++; }
/// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- internal bool SupportsDataType(ObjectTypes objType, object CurrentValue) { Comment(" Checking to see if " + CurrentValue.GetType() + " supports " + objType); ObjectTypes[] supportedDataType = SupportedType(CurrentValue); return (!Array.IndexOf(supportedDataType, objType).Equals(-1)); }
/// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- internal void TS_SupportsDataType(ObjectTypes objType, object CurrentValue, bool CanBeNull, CheckType checkType) { Comment("Determining if " + CurrentValue + " supports " + objType + " type"); if (CanBeNull && (CurrentValue == null)) { Comment("Object was equal to null and is allowed"); } else { // This is a step, since we said it could not support null values if we get to this location if (CurrentValue == null) ThrowMe(CheckType.Verification, "Cannot check to see if CurrentValue supports " + objType + " since CurrentValue = null so cannot call CurrentValue.GetType()"); if (!SupportsDataType(objType, CurrentValue)) ThrowMe(checkType, CurrentValue.GetType() + " does not support " + objType); } m_TestStep++; }
public AliasedSetCommand( AccessLevel level, string command, string name, string value, ObjectTypes objects ) { m_Name = name; m_Value = value; AccessLevel = level; if ( objects == ObjectTypes.Items ) Supports = CommandSupport.AllItems; else if ( objects == ObjectTypes.Mobiles ) Supports = CommandSupport.AllMobiles; else Supports = CommandSupport.All; Commands = new string[]{ command }; ObjectTypes = objects; Usage = command; Description = String.Format( "Sets the {0} property to {1}.", name, value ); }
/// <summary> /// FavoriteId, ObjectTypeId, ObjectId, ObjectUid, UserId, Title /// </summary> /// <returns></returns> public static DataTable GetListFavoritesDT(ObjectTypes objectType) { return DBCommon.GetListFavoritesDT((int)objectType, Security.CurrentUser.UserID); }
private void ProcessUpdateRequest(Exchange exchange) { Request request = exchange.Request; Guid clientID; Response response; if (StringUtils.GuidTryDecode(request.UriPath.Substring(4), out clientID)) { LWM2MClient client = BusinessLogicFactory.Clients.GetClient(clientID); if (client == null) { response = Response.CreateResponse(request, StatusCode.NotFound); } else { client.Parse(request.UriQueries); BusinessLogicFactory.Clients.UpdateClientActivity(client); client.Address = request.Source; client.EndPoint = exchange.EndPoint; bool updatedLifeTime = false; if ((request.ContentType == (int)MediaType.ApplicationLinkFormat) || (request.ContentType == -1)) { if (request.PayloadSize > 0) { ObjectTypes objectTypes = new ObjectTypes(); objectTypes.Parse(request.PayloadString); if (ObjectTypes.Compare(client.SupportedTypes, objectTypes) != 0) { client.SupportedTypes = objectTypes; if (client.ClientID != Guid.Empty) { DataAccessFactory.Clients.SaveClient(client, TObjectState.Add); updatedLifeTime = true; } BusinessLogicFactory.Clients.ClientChangedSupportedTypes(client); } } } if (!updatedLifeTime) { BusinessLogicFactory.Clients.UpdateClientLifetime(client.ClientID, client.Lifetime); } response = Response.CreateResponse(request, StatusCode.Changed); ApplicationEventLog.Write(LogLevel.Information, string.Concat("Client update ", client.Name, " address ", client.Address.ToString())); } } else { ApplicationEventLog.WriteEntry(string.Concat("Invalid update location", request.UriPath)); response = Response.CreateResponse(request, StatusCode.BadRequest); } exchange.SendResponse(response); }
private void ProcessRegisterRequest(Exchange exchange) { Request request = exchange.Request; LWM2MClient client = new LWM2MClient(); client.Server = _ServerEndPoint; client.Address = request.Source; client.Parse(request.UriQueries); ObjectTypes objectTypes = new ObjectTypes(); objectTypes.Parse(request.PayloadString); client.SupportedTypes = objectTypes; client.EndPoint = exchange.EndPoint; if (_SecureChannel != null) { CertificateInfo certificateInfo = _SecureChannel.GetClientCertificateInfo(client.Address); if (certificateInfo == null) { string pskIdentity = _SecureChannel.GetClientPSKIdentity(client.Address); if (!string.IsNullOrEmpty(pskIdentity)) { Guid clientID; PSKIdentity identity = DataAccessFactory.Identities.GetPSKIdentity(pskIdentity); if (identity != null) { if (StringUtils.GuidTryDecode(pskIdentity, out clientID)) { client.ClientID = clientID; } client.OrganisationID = identity.OrganisationID; } } } else { Console.WriteLine(certificateInfo.Subject.CommonName); Console.WriteLine(certificateInfo.Subject.Organistion); Guid clientID; if (Guid.TryParse(certificateInfo.Subject.CommonName, out clientID)) { client.ClientID = clientID; } int organisationID; if (int.TryParse(certificateInfo.Subject.Organistion, out organisationID)) { client.OrganisationID = organisationID; } } } if (client.ClientID != Guid.Empty && (client.OrganisationID > 0 || !SecureOnly) && !DataAccessFactory.Clients.IsBlacklisted(client.ClientID)) { BusinessLogicFactory.Clients.AddClient(client); } Response response = Response.CreateResponse(request, StatusCode.Created); //response.AddOption(Option.Create(OptionType.LocationPath, string.Concat("rd/",StringUtils.GuidEncode(client.ClientID)))); response.AddOption(Option.Create(OptionType.LocationPath, "rd")); response.AddOption(Option.Create(OptionType.LocationPath, StringUtils.GuidEncode(client.ClientID))); exchange.SendResponse(response); ApplicationEventLog.Write(LogLevel.Information, string.Concat("Client registered ", client.Name, " address ", client.Address.ToString())); }
/// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- internal void TS_VerifyObjectType(object obj, ObjectTypes objType, bool CanBeNull, CheckType checkType) { bool CorrectType = false; if (obj == null) //& CanBeNull.Equals(false)) ThrowMe(checkType, TestCaseCurrentStep + ": ValueAsObject returned a null value"); switch (objType) { case ObjectTypes.Boolean: CorrectType = obj.GetType().Equals(typeof(System.Boolean)); break; case ObjectTypes.Char: CorrectType = obj.GetType().Equals(typeof(System.Char)); break; case ObjectTypes.SByte: CorrectType = obj.GetType().Equals(typeof(System.SByte)); break; case ObjectTypes.Byte: CorrectType = obj.GetType().Equals(typeof(System.Byte)); break; case ObjectTypes.Int16: CorrectType = obj.GetType().Equals(typeof(System.Int16)); break; case ObjectTypes.Int32: CorrectType = obj.GetType().Equals(typeof(System.Int32)); break; case ObjectTypes.UInt16: CorrectType = obj.GetType().Equals(typeof(System.UInt16)); break; case ObjectTypes.UInt32: CorrectType = obj.GetType().Equals(typeof(System.UInt32)); break; case ObjectTypes.Int64: CorrectType = obj.GetType().Equals(typeof(System.Int64)); break; case ObjectTypes.UInt64: CorrectType = obj.GetType().Equals(typeof(System.UInt64)); break; case ObjectTypes.Single: CorrectType = obj.GetType().Equals(typeof(System.Single)); break; case ObjectTypes.Decimal: CorrectType = obj.GetType().Equals(typeof(System.Decimal)); break; case ObjectTypes.Double: CorrectType = obj.GetType().Equals(typeof(System.Double)); break; case ObjectTypes.Date: CorrectType = obj.GetType().Equals(typeof(System.DateTime)); break; case ObjectTypes.DateTime: CorrectType = obj.GetType().Equals(typeof(System.DateTime)); break; case ObjectTypes.String: CorrectType = obj.GetType().Equals(typeof(System.String)); break; case ObjectTypes.ItemCheckState: CorrectType = obj.GetType().Equals(typeof(string)); break; case ObjectTypes.IPAddress: CorrectType = obj.GetType().Equals(typeof(System.Net.IPAddress)); break; default: ThrowMe(checkType, TestCaseCurrentStep + ": ValueAsObject returned " + obj.GetType().ToString()); break; } if (!CorrectType) ThrowMe(checkType, "Current object is '" + obj.GetType().ToString() + "' and not '" + objType + "'"); Comment("Object type is '" + obj.GetType() + "'"); m_TestStep++; }
/// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- internal void TS_GetRandomValue(out object obj, object CurrentType, ObjectTypes dataType, bool SameType, bool MustBeDifferentValue, CheckType checkType) { ObjectTypes newObjectType = dataType; // If we pass in unknown, determine the correct data type if (dataType.Equals(ObjectTypes.Unknown)) { dataType = this.Get_ObjectTypes(CurrentType); if (dataType.Equals(ObjectTypes.IPAddress)) ThrowMe(CheckType.IncorrectElementConfiguration, "Don't know how to get a random IPAddress"); } // Get a new type if SameType == false if (!SameType) { do { newObjectType = (ObjectTypes)(int)Helpers.RandomValue(0, (int)ObjectTypes.Last); } while (newObjectType.Equals(ObjectTypes.Last) || newObjectType.Equals(ObjectTypes.IPAddress) || newObjectType.Equals(newObjectType)); dataType = newObjectType; } // Try 10 times to find the random value int TryCount = 0; do { if (TryCount > 10) ThrowMe(checkType, "Could not determine a random value different from the current value in 10 tries"); obj = Helpers.GetRandomValidValue(m_le, null); } while (MustBeDifferentValue.Equals(true) && obj.Equals(CurrentType)); Comment("Returning random value of (" + obj.GetType() + ")" + obj); m_TestStep++; }
/// <summary> /// Reader returns fields: /// DiscussionId, ObjectTypeId, ObjectId, CreatorId, CreationDate, Text, CreatorName /// </summary> public static DataTable GetListDiscussionsDataTable(ObjectTypes ObjectTypeId, int ObjectId, int TimeZoneId) { if (ObjectTypeId == ObjectTypes.ToDo) // вернуть с учётом родительского Task return DbHelper2.RunSpDataTable( TimeZoneId, new string[] { "CreationDate" }, "DiscussionsGetByToDo", DbHelper2.mp("@ToDoId", SqlDbType.Int, ObjectId)); else if (ObjectTypeId == ObjectTypes.Task) // вернуть с учётом дочерних todo return DbHelper2.RunSpDataTable( TimeZoneId, new string[] { "CreationDate" }, "DiscussionsGetByTask", DbHelper2.mp("@TaskId", SqlDbType.Int, ObjectId)); else return DbHelper2.RunSpDataTable( TimeZoneId, new string[] { "CreationDate" }, "DiscussionsGet", DbHelper2.mp("@ObjectTypeId", SqlDbType.Int, (int)ObjectTypeId), DbHelper2.mp("@ObjectId", SqlDbType.Int, ObjectId)); }