content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using UnityEngine; public class MenuPage : Openable { public int index; private UIAnimation transferAnimation; public override void Awake() { setupTransition(); base.Awake(); } public virtual void Start() { } public void setupTransition() { transferAnimation = new Fade(); transferAnimation.target = transform; } public override void OnOpen() { Debug.Log("Playing animation: " + this); transferAnimation.Play(); Finished = true; } public override void OnClose() { transferAnimation.Play(); Finished = true; } }
18.222222
48
0.58689
[ "MIT" ]
Mineorbit/DungeonsAndDungeons
Assets/Scripts/UI/Menus/MenuPage.cs
656
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Compliance.EarlyBound { [System.Runtime.Serialization.DataContractAttribute()] public enum DuplicateRuleMatchingEntityTypeCode { [System.Runtime.Serialization.EnumMemberAttribute()] AccessRequestDocument = 10224, [System.Runtime.Serialization.EnumMemberAttribute()] ACIViewMapper = 8040, [System.Runtime.Serialization.EnumMemberAttribute()] ActionCard = 9962, [System.Runtime.Serialization.EnumMemberAttribute()] ActionCardType = 9983, [System.Runtime.Serialization.EnumMemberAttribute()] ActionCardUserSettings = 9973, [System.Runtime.Serialization.EnumMemberAttribute()] ActionCardUserState = 9968, [System.Runtime.Serialization.EnumMemberAttribute()] Activity = 4200, [System.Runtime.Serialization.EnumMemberAttribute()] ActivityFileAttachment = 10110, [System.Runtime.Serialization.EnumMemberAttribute()] ActivityParty = 135, [System.Runtime.Serialization.EnumMemberAttribute()] ActofParliament = 10225, [System.Runtime.Serialization.EnumMemberAttribute()] Address = 1071, [System.Runtime.Serialization.EnumMemberAttribute()] AdvancedSimilarityRule = 9949, [System.Runtime.Serialization.EnumMemberAttribute()] AIBuilderDataset = 10012, [System.Runtime.Serialization.EnumMemberAttribute()] AIBuilderDatasetFile = 10013, [System.Runtime.Serialization.EnumMemberAttribute()] AIBuilderDatasetRecord = 10035, [System.Runtime.Serialization.EnumMemberAttribute()] AIBuilderDatasetsContainer = 10014, [System.Runtime.Serialization.EnumMemberAttribute()] AIBuilderFile = 10015, [System.Runtime.Serialization.EnumMemberAttribute()] AIBuilderFileAttachedData = 10016, [System.Runtime.Serialization.EnumMemberAttribute()] AIConfiguration = 402, [System.Runtime.Serialization.EnumMemberAttribute()] AIFormProcessingDocument = 10017, [System.Runtime.Serialization.EnumMemberAttribute()] AIModel = 401, [System.Runtime.Serialization.EnumMemberAttribute()] AIObjectDetectionBoundingBox = 10020, [System.Runtime.Serialization.EnumMemberAttribute()] AIObjectDetectionImage = 10018, [System.Runtime.Serialization.EnumMemberAttribute()] AIObjectDetectionImageMapping = 10021, [System.Runtime.Serialization.EnumMemberAttribute()] AIObjectDetectionLabel = 10019, [System.Runtime.Serialization.EnumMemberAttribute()] AITemplate = 400, [System.Runtime.Serialization.EnumMemberAttribute()] AllegationConcern = 10226, [System.Runtime.Serialization.EnumMemberAttribute()] AllegationType = 10227, [System.Runtime.Serialization.EnumMemberAttribute()] AnalysisComponent = 10026, [System.Runtime.Serialization.EnumMemberAttribute()] AnalysisJob = 10027, [System.Runtime.Serialization.EnumMemberAttribute()] AnalysisResult = 10028, [System.Runtime.Serialization.EnumMemberAttribute()] AnalysisResultDetail = 10029, [System.Runtime.Serialization.EnumMemberAttribute()] Announcement = 132, [System.Runtime.Serialization.EnumMemberAttribute()] AnnualFiscalCalendar = 2000, [System.Runtime.Serialization.EnumMemberAttribute()] ApiSettings = 10010, [System.Runtime.Serialization.EnumMemberAttribute()] AppAction = 10155, [System.Runtime.Serialization.EnumMemberAttribute()] AppConfigMaster = 9011, [System.Runtime.Serialization.EnumMemberAttribute()] AppConfiguration = 9012, [System.Runtime.Serialization.EnumMemberAttribute()] AppConfigurationInstance = 9013, [System.Runtime.Serialization.EnumMemberAttribute()] ApplicationFile = 4707, [System.Runtime.Serialization.EnumMemberAttribute()] ApplicationRibbons = 1120, [System.Runtime.Serialization.EnumMemberAttribute()] ApplicationUser = 10041, [System.Runtime.Serialization.EnumMemberAttribute()] AppModuleComponent = 9007, [System.Runtime.Serialization.EnumMemberAttribute()] AppModuleMetadata = 8700, [System.Runtime.Serialization.EnumMemberAttribute()] AppModuleMetadataAsyncOperation = 8702, [System.Runtime.Serialization.EnumMemberAttribute()] AppModuleMetadataDependency = 8701, [System.Runtime.Serialization.EnumMemberAttribute()] AppModuleRoles = 9009, [System.Runtime.Serialization.EnumMemberAttribute()] Appointment = 4201, [System.Runtime.Serialization.EnumMemberAttribute()] Article = 127, [System.Runtime.Serialization.EnumMemberAttribute()] ArticleComment = 1082, [System.Runtime.Serialization.EnumMemberAttribute()] ArticleTemplate = 1016, [System.Runtime.Serialization.EnumMemberAttribute()] Attachment_1001 = 1001, [System.Runtime.Serialization.EnumMemberAttribute()] Attachment_1002 = 1002, [System.Runtime.Serialization.EnumMemberAttribute()] Attribute = 9808, [System.Runtime.Serialization.EnumMemberAttribute()] AttributeMap = 4601, [System.Runtime.Serialization.EnumMemberAttribute()] Auditing = 4567, [System.Runtime.Serialization.EnumMemberAttribute()] AuthorizationServer = 1094, [System.Runtime.Serialization.EnumMemberAttribute()] AzureServiceConnection = 9936, [System.Runtime.Serialization.EnumMemberAttribute()] BATimeEntry = 10228, [System.Runtime.Serialization.EnumMemberAttribute()] BotContent = 10070, [System.Runtime.Serialization.EnumMemberAttribute()] BulkDeleteFailure = 4425, [System.Runtime.Serialization.EnumMemberAttribute()] BulkDeleteOperation = 4424, [System.Runtime.Serialization.EnumMemberAttribute()] BusinessAdvisory = 10291, [System.Runtime.Serialization.EnumMemberAttribute()] BusinessDataLocalizedLabel = 4232, [System.Runtime.Serialization.EnumMemberAttribute()] BusinessProcessFlowInstance = 4725, [System.Runtime.Serialization.EnumMemberAttribute()] BusinessUnit = 10, [System.Runtime.Serialization.EnumMemberAttribute()] BusinessUnitMap = 6, [System.Runtime.Serialization.EnumMemberAttribute()] Calendar = 4003, [System.Runtime.Serialization.EnumMemberAttribute()] CalendarRule = 4004, [System.Runtime.Serialization.EnumMemberAttribute()] CallbackRegistration = 301, [System.Runtime.Serialization.EnumMemberAttribute()] CanvasApp = 300, [System.Runtime.Serialization.EnumMemberAttribute()] CanvasAppExtendedMetadata = 10050, [System.Runtime.Serialization.EnumMemberAttribute()] CascadeGrantRevokeAccessRecordsTracker = 10054, [System.Runtime.Serialization.EnumMemberAttribute()] CascadeGrantRevokeAccessVersionTracker = 10055, [System.Runtime.Serialization.EnumMemberAttribute()] Catalog = 10064, [System.Runtime.Serialization.EnumMemberAttribute()] CatalogAssignment = 10065, [System.Runtime.Serialization.EnumMemberAttribute()] Category = 9959, [System.Runtime.Serialization.EnumMemberAttribute()] ChannelAccessProfile = 3005, [System.Runtime.Serialization.EnumMemberAttribute()] ChannelAccessProfileRule = 9400, [System.Runtime.Serialization.EnumMemberAttribute()] ChannelAccessProfileRuleItem = 9401, [System.Runtime.Serialization.EnumMemberAttribute()] ChannelProperty = 1236, [System.Runtime.Serialization.EnumMemberAttribute()] ChannelPropertyGroup = 1234, [System.Runtime.Serialization.EnumMemberAttribute()] Chatbot = 10072, [System.Runtime.Serialization.EnumMemberAttribute()] Chatbotsubcomponent = 10073, [System.Runtime.Serialization.EnumMemberAttribute()] Checklist = 10229, [System.Runtime.Serialization.EnumMemberAttribute()] ChecklistResponse = 10230, [System.Runtime.Serialization.EnumMemberAttribute()] ChecklistType = 10231, [System.Runtime.Serialization.EnumMemberAttribute()] Clientupdate = 36, [System.Runtime.Serialization.EnumMemberAttribute()] ColumnMapping = 4417, [System.Runtime.Serialization.EnumMemberAttribute()] Comment_10166 = 10166, [System.Runtime.Serialization.EnumMemberAttribute()] Comment_8005 = 8005, [System.Runtime.Serialization.EnumMemberAttribute()] Complaint = 10233, [System.Runtime.Serialization.EnumMemberAttribute()] ComplianceBreachCause = 10234, [System.Runtime.Serialization.EnumMemberAttribute()] ComplianceBreachEffort = 10235, [System.Runtime.Serialization.EnumMemberAttribute()] ComplianceBreachHarm = 10236, [System.Runtime.Serialization.EnumMemberAttribute()] ComplianceBreachInfluence = 10237, [System.Runtime.Serialization.EnumMemberAttribute()] CompliancePersonalInformation = 10238, [System.Runtime.Serialization.EnumMemberAttribute()] ComponentLayer = 10003, [System.Runtime.Serialization.EnumMemberAttribute()] ComponentLayerDataSource = 10004, [System.Runtime.Serialization.EnumMemberAttribute()] Connection = 3234, [System.Runtime.Serialization.EnumMemberAttribute()] ConnectionReference = 10049, [System.Runtime.Serialization.EnumMemberAttribute()] ConnectionRole = 3231, [System.Runtime.Serialization.EnumMemberAttribute()] ConnectionRoleObjectTypeCode = 3233, [System.Runtime.Serialization.EnumMemberAttribute()] Connector = 372, [System.Runtime.Serialization.EnumMemberAttribute()] Contact = 2, [System.Runtime.Serialization.EnumMemberAttribute()] ContactAudit = 10239, [System.Runtime.Serialization.EnumMemberAttribute()] ConversationTranscript = 10071, [System.Runtime.Serialization.EnumMemberAttribute()] CTSCategory = 10241, [System.Runtime.Serialization.EnumMemberAttribute()] CTSCorrespondence = 10242, [System.Runtime.Serialization.EnumMemberAttribute()] CTSCorrespondenceType = 10243, [System.Runtime.Serialization.EnumMemberAttribute()] CTSDocument = 10244, [System.Runtime.Serialization.EnumMemberAttribute()] CTSDocumentType = 10245, [System.Runtime.Serialization.EnumMemberAttribute()] CTSSigningAuthority = 10246, [System.Runtime.Serialization.EnumMemberAttribute()] CTSTask = 10249, [System.Runtime.Serialization.EnumMemberAttribute()] CTSTaskAction = 10247, [System.Runtime.Serialization.EnumMemberAttribute()] CTSTaskActionRequired = 10248, [System.Runtime.Serialization.EnumMemberAttribute()] CTSTaskSection = 10250, [System.Runtime.Serialization.EnumMemberAttribute()] Currency = 9105, [System.Runtime.Serialization.EnumMemberAttribute()] CustomAPI = 10067, [System.Runtime.Serialization.EnumMemberAttribute()] CustomAPIRequestParameter = 10068, [System.Runtime.Serialization.EnumMemberAttribute()] CustomAPIResponseProperty = 10069, [System.Runtime.Serialization.EnumMemberAttribute()] CustomControl = 9753, [System.Runtime.Serialization.EnumMemberAttribute()] CustomControlDefaultConfig = 9755, [System.Runtime.Serialization.EnumMemberAttribute()] CustomControlResource = 9754, [System.Runtime.Serialization.EnumMemberAttribute()] CustomerRelationship = 4502, [System.Runtime.Serialization.EnumMemberAttribute()] Dataflow = 418, [System.Runtime.Serialization.EnumMemberAttribute()] DataflowRefreshHistory = 10222, [System.Runtime.Serialization.EnumMemberAttribute()] DataImport = 4410, [System.Runtime.Serialization.EnumMemberAttribute()] DataLakeFolder = 10060, [System.Runtime.Serialization.EnumMemberAttribute()] DataLakeFolderPermission = 10061, [System.Runtime.Serialization.EnumMemberAttribute()] DataLakeWorkspace = 10039, [System.Runtime.Serialization.EnumMemberAttribute()] DataLakeWorkspacePermission = 10040, [System.Runtime.Serialization.EnumMemberAttribute()] DataMap = 4411, [System.Runtime.Serialization.EnumMemberAttribute()] DataPerformanceDashboard = 4450, [System.Runtime.Serialization.EnumMemberAttribute()] DelveActionHub = 9961, [System.Runtime.Serialization.EnumMemberAttribute()] Dependency = 7105, [System.Runtime.Serialization.EnumMemberAttribute()] DependencyFeature = 7108, [System.Runtime.Serialization.EnumMemberAttribute()] DependencyNode = 7106, [System.Runtime.Serialization.EnumMemberAttribute()] Directorate = 10251, [System.Runtime.Serialization.EnumMemberAttribute()] DisplayString = 4102, [System.Runtime.Serialization.EnumMemberAttribute()] DisplayStringMap = 4101, [System.Runtime.Serialization.EnumMemberAttribute()] DispositionAction = 10252, [System.Runtime.Serialization.EnumMemberAttribute()] DispositionReason = 10253, [System.Runtime.Serialization.EnumMemberAttribute()] DocumentLocation = 9508, [System.Runtime.Serialization.EnumMemberAttribute()] DocumentSuggestions = 1189, [System.Runtime.Serialization.EnumMemberAttribute()] DocumentTemplate = 9940, [System.Runtime.Serialization.EnumMemberAttribute()] DuplicateDetectionRule = 4414, [System.Runtime.Serialization.EnumMemberAttribute()] DuplicateRecord = 4415, [System.Runtime.Serialization.EnumMemberAttribute()] DuplicateRuleCondition = 4416, [System.Runtime.Serialization.EnumMemberAttribute()] DutyCounselCalendar = 10254, [System.Runtime.Serialization.EnumMemberAttribute()] Email = 4202, [System.Runtime.Serialization.EnumMemberAttribute()] EmailHash = 4023, [System.Runtime.Serialization.EnumMemberAttribute()] EmailSearch = 4299, [System.Runtime.Serialization.EnumMemberAttribute()] EmailServerProfile = 9605, [System.Runtime.Serialization.EnumMemberAttribute()] EmailSignature = 9997, [System.Runtime.Serialization.EnumMemberAttribute()] EmailTemplate = 2010, [System.Runtime.Serialization.EnumMemberAttribute()] Entity = 9800, [System.Runtime.Serialization.EnumMemberAttribute()] EntityAnalyticsConfig = 430, [System.Runtime.Serialization.EnumMemberAttribute()] EntityImageConfiguration = 432, [System.Runtime.Serialization.EnumMemberAttribute()] EntityIndex = 9815, [System.Runtime.Serialization.EnumMemberAttribute()] EntityKey = 9810, [System.Runtime.Serialization.EnumMemberAttribute()] EntityMap = 4600, [System.Runtime.Serialization.EnumMemberAttribute()] EntityRefreshHistory = 10223, [System.Runtime.Serialization.EnumMemberAttribute()] EntityRelationship = 9811, [System.Runtime.Serialization.EnumMemberAttribute()] EnvironmentVariable = 10255, [System.Runtime.Serialization.EnumMemberAttribute()] EnvironmentVariableDefinition = 380, [System.Runtime.Serialization.EnumMemberAttribute()] EnvironmentVariableValue = 381, [System.Runtime.Serialization.EnumMemberAttribute()] Event = 10256, [System.Runtime.Serialization.EnumMemberAttribute()] ExchangeSyncIdMapping = 4120, [System.Runtime.Serialization.EnumMemberAttribute()] ExpanderEvent = 4711, [System.Runtime.Serialization.EnumMemberAttribute()] ExpiredProcess = 955, [System.Runtime.Serialization.EnumMemberAttribute()] ExportSolutionUpload = 10052, [System.Runtime.Serialization.EnumMemberAttribute()] ExternalParty = 3008, [System.Runtime.Serialization.EnumMemberAttribute()] ExternalPartyItem = 9987, [System.Runtime.Serialization.EnumMemberAttribute()] Fax = 4204, [System.Runtime.Serialization.EnumMemberAttribute()] FCAProceduralStep = 10240, [System.Runtime.Serialization.EnumMemberAttribute()] FCProceduralStep = 10257, [System.Runtime.Serialization.EnumMemberAttribute()] FeatureControlSetting = 10150, [System.Runtime.Serialization.EnumMemberAttribute()] Feedback = 9958, [System.Runtime.Serialization.EnumMemberAttribute()] FieldPermission = 1201, [System.Runtime.Serialization.EnumMemberAttribute()] FieldSecurityProfile = 1200, [System.Runtime.Serialization.EnumMemberAttribute()] FieldSharing = 44, [System.Runtime.Serialization.EnumMemberAttribute()] FileAttachment = 55, [System.Runtime.Serialization.EnumMemberAttribute()] FilterTemplate = 30, [System.Runtime.Serialization.EnumMemberAttribute()] FixedMonthlyFiscalCalendar = 2004, [System.Runtime.Serialization.EnumMemberAttribute()] FlowMachine = 10104, [System.Runtime.Serialization.EnumMemberAttribute()] FlowMachineGroup = 10105, [System.Runtime.Serialization.EnumMemberAttribute()] FlowSession = 4720, [System.Runtime.Serialization.EnumMemberAttribute()] Follow = 8003, [System.Runtime.Serialization.EnumMemberAttribute()] GAAffectedIndividual = 10259, [System.Runtime.Serialization.EnumMemberAttribute()] GADisclosureRecipient = 10260, [System.Runtime.Serialization.EnumMemberAttribute()] GANotification = 10262, [System.Runtime.Serialization.EnumMemberAttribute()] GAPersonalInformation = 10261, [System.Runtime.Serialization.EnumMemberAttribute()] GlobalSearchConfiguration = 54, [System.Runtime.Serialization.EnumMemberAttribute()] Goal = 9600, [System.Runtime.Serialization.EnumMemberAttribute()] GoalMetric = 9603, [System.Runtime.Serialization.EnumMemberAttribute()] HelpPage = 10025, [System.Runtime.Serialization.EnumMemberAttribute()] HierarchyRule = 8840, [System.Runtime.Serialization.EnumMemberAttribute()] HierarchySecurityConfiguration = 9919, [System.Runtime.Serialization.EnumMemberAttribute()] Holiday = 10263, [System.Runtime.Serialization.EnumMemberAttribute()] HolidayWrapper = 9996, [System.Runtime.Serialization.EnumMemberAttribute()] ImageAttributeConfiguration = 431, [System.Runtime.Serialization.EnumMemberAttribute()] ImageDescriptor = 1007, [System.Runtime.Serialization.EnumMemberAttribute()] ImportData = 4413, [System.Runtime.Serialization.EnumMemberAttribute()] ImportEntityMapping = 4428, [System.Runtime.Serialization.EnumMemberAttribute()] ImportJob = 9107, [System.Runtime.Serialization.EnumMemberAttribute()] ImportLog = 4423, [System.Runtime.Serialization.EnumMemberAttribute()] ImportSourceFile = 4412, [System.Runtime.Serialization.EnumMemberAttribute()] IndexAttribute = 9816, [System.Runtime.Serialization.EnumMemberAttribute()] IndexedArticle = 126, [System.Runtime.Serialization.EnumMemberAttribute()] IndividualComplaint = 10264, [System.Runtime.Serialization.EnumMemberAttribute()] Industry = 10265, [System.Runtime.Serialization.EnumMemberAttribute()] InformationRequest = 10266, [System.Runtime.Serialization.EnumMemberAttribute()] IntegrationStatus = 3000, [System.Runtime.Serialization.EnumMemberAttribute()] InteractionforEmail = 9986, [System.Runtime.Serialization.EnumMemberAttribute()] InternalAddress = 1003, [System.Runtime.Serialization.EnumMemberAttribute()] InternalCatalogAssignment = 10066, [System.Runtime.Serialization.EnumMemberAttribute()] InterProcessLock = 4011, [System.Runtime.Serialization.EnumMemberAttribute()] InvalidDependency = 7107, [System.Runtime.Serialization.EnumMemberAttribute()] Issue = 10267, [System.Runtime.Serialization.EnumMemberAttribute()] ISVConfig = 4705, [System.Runtime.Serialization.EnumMemberAttribute()] KeyVaultReference = 10099, [System.Runtime.Serialization.EnumMemberAttribute()] KnowledgeArticle = 9953, [System.Runtime.Serialization.EnumMemberAttribute()] KnowledgeArticleAttachment = 10164, [System.Runtime.Serialization.EnumMemberAttribute()] KnowledgeArticleCategory = 9960, [System.Runtime.Serialization.EnumMemberAttribute()] KnowledgeArticleImage = 10008, [System.Runtime.Serialization.EnumMemberAttribute()] Knowledgearticlelanguagesetting = 10107, [System.Runtime.Serialization.EnumMemberAttribute()] KnowledgeArticleTemplate = 10009, [System.Runtime.Serialization.EnumMemberAttribute()] KnowledgeArticleViews = 9955, [System.Runtime.Serialization.EnumMemberAttribute()] KnowledgeBaseRecord = 9930, [System.Runtime.Serialization.EnumMemberAttribute()] KnowledgeFederatedArticle = 10077, [System.Runtime.Serialization.EnumMemberAttribute()] KnowledgeFederatedArticleIncident = 10078, [System.Runtime.Serialization.EnumMemberAttribute()] KnowledgeInteractionInsight = 10058, [System.Runtime.Serialization.EnumMemberAttribute()] Knowledgepersonalization = 10106, [System.Runtime.Serialization.EnumMemberAttribute()] Knowledgesearchfilter = 10109, [System.Runtime.Serialization.EnumMemberAttribute()] KnowledgeSearchInsight = 10059, [System.Runtime.Serialization.EnumMemberAttribute()] KnowledgeSearchModel = 9947, [System.Runtime.Serialization.EnumMemberAttribute()] Knowledgesearchpersonalfilterconfig = 10108, [System.Runtime.Serialization.EnumMemberAttribute()] Language = 9957, [System.Runtime.Serialization.EnumMemberAttribute()] LanguageProvisioningState = 9875, [System.Runtime.Serialization.EnumMemberAttribute()] LegalConsultation = 10268, [System.Runtime.Serialization.EnumMemberAttribute()] LegalConsultationTask = 10269, [System.Runtime.Serialization.EnumMemberAttribute()] LegalStatusHistory = 10270, [System.Runtime.Serialization.EnumMemberAttribute()] Legislation = 10271, [System.Runtime.Serialization.EnumMemberAttribute()] LegislationAllegationType = 10272, [System.Runtime.Serialization.EnumMemberAttribute()] Letter = 4207, [System.Runtime.Serialization.EnumMemberAttribute()] License = 2027, [System.Runtime.Serialization.EnumMemberAttribute()] Like = 8006, [System.Runtime.Serialization.EnumMemberAttribute()] ListValueMapping = 4418, [System.Runtime.Serialization.EnumMemberAttribute()] Litigation = 10258, [System.Runtime.Serialization.EnumMemberAttribute()] LocalConfigStore = 9201, [System.Runtime.Serialization.EnumMemberAttribute()] LookupMapping = 4419, [System.Runtime.Serialization.EnumMemberAttribute()] Mailbox = 9606, [System.Runtime.Serialization.EnumMemberAttribute()] MailboxAutoTrackingFolder = 9608, [System.Runtime.Serialization.EnumMemberAttribute()] MailboxStatistics = 9607, [System.Runtime.Serialization.EnumMemberAttribute()] MailboxTrackingCategory = 9609, [System.Runtime.Serialization.EnumMemberAttribute()] MailMergeTemplate = 9106, [System.Runtime.Serialization.EnumMemberAttribute()] ManagedIdentity = 10100, [System.Runtime.Serialization.EnumMemberAttribute()] ManagedProperty = 9812, [System.Runtime.Serialization.EnumMemberAttribute()] MetadataDifference = 4231, [System.Runtime.Serialization.EnumMemberAttribute()] MobileOfflineProfile = 9866, [System.Runtime.Serialization.EnumMemberAttribute()] MobileOfflineProfileItem = 9867, [System.Runtime.Serialization.EnumMemberAttribute()] MobileOfflineProfileItemAssociation = 9868, [System.Runtime.Serialization.EnumMemberAttribute()] ModeldrivenApp = 9006, [System.Runtime.Serialization.EnumMemberAttribute()] ModelDrivenAppComponentNode = 10046, [System.Runtime.Serialization.EnumMemberAttribute()] ModelDrivenAppComponentNodesEdge = 10045, [System.Runtime.Serialization.EnumMemberAttribute()] ModelDrivenAppElement = 10044, [System.Runtime.Serialization.EnumMemberAttribute()] ModelDrivenAppSetting = 10047, [System.Runtime.Serialization.EnumMemberAttribute()] ModelDrivenAppUserSetting = 10096, [System.Runtime.Serialization.EnumMemberAttribute()] MonthlyFiscalCalendar = 2003, [System.Runtime.Serialization.EnumMemberAttribute()] MultiEntitySearch = 9910, [System.Runtime.Serialization.EnumMemberAttribute()] MultiSelectOptionValue = 9912, [System.Runtime.Serialization.EnumMemberAttribute()] NavigationSetting = 9900, [System.Runtime.Serialization.EnumMemberAttribute()] NewProcess = 950, [System.Runtime.Serialization.EnumMemberAttribute()] NonRelationalDataSource = 10038, [System.Runtime.Serialization.EnumMemberAttribute()] Note = 5, [System.Runtime.Serialization.EnumMemberAttribute()] Notification_10156 = 10156, [System.Runtime.Serialization.EnumMemberAttribute()] Notification_10273 = 10273, [System.Runtime.Serialization.EnumMemberAttribute()] Notification_4110 = 4110, [System.Runtime.Serialization.EnumMemberAttribute()] ODatav4DataSource = 10011, [System.Runtime.Serialization.EnumMemberAttribute()] OfficeDocument = 4490, [System.Runtime.Serialization.EnumMemberAttribute()] OfficeGraphDocument = 9950, [System.Runtime.Serialization.EnumMemberAttribute()] OfficiumDocumentType = 10274, [System.Runtime.Serialization.EnumMemberAttribute()] OfflineCommandDefinition = 9870, [System.Runtime.Serialization.EnumMemberAttribute()] OPCPriority = 10275, [System.Runtime.Serialization.EnumMemberAttribute()] OptionSet = 9809, [System.Runtime.Serialization.EnumMemberAttribute()] OrganisationDepartment = 1, [System.Runtime.Serialization.EnumMemberAttribute()] Organization = 1019, [System.Runtime.Serialization.EnumMemberAttribute()] OrganizationDataSyncSubscription = 10094, [System.Runtime.Serialization.EnumMemberAttribute()] OrganizationDataSyncSubscriptionEntity = 10095, [System.Runtime.Serialization.EnumMemberAttribute()] OrganizationInsightsMetric = 9699, [System.Runtime.Serialization.EnumMemberAttribute()] OrganizationInsightsNotification = 9690, [System.Runtime.Serialization.EnumMemberAttribute()] OrganizationSetting = 10093, [System.Runtime.Serialization.EnumMemberAttribute()] OrganizationStatistic = 4708, [System.Runtime.Serialization.EnumMemberAttribute()] OrganizationUI = 1021, [System.Runtime.Serialization.EnumMemberAttribute()] OtherProceduralStep = 10276, [System.Runtime.Serialization.EnumMemberAttribute()] Owner = 7, [System.Runtime.Serialization.EnumMemberAttribute()] OwnerHistory = 10277, [System.Runtime.Serialization.EnumMemberAttribute()] OwnerMapping = 4420, [System.Runtime.Serialization.EnumMemberAttribute()] Package = 10056, [System.Runtime.Serialization.EnumMemberAttribute()] PAFile = 10279, [System.Runtime.Serialization.EnumMemberAttribute()] PAIssue = 10278, [System.Runtime.Serialization.EnumMemberAttribute()] PAPIPEDAStatusHistory = 10280, [System.Runtime.Serialization.EnumMemberAttribute()] PartnerApplication = 1095, [System.Runtime.Serialization.EnumMemberAttribute()] PDFSetting = 10051, [System.Runtime.Serialization.EnumMemberAttribute()] PersonalDocumentTemplate = 9941, [System.Runtime.Serialization.EnumMemberAttribute()] PersonalInformationType = 10283, [System.Runtime.Serialization.EnumMemberAttribute()] PhoneCall = 4210, [System.Runtime.Serialization.EnumMemberAttribute()] PIAEvent = 10284, [System.Runtime.Serialization.EnumMemberAttribute()] PIAFile = 10285, [System.Runtime.Serialization.EnumMemberAttribute()] PIATask = 10286, [System.Runtime.Serialization.EnumMemberAttribute()] PIPEDAComplaintType = 10289, [System.Runtime.Serialization.EnumMemberAttribute()] PIPEDAFile = 10288, [System.Runtime.Serialization.EnumMemberAttribute()] PIPEDAIssue = 10287, [System.Runtime.Serialization.EnumMemberAttribute()] PIPEDASectionPrinciple = 10290, [System.Runtime.Serialization.EnumMemberAttribute()] PluginAssembly = 4605, [System.Runtime.Serialization.EnumMemberAttribute()] PluginPackage = 10151, [System.Runtime.Serialization.EnumMemberAttribute()] PluginTraceLog = 4619, [System.Runtime.Serialization.EnumMemberAttribute()] PluginType = 4602, [System.Runtime.Serialization.EnumMemberAttribute()] PluginTypeStatistic = 4603, [System.Runtime.Serialization.EnumMemberAttribute()] PMInferredTask = 10144, [System.Runtime.Serialization.EnumMemberAttribute()] PMRecording = 10145, [System.Runtime.Serialization.EnumMemberAttribute()] Position = 50, [System.Runtime.Serialization.EnumMemberAttribute()] Post = 8000, [System.Runtime.Serialization.EnumMemberAttribute()] PostRegarding = 8002, [System.Runtime.Serialization.EnumMemberAttribute()] PostRole = 8001, [System.Runtime.Serialization.EnumMemberAttribute()] PrincipalEntityBusinessUnitMap = 10154, [System.Runtime.Serialization.EnumMemberAttribute()] PrincipalSyncAttributeMap = 1404, [System.Runtime.Serialization.EnumMemberAttribute()] PrivacyComplaintType = 10282, [System.Runtime.Serialization.EnumMemberAttribute()] PrivacySection = 10281, [System.Runtime.Serialization.EnumMemberAttribute()] Privilege = 1023, [System.Runtime.Serialization.EnumMemberAttribute()] PrivilegeObjectTypeCode = 31, [System.Runtime.Serialization.EnumMemberAttribute()] Process = 4703, [System.Runtime.Serialization.EnumMemberAttribute()] ProcessConfiguration = 9650, [System.Runtime.Serialization.EnumMemberAttribute()] ProcessDependency = 4704, [System.Runtime.Serialization.EnumMemberAttribute()] ProcessLog = 4706, [System.Runtime.Serialization.EnumMemberAttribute()] ProcessSession = 4710, [System.Runtime.Serialization.EnumMemberAttribute()] ProcessStage = 4724, [System.Runtime.Serialization.EnumMemberAttribute()] ProcessStageParameter = 10023, [System.Runtime.Serialization.EnumMemberAttribute()] ProcessTrigger = 4712, [System.Runtime.Serialization.EnumMemberAttribute()] Provision = 10292, [System.Runtime.Serialization.EnumMemberAttribute()] ProvisionLanguageForUser = 10062, [System.Runtime.Serialization.EnumMemberAttribute()] PRPAActivity = 10293, [System.Runtime.Serialization.EnumMemberAttribute()] PRPAContributionsProgram = 10294, [System.Runtime.Serialization.EnumMemberAttribute()] PRPAFPT = 10295, [System.Runtime.Serialization.EnumMemberAttribute()] PRPAGeneralAdmin = 10296, [System.Runtime.Serialization.EnumMemberAttribute()] PRPAGuidance = 10297, [System.Runtime.Serialization.EnumMemberAttribute()] PRPAInternational = 10298, [System.Runtime.Serialization.EnumMemberAttribute()] PRPAParlAffairs = 10299, [System.Runtime.Serialization.EnumMemberAttribute()] PRPAPolicy = 10300, [System.Runtime.Serialization.EnumMemberAttribute()] PRPASubjectCategory = 10232, [System.Runtime.Serialization.EnumMemberAttribute()] PRPASubjectType = 10322, [System.Runtime.Serialization.EnumMemberAttribute()] PRPASupporttoOtherGroup = 10301, [System.Runtime.Serialization.EnumMemberAttribute()] PRPATask = 10302, [System.Runtime.Serialization.EnumMemberAttribute()] PRPAWatchingBrief = 10303, [System.Runtime.Serialization.EnumMemberAttribute()] Publisher = 7101, [System.Runtime.Serialization.EnumMemberAttribute()] PublisherAddress = 7102, [System.Runtime.Serialization.EnumMemberAttribute()] QuarterlyFiscalCalendar = 2002, [System.Runtime.Serialization.EnumMemberAttribute()] QuestionTemplate = 10304, [System.Runtime.Serialization.EnumMemberAttribute()] QuestionType = 10305, [System.Runtime.Serialization.EnumMemberAttribute()] Queue = 2020, [System.Runtime.Serialization.EnumMemberAttribute()] QueueItem = 2029, [System.Runtime.Serialization.EnumMemberAttribute()] QueueItemCount = 2023, [System.Runtime.Serialization.EnumMemberAttribute()] QueueMemberCount = 2024, [System.Runtime.Serialization.EnumMemberAttribute()] Recommendation = 10306, [System.Runtime.Serialization.EnumMemberAttribute()] RecordCreationandUpdateRule = 9300, [System.Runtime.Serialization.EnumMemberAttribute()] RecordCreationandUpdateRuleItem = 9301, [System.Runtime.Serialization.EnumMemberAttribute()] RecurrenceRule = 4250, [System.Runtime.Serialization.EnumMemberAttribute()] RecurringAppointment = 4251, [System.Runtime.Serialization.EnumMemberAttribute()] ReferenceDocument = 10307, [System.Runtime.Serialization.EnumMemberAttribute()] RelationshipAttribute = 9814, [System.Runtime.Serialization.EnumMemberAttribute()] RelationshipEntity = 9813, [System.Runtime.Serialization.EnumMemberAttribute()] RelationshipRole = 4500, [System.Runtime.Serialization.EnumMemberAttribute()] RelationshipRoleMap = 4501, [System.Runtime.Serialization.EnumMemberAttribute()] Reminder = 10308, [System.Runtime.Serialization.EnumMemberAttribute()] ReplicationBacklog = 1140, [System.Runtime.Serialization.EnumMemberAttribute()] Report = 9100, [System.Runtime.Serialization.EnumMemberAttribute()] ReportLink = 9104, [System.Runtime.Serialization.EnumMemberAttribute()] ReportRelatedCategory = 9102, [System.Runtime.Serialization.EnumMemberAttribute()] ReportRelatedEntity = 9101, [System.Runtime.Serialization.EnumMemberAttribute()] ReportVisibility = 9103, [System.Runtime.Serialization.EnumMemberAttribute()] RevokeInheritedAccessRecordsTracker = 10083, [System.Runtime.Serialization.EnumMemberAttribute()] RibbonClientMetadata = 4579, [System.Runtime.Serialization.EnumMemberAttribute()] RibbonCommand = 1116, [System.Runtime.Serialization.EnumMemberAttribute()] RibbonContextGroup = 1115, [System.Runtime.Serialization.EnumMemberAttribute()] RibbonDifference = 1130, [System.Runtime.Serialization.EnumMemberAttribute()] RibbonMetadataToProcess = 9880, [System.Runtime.Serialization.EnumMemberAttribute()] RibbonRule = 1117, [System.Runtime.Serialization.EnumMemberAttribute()] RibbonTabToCommandMapping = 1113, [System.Runtime.Serialization.EnumMemberAttribute()] RichTextAttachment = 10053, [System.Runtime.Serialization.EnumMemberAttribute()] RiskAppetite = 10309, [System.Runtime.Serialization.EnumMemberAttribute()] RiskAssessment = 10310, [System.Runtime.Serialization.EnumMemberAttribute()] RiskAssessmentCategory = 10311, [System.Runtime.Serialization.EnumMemberAttribute()] RiskAssessmentCategoryTemplate = 10312, [System.Runtime.Serialization.EnumMemberAttribute()] RiskAssessmentDefinition = 10313, [System.Runtime.Serialization.EnumMemberAttribute()] RiskAssessmentDefinitionTemplate = 10314, [System.Runtime.Serialization.EnumMemberAttribute()] RiskAssessmentFactorTemplate = 10315, [System.Runtime.Serialization.EnumMemberAttribute()] RiskAssessmentType = 10316, [System.Runtime.Serialization.EnumMemberAttribute()] RoleTemplate = 1037, [System.Runtime.Serialization.EnumMemberAttribute()] RollupField = 9604, [System.Runtime.Serialization.EnumMemberAttribute()] RollupJob = 9511, [System.Runtime.Serialization.EnumMemberAttribute()] RollupProperties = 9510, [System.Runtime.Serialization.EnumMemberAttribute()] RollupQuery = 9602, [System.Runtime.Serialization.EnumMemberAttribute()] RoutingRuleSet = 8181, [System.Runtime.Serialization.EnumMemberAttribute()] RuleItem = 8199, [System.Runtime.Serialization.EnumMemberAttribute()] RuntimeDependency = 7200, [System.Runtime.Serialization.EnumMemberAttribute()] SavedOrganizationInsightsConfiguration = 1309, [System.Runtime.Serialization.EnumMemberAttribute()] SavedView = 4230, [System.Runtime.Serialization.EnumMemberAttribute()] SCCProceduralSteps = 10317, [System.Runtime.Serialization.EnumMemberAttribute()] SdkMessage = 4606, [System.Runtime.Serialization.EnumMemberAttribute()] SdkMessageFilter = 4607, [System.Runtime.Serialization.EnumMemberAttribute()] SdkMessagePair = 4613, [System.Runtime.Serialization.EnumMemberAttribute()] SdkMessageProcessingStep = 4608, [System.Runtime.Serialization.EnumMemberAttribute()] SdkMessageProcessingStepImage = 4615, [System.Runtime.Serialization.EnumMemberAttribute()] SdkMessageProcessingStepSecureConfiguration = 4616, [System.Runtime.Serialization.EnumMemberAttribute()] SdkMessageRequest = 4609, [System.Runtime.Serialization.EnumMemberAttribute()] SdkMessageRequestField = 4614, [System.Runtime.Serialization.EnumMemberAttribute()] SdkMessageResponse = 4610, [System.Runtime.Serialization.EnumMemberAttribute()] SdkMessageResponseField = 4611, [System.Runtime.Serialization.EnumMemberAttribute()] Searchprovider = 10079, [System.Runtime.Serialization.EnumMemberAttribute()] SearchTelemetry = 10080, [System.Runtime.Serialization.EnumMemberAttribute()] SectorCategory = 10318, [System.Runtime.Serialization.EnumMemberAttribute()] SectorSubCategory = 10319, [System.Runtime.Serialization.EnumMemberAttribute()] SecurityRole = 1036, [System.Runtime.Serialization.EnumMemberAttribute()] SemiannualFiscalCalendar = 2001, [System.Runtime.Serialization.EnumMemberAttribute()] ServiceConfiguration = 10036, [System.Runtime.Serialization.EnumMemberAttribute()] ServiceEndpoint = 4618, [System.Runtime.Serialization.EnumMemberAttribute()] ServicePlan = 101, [System.Runtime.Serialization.EnumMemberAttribute()] ServicePlanMapping = 10153, [System.Runtime.Serialization.EnumMemberAttribute()] SettingDefinition = 10048, [System.Runtime.Serialization.EnumMemberAttribute()] SharePointData = 9509, [System.Runtime.Serialization.EnumMemberAttribute()] SharepointDocument = 9507, [System.Runtime.Serialization.EnumMemberAttribute()] SharePointSite = 9502, [System.Runtime.Serialization.EnumMemberAttribute()] SimilarityRule = 9951, [System.Runtime.Serialization.EnumMemberAttribute()] SiteMap = 4709, [System.Runtime.Serialization.EnumMemberAttribute()] SLA = 9750, [System.Runtime.Serialization.EnumMemberAttribute()] SLAItem = 9751, [System.Runtime.Serialization.EnumMemberAttribute()] SLAKPI = 10037, [System.Runtime.Serialization.EnumMemberAttribute()] SLAKPIInstance = 9752, [System.Runtime.Serialization.EnumMemberAttribute()] SocialActivity = 4216, [System.Runtime.Serialization.EnumMemberAttribute()] SocialInsightsConfiguration = 1300, [System.Runtime.Serialization.EnumMemberAttribute()] SocialProfile = 99, [System.Runtime.Serialization.EnumMemberAttribute()] Solution = 7100, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionComponent = 7103, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionComponentAttributeConfiguration = 10002, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionComponentBatchConfiguration = 10152, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionComponentConfiguration = 10033, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionComponentCountDataSource = 10163, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionComponentCountSummary = 10162, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionComponentDataSource = 10007, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionComponentDefinition = 7104, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionComponentRelationshipConfiguration = 10043, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionComponentSummary = 10006, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionHealthRule = 10030, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionHealthRuleArgument = 10031, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionHealthRuleSet = 10032, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionHistory = 10000, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionHistoryData = 9890, [System.Runtime.Serialization.EnumMemberAttribute()] SolutionHistoryDataSource = 10001, [System.Runtime.Serialization.EnumMemberAttribute()] StageSolutionUpload = 10034, [System.Runtime.Serialization.EnumMemberAttribute()] StatusMap = 1075, [System.Runtime.Serialization.EnumMemberAttribute()] StringMap = 1043, [System.Runtime.Serialization.EnumMemberAttribute()] Subject = 129, [System.Runtime.Serialization.EnumMemberAttribute()] SubjectCategory = 10321, [System.Runtime.Serialization.EnumMemberAttribute()] SubjectType = 10320, [System.Runtime.Serialization.EnumMemberAttribute()] Subscription = 29, [System.Runtime.Serialization.EnumMemberAttribute()] SubscriptionClients = 1072, [System.Runtime.Serialization.EnumMemberAttribute()] SubscriptionManuallyTrackedObject = 37, [System.Runtime.Serialization.EnumMemberAttribute()] SubscriptionStatisticOffline = 45, [System.Runtime.Serialization.EnumMemberAttribute()] SubscriptionStatisticOutlook = 46, [System.Runtime.Serialization.EnumMemberAttribute()] SubscriptionSyncEntryOffline = 47, [System.Runtime.Serialization.EnumMemberAttribute()] SubscriptionSyncEntryOutlook = 48, [System.Runtime.Serialization.EnumMemberAttribute()] SubscriptionSynchronizationInformation = 33, [System.Runtime.Serialization.EnumMemberAttribute()] SuggestionCardTemplate = 1190, [System.Runtime.Serialization.EnumMemberAttribute()] SyncAttributeMapping = 1401, [System.Runtime.Serialization.EnumMemberAttribute()] SyncAttributeMappingProfile = 1400, [System.Runtime.Serialization.EnumMemberAttribute()] SyncError = 9869, [System.Runtime.Serialization.EnumMemberAttribute()] SystemApplicationMetadata = 7000, [System.Runtime.Serialization.EnumMemberAttribute()] SystemChart = 1111, [System.Runtime.Serialization.EnumMemberAttribute()] SystemForm = 1030, [System.Runtime.Serialization.EnumMemberAttribute()] SystemJob = 4700, [System.Runtime.Serialization.EnumMemberAttribute()] SystemUserAuthorizationChangeTracker = 60, [System.Runtime.Serialization.EnumMemberAttribute()] SystemUserBusinessUnitEntityMap = 42, [System.Runtime.Serialization.EnumMemberAttribute()] SystemUserManagerMap = 51, [System.Runtime.Serialization.EnumMemberAttribute()] SystemUserPrincipal = 14, [System.Runtime.Serialization.EnumMemberAttribute()] TACase = 10324, [System.Runtime.Serialization.EnumMemberAttribute()] Task = 4212, [System.Runtime.Serialization.EnumMemberAttribute()] TaskTemplate = 10323, [System.Runtime.Serialization.EnumMemberAttribute()] Team = 9, [System.Runtime.Serialization.EnumMemberAttribute()] TeamMobileOfflineProfileMembership = 10097, [System.Runtime.Serialization.EnumMemberAttribute()] TeamProfiles = 1203, [System.Runtime.Serialization.EnumMemberAttribute()] TeamSyncAttributeMappingProfiles = 1403, [System.Runtime.Serialization.EnumMemberAttribute()] Teamtemplate = 92, [System.Runtime.Serialization.EnumMemberAttribute()] Territory = 2013, [System.Runtime.Serialization.EnumMemberAttribute()] TextAnalyticsEntityMapping = 9945, [System.Runtime.Serialization.EnumMemberAttribute()] Theme_10325 = 10325, [System.Runtime.Serialization.EnumMemberAttribute()] Theme_2015 = 2015, [System.Runtime.Serialization.EnumMemberAttribute()] TimeStampDateMapping = 9932, [System.Runtime.Serialization.EnumMemberAttribute()] TimeZoneDefinition = 4810, [System.Runtime.Serialization.EnumMemberAttribute()] TimeZoneLocalizedName = 4812, [System.Runtime.Serialization.EnumMemberAttribute()] TimeZoneRule = 4811, [System.Runtime.Serialization.EnumMemberAttribute()] Topic = 10326, [System.Runtime.Serialization.EnumMemberAttribute()] Tour = 10143, [System.Runtime.Serialization.EnumMemberAttribute()] Trace = 8050, [System.Runtime.Serialization.EnumMemberAttribute()] TraceAssociation = 8051, [System.Runtime.Serialization.EnumMemberAttribute()] TraceRegarding = 8052, [System.Runtime.Serialization.EnumMemberAttribute()] Trackinginformationfordeletedentities = 35, [System.Runtime.Serialization.EnumMemberAttribute()] TransformationMapping = 4426, [System.Runtime.Serialization.EnumMemberAttribute()] TransformationParameterMapping = 4427, [System.Runtime.Serialization.EnumMemberAttribute()] TranslationProcess = 951, [System.Runtime.Serialization.EnumMemberAttribute()] UnresolvedAddress = 2012, [System.Runtime.Serialization.EnumMemberAttribute()] UntrackedEmail = 4220, [System.Runtime.Serialization.EnumMemberAttribute()] User = 8, [System.Runtime.Serialization.EnumMemberAttribute()] UserApplicationMetadata = 7001, [System.Runtime.Serialization.EnumMemberAttribute()] UserChart = 1112, [System.Runtime.Serialization.EnumMemberAttribute()] UserDashboard = 1031, [System.Runtime.Serialization.EnumMemberAttribute()] UserEntityInstanceData = 2501, [System.Runtime.Serialization.EnumMemberAttribute()] UserEntityUISettings = 2500, [System.Runtime.Serialization.EnumMemberAttribute()] UserFiscalCalendar = 1086, [System.Runtime.Serialization.EnumMemberAttribute()] UserMapping = 2016, [System.Runtime.Serialization.EnumMemberAttribute()] UserMobileOfflineProfileMembership = 10098, [System.Runtime.Serialization.EnumMemberAttribute()] UserSearchFacet = 52, [System.Runtime.Serialization.EnumMemberAttribute()] UserSettings = 150, [System.Runtime.Serialization.EnumMemberAttribute()] View = 1039, [System.Runtime.Serialization.EnumMemberAttribute()] VirtualEntityDataProvider = 78, [System.Runtime.Serialization.EnumMemberAttribute()] VirtualEntityDataSource = 85, [System.Runtime.Serialization.EnumMemberAttribute()] VirtualEntityMetadata = 10111, [System.Runtime.Serialization.EnumMemberAttribute()] WebResource = 9333, [System.Runtime.Serialization.EnumMemberAttribute()] WebWizard = 4800, [System.Runtime.Serialization.EnumMemberAttribute()] WebWizardAccessPrivilege = 4803, [System.Runtime.Serialization.EnumMemberAttribute()] WizardPage = 4802, [System.Runtime.Serialization.EnumMemberAttribute()] WorkflowBinary = 10024, [System.Runtime.Serialization.EnumMemberAttribute()] WorkflowWaitSubscription = 4702, } }
28.750155
80
0.765192
[ "MIT" ]
opc-cpvp/OPC.PowerApps
src/Compliance.EarlyBound/OptionSets/DuplicateRuleMatchingEntityTypeCode.cs
46,489
C#
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace KeyVault.Acmebot.Models { public class CertificateItem { [JsonProperty("id")] public Uri Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("dnsNames")] public IReadOnlyList<string> DnsNames { get; set; } [JsonProperty("createdOn")] public DateTimeOffset CreatedOn { get; set; } [JsonProperty("expiresOn")] public DateTimeOffset ExpiresOn { get; set; } [JsonProperty("x509Thumbprint")] public string X509Thumbprint { get; set; } [JsonProperty("keyType")] public string KeyType { get; set; } [JsonProperty("keySize")] public int? KeySize { get; set; } [JsonProperty("keyCurveName")] public string KeyCurveName { get; set; } [JsonProperty("reuseKey")] public bool? ReuseKey { get; set; } } }
24.170732
59
0.601413
[ "Apache-2.0" ]
CMeeg/keyvault-acmebot
KeyVault.Acmebot/Models/CertificateItem.cs
993
C#
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// Static class that contains static glm functions /// </summary> public static partial class glm { /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public static decimal[,] Values(decmat2x5 m) => m.Values; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public static decimal[] Values1D(decmat2x5 m) => m.Values1D; /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public static IEnumerator<decimal> GetEnumerator(decmat2x5 m) => m.GetEnumerator(); } }
27.394737
91
0.638809
[ "MIT" ]
akriegman/GlmSharpN
GlmSharp/GlmSharp5/Mat2x5/decmat2x5.glm.cs
1,041
C#
/*generated*/ using System; using java.lang; using SimpleJSON; using de.yard.threed.platform; using java.util; using de.yard.threed.core.platform; namespace de.yard.threed.platform.unity { public class UnityJsonArray : UnityJsonValue , NativeJsonArray { public JSONArray value; public UnityJsonArray (JSONArray value) { this.value = value; a = true; } virtual public NativeJsonValue get (int index) { return UnityJsonObject.buildJsonValue (value [index]); } virtual public int size () { return value.Count; } } }
20.9375
70
0.591045
[ "MIT" ]
thomass171/tcp-22
platform-unity/PlatformUnity/Assets/scripts-platform/UnityJsonArray.cs
670
C#
// Asset Usage Detector - by Suleyman Yasir KULA (yasirkula@gmail.com) namespace AssetUsageDetectorNamespace { using Extras; using UnityEngine; using UnityEditor; using UnityEditor.Animations; using UnityEngine.SceneManagement; using UnityEditor.SceneManagement; using System.Collections; using System.Collections.Generic; using System.Reflection; using System; using System.IO; using UnityEngine.UI; using System.Text; #if UNITY_2017_1_OR_NEWER using UnityEngine.U2D; #if UNITY_2018_2_OR_NEWER using UnityEditor.U2D; #endif using UnityEngine.Playables; #endif #if UNITY_2017_2_OR_NEWER using UnityEngine.Tilemaps; #endif using Object = UnityEngine.Object; [Flags] public enum SceneSearchMode { None = 0, OpenScenes = 1, ScenesInBuildSettingsAll = 2, ScenesInBuildSettingsTickedOnly = 4, AllScenes = 8 }; public enum PathDrawingMode { Full = 0, ShortRelevantParts = 1, Shortest = 2 }; public class AssetUsageDetector { #region Helper Classes [Serializable] public class Parameters { public Object[] objectsToSearch = null; public SceneSearchMode searchInScenes = SceneSearchMode.AllScenes; public Object[] searchInScenesSubset = null; public bool searchInAssetsFolder = true; public Object[] searchInAssetsSubset = null; public Object[] excludedAssetsFromSearch = null; public bool dontSearchInSourceAssets = true; public Object[] excludedScenesFromSearch = null; public int searchDepthLimit = 4; public BindingFlags fieldModifiers = BindingFlags.Public | BindingFlags.NonPublic; public BindingFlags propertyModifiers = BindingFlags.Public | BindingFlags.NonPublic; public bool searchNonSerializableVariables = true; public bool lazySceneSearch = false; public bool noAssetDatabaseChanges = false; public bool showDetailedProgressBar = false; } private class CacheEntry { public enum Result { Unknown = 0, No = 1, Yes = 2 }; public string hash; public string[] dependencies; public long[] fileSizes; public bool verified; public Result searchResult; public CacheEntry( string path ) { Verify( path ); } public CacheEntry( string hash, string[] dependencies, long[] fileSizes ) { this.hash = hash; this.dependencies = dependencies; this.fileSizes = fileSizes; } public void Verify( string path ) { string hash = AssetDatabase.GetAssetDependencyHash( path ).ToString(); if( this.hash != hash ) { this.hash = hash; Refresh( path ); } verified = true; } public void Refresh( string path ) { dependencies = AssetDatabase.GetDependencies( path, false ); if( fileSizes == null || fileSizes.Length != dependencies.Length ) fileSizes = new long[dependencies.Length]; for( int i = 0; i < dependencies.Length; i++ ) { FileInfo assetFile = new FileInfo( dependencies[i] ); fileSizes[i] = assetFile.Exists ? assetFile.Length : 0L; } } } #endregion // A set that contains the searched asset(s) and their sub-assets (if any) private readonly HashSet<Object> objectsToSearchSet = new HashSet<Object>(); // Scene object(s) in objectsToSearchSet private readonly HashSet<Object> sceneObjectsToSearchSet = new HashSet<Object>(); // sceneObjectsToSearchSet's scene(s) private readonly HashSet<string> sceneObjectsToSearchScenesSet = new HashSet<string>(); // Project asset(s) in objectsToSearchSet private readonly HashSet<Object> assetsToSearchSet = new HashSet<Object>(); // assetsToSearchSet's path(s) private readonly HashSet<string> assetsToSearchPathsSet = new HashSet<string>(); // The root prefab objects in assetsToSearch that will be used to search for prefab references private readonly List<GameObject> assetsToSearchRootPrefabs = new List<GameObject>( 4 ); // Path(s) of the assets that should be excluded from the search private readonly HashSet<string> excludedAssetsPathsSet = new HashSet<string>(); // Results for the currently searched scene private SearchResultGroup currentSearchResultGroup; // An optimization to fetch & filter fields and properties of a class only once private readonly Dictionary<Type, VariableGetterHolder[]> typeToVariables = new Dictionary<Type, VariableGetterHolder[]>( 4096 ); // An optimization to search an object only once (key is a hash of the searched object) private readonly Dictionary<string, ReferenceNode> searchedObjects = new Dictionary<string, ReferenceNode>( 32768 ); // An optimization to fetch an animation clip's curve bindings only once private readonly Dictionary<AnimationClip, EditorCurveBinding[]> animationClipUniqueBindings = new Dictionary<AnimationClip, EditorCurveBinding[]>( 256 ); // An optimization to fetch the dependencies of an asset only once (key is the path of the asset) private Dictionary<string, CacheEntry> assetDependencyCache; private CacheEntry lastRefreshedCacheEntry; // Dictionary to quickly find the function to search a specific type with private Dictionary<Type, Func<Object, ReferenceNode>> typeToSearchFunction; // Stack of SearchObject function parameters to avoid infinite loops (which happens when same object is passed as parameter to function) private readonly List<object> callStack = new List<object>( 64 ); private bool searchPrefabConnections; private bool searchMonoBehavioursForScript; private bool searchRenderers; private bool searchMaterialsForShader; private bool searchMaterialsForTexture; private bool searchSerializableVariablesOnly; private bool prevSearchSerializableVariablesOnly; private int searchDepthLimit; // Depth limit for recursively searching variables of objects private Object currentSearchedObject; private int currentDepth; private bool dontSearchInSourceAssets; private bool searchingSourceAssets; private bool isInPlayMode; #if UNITY_2018_3_OR_NEWER private UnityEditor.Experimental.SceneManagement.PrefabStage openPrefabStage; private GameObject openPrefabStagePrefabAsset; #endif private BindingFlags fieldModifiers, propertyModifiers; private BindingFlags prevFieldModifiers, prevPropertyModifiers; private int searchedObjectsCount; // Number of searched objects private double searchStartTime; private readonly List<ReferenceNode> nodesPool = new List<ReferenceNode>( 32 ); private readonly List<VariableGetterHolder> validVariables = new List<VariableGetterHolder>( 32 ); private string CachePath { get { return Application.dataPath + "/../Library/AssetUsageDetector.cache"; } } // Path of the cache file // Search for references! public SearchResult Run( Parameters searchParameters ) { if( searchParameters == null ) { Debug.LogError( "searchParameters must not be null!" ); return new SearchResult( false, null, null, this, searchParameters ); } if( searchParameters.objectsToSearch == null ) { Debug.LogError( "objectsToSearch list is empty!" ); return new SearchResult( false, null, null, this, searchParameters ); } if( !EditorApplication.isPlaying && !Utilities.AreScenesSaved() ) { // Don't start the search if at least one scene is currently dirty (not saved) Debug.LogError( "Save open scenes first!" ); return new SearchResult( false, null, null, this, searchParameters ); } List<SearchResultGroup> searchResult = null; isInPlayMode = EditorApplication.isPlaying; #if UNITY_2018_3_OR_NEWER openPrefabStagePrefabAsset = null; string openPrefabStageAssetPath = null; openPrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage(); if( openPrefabStage != null ) { if( !openPrefabStage.stageHandle.IsValid() ) openPrefabStage = null; else { if( openPrefabStage.scene.isDirty ) { // Don't start the search if a prefab stage is currently open and dirty (not saved) Debug.LogError( "Save open prefabs first!" ); return new SearchResult( false, null, null, this, searchParameters ); } openPrefabStagePrefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( openPrefabStage.prefabAssetPath ); openPrefabStageAssetPath = openPrefabStage.prefabAssetPath; } } #endif // Get the scenes that are open right now SceneSetup[] initialSceneSetup = !isInPlayMode ? EditorSceneManager.GetSceneManagerSetup() : null; // Make sure the AssetDatabase is up-to-date AssetDatabase.SaveAssets(); try { currentDepth = 0; searchedObjectsCount = 0; searchStartTime = EditorApplication.timeSinceStartup; this.fieldModifiers = searchParameters.fieldModifiers | BindingFlags.Instance | BindingFlags.DeclaredOnly; this.propertyModifiers = searchParameters.propertyModifiers | BindingFlags.Instance | BindingFlags.DeclaredOnly; this.searchDepthLimit = searchParameters.searchDepthLimit; this.searchSerializableVariablesOnly = !searchParameters.searchNonSerializableVariables; this.dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets; // Initialize commonly used variables searchResult = new List<SearchResultGroup>(); // Overall search results if( prevFieldModifiers != fieldModifiers || prevPropertyModifiers != propertyModifiers || prevSearchSerializableVariablesOnly != searchSerializableVariablesOnly ) typeToVariables.Clear(); searchedObjects.Clear(); animationClipUniqueBindings.Clear(); callStack.Clear(); objectsToSearchSet.Clear(); sceneObjectsToSearchSet.Clear(); sceneObjectsToSearchScenesSet.Clear(); assetsToSearchSet.Clear(); assetsToSearchPathsSet.Clear(); assetsToSearchRootPrefabs.Clear(); excludedAssetsPathsSet.Clear(); if( assetDependencyCache == null ) { LoadCache(); searchStartTime = EditorApplication.timeSinceStartup; } else if( !searchParameters.noAssetDatabaseChanges ) { foreach( var cacheEntry in assetDependencyCache.Values ) cacheEntry.verified = false; } foreach( var cacheEntry in assetDependencyCache.Values ) cacheEntry.searchResult = CacheEntry.Result.Unknown; lastRefreshedCacheEntry = null; if( typeToSearchFunction == null ) { typeToSearchFunction = new Dictionary<Type, Func<Object, ReferenceNode>>() { { typeof( GameObject ), SearchGameObject }, { typeof( Material ), SearchMaterial }, { typeof( RuntimeAnimatorController ), SearchAnimatorController }, { typeof( AnimatorOverrideController ), SearchAnimatorController }, { typeof( AnimatorController ), SearchAnimatorController }, { typeof( AnimatorStateMachine ), SearchAnimatorStateMachine }, { typeof( AnimatorState ), SearchAnimatorState }, { typeof( AnimatorStateTransition ), SearchAnimatorStateTransition }, { typeof( BlendTree ), SearchBlendTree }, { typeof( AnimationClip ), SearchAnimationClip }, #if UNITY_2017_1_OR_NEWER { typeof( SpriteAtlas ), SearchSpriteAtlas }, #endif }; } prevFieldModifiers = fieldModifiers; prevPropertyModifiers = propertyModifiers; prevSearchSerializableVariablesOnly = searchSerializableVariablesOnly; searchPrefabConnections = false; searchMonoBehavioursForScript = false; searchRenderers = false; searchMaterialsForShader = false; searchMaterialsForTexture = false; // Store the searched objects(s) in HashSets HashSet<string> folderContentsSet = new HashSet<string>(); foreach( Object obj in searchParameters.objectsToSearch ) { if( obj == null || obj.Equals( null ) ) continue; if( obj.IsFolder() ) folderContentsSet.UnionWith( Utilities.EnumerateFolderContents( obj ) ); else AddSearchedObjectToFilteredSets( obj, true ); } foreach( string filePath in folderContentsSet ) { // Skip scene assets if( filePath.EndsWith( ".unity" ) ) continue; Object[] assets = AssetDatabase.LoadAllAssetsAtPath( filePath ); if( assets == null || assets.Length == 0 ) continue; for( int i = 0; i < assets.Length; i++ ) AddSearchedObjectToFilteredSets( assets[i], true ); } foreach( Object obj in objectsToSearchSet ) { if( obj is Texture ) { searchRenderers = true; searchMaterialsForTexture = true; } else if( obj is Material ) { searchRenderers = true; } else if( obj is MonoScript ) { searchMonoBehavioursForScript = true; } else if( obj is Shader ) { searchRenderers = true; searchMaterialsForShader = true; } else if( obj is GameObject ) { searchPrefabConnections = true; } } // Find the scenes to search for references HashSet<string> scenesToSearch = new HashSet<string>(); if( searchParameters.searchInScenesSubset != null ) { foreach( Object obj in searchParameters.searchInScenesSubset ) { if( obj == null || obj.Equals( null ) ) continue; if( !obj.IsAsset() ) continue; if( obj.IsFolder() ) { string[] folderContents = AssetDatabase.FindAssets( "t:SceneAsset", new string[] { AssetDatabase.GetAssetPath( obj ) } ); if( folderContents == null ) continue; for( int i = 0; i < folderContents.Length; i++ ) scenesToSearch.Add( AssetDatabase.GUIDToAssetPath( folderContents[i] ) ); } else if( obj is SceneAsset ) scenesToSearch.Add( AssetDatabase.GetAssetPath( obj ) ); } } else if( ( searchParameters.searchInScenes & SceneSearchMode.AllScenes ) == SceneSearchMode.AllScenes ) { // Get all scenes from the Assets folder string[] sceneGuids = AssetDatabase.FindAssets( "t:SceneAsset" ); for( int i = 0; i < sceneGuids.Length; i++ ) scenesToSearch.Add( AssetDatabase.GUIDToAssetPath( sceneGuids[i] ) ); } else { if( ( searchParameters.searchInScenes & SceneSearchMode.OpenScenes ) == SceneSearchMode.OpenScenes ) { // Get all open (and loaded) scenes for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ ) { Scene scene = EditorSceneManager.GetSceneAt( i ); if( scene.IsValid() ) scenesToSearch.Add( scene.path ); } } bool searchInScenesInBuildTickedAll = ( searchParameters.searchInScenes & SceneSearchMode.ScenesInBuildSettingsAll ) == SceneSearchMode.ScenesInBuildSettingsAll; if( searchInScenesInBuildTickedAll || ( searchParameters.searchInScenes & SceneSearchMode.ScenesInBuildSettingsTickedOnly ) == SceneSearchMode.ScenesInBuildSettingsTickedOnly ) { // Get all scenes in build settings EditorBuildSettingsScene[] scenesTemp = EditorBuildSettings.scenes; for( int i = 0; i < scenesTemp.Length; i++ ) { if( ( searchInScenesInBuildTickedAll || scenesTemp[i].enabled ) ) scenesToSearch.Add( scenesTemp[i].path ); } } } // In Play mode, only open scenes can be searched if( isInPlayMode ) { HashSet<string> openScenes = new HashSet<string>(); for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ ) { Scene scene = EditorSceneManager.GetSceneAt( i ); if( scene.IsValid() ) openScenes.Add( scene.path ); } scenesToSearch.RemoveWhere( ( path ) => { if( !openScenes.Contains( path ) ) { Debug.Log( "Can't search unloaded scenes while in play mode, skipped " + path ); return true; } return false; } ); } // Initialize the nodes of searched asset(s) foreach( Object obj in objectsToSearchSet ) searchedObjects.Add( obj.Hash(), PopReferenceNode( obj ) ); // Progressbar values int searchProgress = 0; int searchTotalProgress = scenesToSearch.Count; if( isInPlayMode && searchParameters.searchInScenes != SceneSearchMode.None ) searchTotalProgress++; // DontDestroyOnLoad scene // Don't search assets if searched object(s) are all scene objects as assets can't hold references to scene objects if( searchParameters.searchInAssetsFolder && assetsToSearchSet.Count > 0 ) { currentSearchResultGroup = new SearchResultGroup( "Project Window (Assets)", SearchResultGroup.GroupType.Assets ); // Get the paths of all assets that are to be searched IEnumerable<string> assetPaths; if( searchParameters.searchInAssetsSubset == null ) { string[] allAssetPaths = AssetDatabase.GetAllAssetPaths(); assetPaths = allAssetPaths; if( searchParameters.showDetailedProgressBar ) searchTotalProgress += allAssetPaths.Length; } else { folderContentsSet.Clear(); foreach( Object obj in searchParameters.searchInAssetsSubset ) { if( obj == null || obj.Equals( null ) ) continue; if( !obj.IsAsset() ) continue; if( obj.IsFolder() ) folderContentsSet.UnionWith( Utilities.EnumerateFolderContents( obj ) ); else folderContentsSet.Add( AssetDatabase.GetAssetPath( obj ) ); } assetPaths = folderContentsSet; if( searchParameters.showDetailedProgressBar ) searchTotalProgress += folderContentsSet.Count; } // Calculate the path(s) of the assets that won't be searched for references if( searchParameters.excludedAssetsFromSearch != null ) { foreach( Object obj in searchParameters.excludedAssetsFromSearch ) { if( obj == null || obj.Equals( null ) ) continue; if( !obj.IsAsset() ) continue; if( obj.IsFolder() ) excludedAssetsPathsSet.UnionWith( Utilities.EnumerateFolderContents( obj ) ); else excludedAssetsPathsSet.Add( AssetDatabase.GetAssetPath( obj ) ); } } if( EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Searching assets", 0f ) ) throw new Exception( "Search aborted" ); foreach( string path in assetPaths ) { if( searchParameters.showDetailedProgressBar && ++searchProgress % 30 == 1 && EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Searching assets", (float) searchProgress / searchTotalProgress ) ) throw new Exception( "Search aborted" ); if( excludedAssetsPathsSet.Contains( path ) ) continue; // If asset resides inside the Assets directory and is not a scene asset if( path.StartsWith( "Assets/" ) && !path.EndsWith( ".unity" ) ) { if( !AssetHasAnyReference( path ) ) continue; Object[] assets = AssetDatabase.LoadAllAssetsAtPath( path ); if( assets == null || assets.Length == 0 ) continue; for( int i = 0; i < assets.Length; i++ ) { // Components are already searched while searching the GameObject if( assets[i] is Component ) continue; BeginSearchObject( assets[i] ); } } } // If a reference is found in the Project view, save the results if( currentSearchResultGroup.NumberOfReferences > 0 ) searchResult.Add( currentSearchResultGroup ); } // Search non-serializable variables for references while searching a scene in play mode if( isInPlayMode ) searchSerializableVariablesOnly = false; if( scenesToSearch.Count > 0 ) { // Calculate the path(s) of the scenes that won't be searched for references HashSet<string> excludedScenesPathsSet = new HashSet<string>(); if( searchParameters.excludedScenesFromSearch != null ) { foreach( Object obj in searchParameters.excludedScenesFromSearch ) { if( obj == null || obj.Equals( null ) ) continue; if( !obj.IsAsset() ) continue; if( obj.IsFolder() ) { string[] folderContents = AssetDatabase.FindAssets( "t:SceneAsset", new string[] { AssetDatabase.GetAssetPath( obj ) } ); if( folderContents == null ) continue; for( int i = 0; i < folderContents.Length; i++ ) excludedScenesPathsSet.Add( AssetDatabase.GUIDToAssetPath( folderContents[i] ) ); } else if( obj is SceneAsset ) excludedScenesPathsSet.Add( AssetDatabase.GetAssetPath( obj ) ); } } foreach( string scenePath in scenesToSearch ) { if( EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Searching scene: " + scenePath, (float) ++searchProgress / searchTotalProgress ) ) throw new Exception( "Search aborted" ); // Search scene for references if( string.IsNullOrEmpty( scenePath ) ) continue; if( excludedScenesPathsSet.Contains( scenePath ) ) continue; SearchScene( scenePath, searchResult, searchParameters.lazySceneSearch, initialSceneSetup ); } } // Search through all the GameObjects under the DontDestroyOnLoad scene (if exists) if( isInPlayMode && searchParameters.searchInScenes != SceneSearchMode.None ) { if( searchParameters.showDetailedProgressBar && EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Searching scene: DontDestroyOnLoad", 1f ) ) throw new Exception( "Search aborted" ); currentSearchResultGroup = new SearchResultGroup( "DontDestroyOnLoad", SearchResultGroup.GroupType.DontDestroyOnLoad ); GameObject[] rootGameObjects = GetDontDestroyOnLoadObjects(); for( int i = 0; i < rootGameObjects.Length; i++ ) SearchGameObjectRecursively( rootGameObjects[i] ); if( currentSearchResultGroup.NumberOfReferences > 0 ) searchResult.Add( currentSearchResultGroup ); } // Searching source assets last prevents some references from being excluded due to callStack.ContainsFast if( !dontSearchInSourceAssets ) { searchingSourceAssets = true; foreach( Object obj in objectsToSearchSet ) { currentSearchedObject = obj; SearchObject( obj ); } searchingSourceAssets = false; } InitializeSearchResultNodes( searchResult ); // Log some c00l stuff to console Debug.Log( "Searched " + searchedObjectsCount + " objects in " + ( EditorApplication.timeSinceStartup - searchStartTime ).ToString( "F2" ) + " seconds" ); return new SearchResult( true, searchResult, initialSceneSetup, this, searchParameters ); } catch( Exception e ) { StringBuilder sb = new StringBuilder( objectsToSearchSet.Count * 50 + callStack.Count * 50 + 500 ); sb.AppendLine( "<b>AssetUsageDetector Error:</b>" ).AppendLine(); if( callStack.Count > 0 ) { sb.AppendLine( "Stack contents: " ); for( int i = callStack.Count - 1; i >= 0; i-- ) { sb.Append( i ).Append( ": " ); Object unityObject = callStack[i] as Object; if( unityObject ) sb.Append( unityObject.name ).Append( " (" ).Append( unityObject.GetType() ).AppendLine( ")" ); else if( callStack[i] != null ) sb.Append( callStack[i].GetType() ).AppendLine( " object" ); else sb.AppendLine( "<<destroyed>>" ); } sb.AppendLine(); } sb.AppendLine( "Searching references of: " ); foreach( Object obj in objectsToSearchSet ) { if( obj ) sb.Append( obj.name ).Append( " (" ).Append( obj.GetType() ).AppendLine( ")" ); } sb.AppendLine(); sb.Append( e ).AppendLine(); Debug.LogError( sb.ToString() ); try { InitializeSearchResultNodes( searchResult ); } catch { } return new SearchResult( false, searchResult, initialSceneSetup, this, searchParameters ); } finally { currentSearchResultGroup = null; currentSearchedObject = null; EditorUtility.ClearProgressBar(); #if UNITY_2018_3_OR_NEWER // If a prefab stage was open when the search was triggered, try reopening the prefab stage after the search is completed if( !string.IsNullOrEmpty( openPrefabStageAssetPath ) ) AssetDatabase.OpenAsset( AssetDatabase.LoadAssetAtPath<GameObject>( openPrefabStageAssetPath ) ); #endif } } private void InitializeSearchResultNodes( List<SearchResultGroup> searchResult ) { for( int i = 0; i < searchResult.Count; i++ ) searchResult[i].InitializeNodes( GetReferenceNode ); // If there are any empty groups after node initialization, remove those groups for( int i = searchResult.Count - 1; i >= 0; i-- ) { if( !searchResult[i].PendingSearch && searchResult[i].NumberOfReferences == 0 ) searchResult.RemoveAtFast( i ); } } // Checks if object is asset or scene object and adds it to the corresponding HashSet(s) private void AddSearchedObjectToFilteredSets( Object obj, bool expandGameObjects ) { if( obj == null || obj.Equals( null ) ) return; if( obj is SceneAsset ) return; objectsToSearchSet.Add( obj ); #if UNITY_2018_3_OR_NEWER // When searching for references of a prefab stage object, try adding its corresponding prefab asset to the searched assets, as well if( openPrefabStage != null && openPrefabStagePrefabAsset != null && obj is GameObject && openPrefabStage.IsPartOfPrefabContents( (GameObject) obj ) ) { GameObject prefabStageObjectSource = ( (GameObject) obj ).FollowSymmetricHierarchy( openPrefabStagePrefabAsset ); if( prefabStageObjectSource != null ) AddSearchedObjectToFilteredSets( prefabStageObjectSource, expandGameObjects ); } #endif bool isAsset = obj.IsAsset(); if( isAsset ) { assetsToSearchSet.Add( obj ); string assetPath = AssetDatabase.GetAssetPath( obj ); if( !string.IsNullOrEmpty( assetPath ) ) { assetsToSearchPathsSet.Add( assetPath ); if( dontSearchInSourceAssets && AssetDatabase.IsMainAsset( obj ) ) excludedAssetsPathsSet.Add( assetPath ); } GameObject go = null; if( obj is GameObject ) go = (GameObject) obj; else if( obj is Component ) go = ( (Component) obj ).gameObject; if( go != null ) { Transform transform = go.transform; bool shouldAddRootPrefabEntry = true; for( int i = assetsToSearchRootPrefabs.Count - 1; i >= 0; i-- ) { Transform rootTransform = assetsToSearchRootPrefabs[i].transform; if( transform.IsChildOf( rootTransform ) ) { shouldAddRootPrefabEntry = false; break; } if( rootTransform.IsChildOf( transform ) ) assetsToSearchRootPrefabs.RemoveAt( i ); } if( shouldAddRootPrefabEntry ) assetsToSearchRootPrefabs.Add( go ); } } else { sceneObjectsToSearchSet.Add( obj ); if( obj is GameObject ) sceneObjectsToSearchScenesSet.Add( ( (GameObject) obj ).scene.path ); else if( obj is Component ) sceneObjectsToSearchScenesSet.Add( ( (Component) obj ).gameObject.scene.path ); } if( expandGameObjects && obj is GameObject ) { // If searched asset is a GameObject, include its components in the search Component[] components = ( (GameObject) obj ).GetComponents<Component>(); for( int i = 0; i < components.Length; i++ ) { if( components[i] == null || components[i].Equals( null ) ) continue; objectsToSearchSet.Add( components[i] ); if( isAsset ) assetsToSearchSet.Add( components[i] ); else sceneObjectsToSearchSet.Add( components[i] ); } } else if( obj is Component ) { // Include searched components' GameObjects in the search, as well AddSearchedObjectToFilteredSets( ( (Component) obj ).gameObject, false ); } } // Search a scene for references private void SearchScene( string scenePath, List<SearchResultGroup> searchResult, bool lazySearch, SceneSetup[] initialSceneSetup ) { Scene scene = EditorSceneManager.GetSceneByPath( scenePath ); if( isInPlayMode && !scene.isLoaded ) return; bool canContainSceneObjectReference = scene.isLoaded && ( !EditorSceneManager.preventCrossSceneReferences || sceneObjectsToSearchScenesSet.Contains( scenePath ) ); if( !canContainSceneObjectReference ) { bool canContainAssetReference = assetsToSearchSet.Count > 0 && ( isInPlayMode || AssetHasAnyReference( scenePath ) ); if( !canContainAssetReference ) return; } if( !scene.isLoaded ) { if( lazySearch ) { searchResult.Add( new SearchResultGroup( scenePath, SearchResultGroup.GroupType.Scene, true, true ) ); return; } scene = EditorSceneManager.OpenScene( scenePath, OpenSceneMode.Additive ); } currentSearchResultGroup = new SearchResultGroup( scenePath, SearchResultGroup.GroupType.Scene ); // Search through all the GameObjects in the scene GameObject[] rootGameObjects = scene.GetRootGameObjects(); for( int i = 0; i < rootGameObjects.Length; i++ ) SearchGameObjectRecursively( rootGameObjects[i] ); // If no references are found in the scene and if the scene is not part of the initial scene setup, close it if( currentSearchResultGroup.NumberOfReferences == 0 ) { if( !isInPlayMode ) { bool sceneIsOneOfInitials = false; for( int i = 0; i < initialSceneSetup.Length; i++ ) { if( initialSceneSetup[i].path == scenePath ) { if( !initialSceneSetup[i].isLoaded ) EditorSceneManager.CloseScene( scene, false ); sceneIsOneOfInitials = true; break; } } if( !sceneIsOneOfInitials ) EditorSceneManager.CloseScene( scene, true ); } } else { // Some references are found in this scene, save the results searchResult.Add( currentSearchResultGroup ); } } // Search a GameObject and its children for references recursively private void SearchGameObjectRecursively( GameObject go ) { BeginSearchObject( go ); Transform tr = go.transform; for( int i = 0; i < tr.childCount; i++ ) SearchGameObjectRecursively( tr.GetChild( i ).gameObject ); } // Begin searching a root object (like a GameObject or an asset) private void BeginSearchObject( Object obj ) { if( obj is SceneAsset ) return; currentSearchedObject = obj; ReferenceNode searchResult = SearchObject( obj ); if( searchResult != null ) currentSearchResultGroup.AddReference( searchResult ); } // Search an object for references private ReferenceNode SearchObject( object obj ) { if( obj == null || obj.Equals( null ) ) return null; // Avoid recursion (which leads to stackoverflow exception) using a stack if( callStack.ContainsFast( obj ) ) return null; bool searchingSourceAsset = searchingSourceAssets && ReferenceEquals( currentSearchedObject, obj ); // Hashing does not work well with structs all the time, don't cache search results for structs string objHash = null; if( !( obj is ValueType ) ) { objHash = obj.Hash(); if( !searchingSourceAsset ) { // If object was searched before, return the cached result ReferenceNode cachedResult; if( searchedObjects.TryGetValue( objHash, out cachedResult ) ) return cachedResult; } } searchedObjectsCount++; ReferenceNode result; Object unityObject = obj as Object; if( unityObject != null ) { // If the Object is an asset, search it in detail only if its dependencies contain at least one of the searched asset(s) if( unityObject.IsAsset() && ( assetsToSearchSet.Count == 0 || !AssetHasAnyReference( AssetDatabase.GetAssetPath( unityObject ) ) ) ) { searchedObjects.Add( objHash, null ); return null; } callStack.Add( unityObject ); // Search the Object in detail Func<Object, ReferenceNode> func; if( typeToSearchFunction.TryGetValue( unityObject.GetType(), out func ) ) result = func( unityObject ); else if( unityObject is Component ) result = SearchComponent( unityObject ); else { result = PopReferenceNode( unityObject ); SearchWithSerializedObject( result ); } callStack.RemoveAt( callStack.Count - 1 ); } else { // Comply with the recursive search limit if( currentDepth >= searchDepthLimit ) return null; callStack.Add( obj ); currentDepth++; result = PopReferenceNode( obj ); SearchFieldsAndPropertiesOf( result ); currentDepth--; callStack.RemoveAt( callStack.Count - 1 ); } if( result != null && result.NumberOfOutgoingLinks == 0 ) { PoolReferenceNode( result ); result = null; } // Cache the search result if we are skimming through a class (not a struct; i.e. objHash != null) // and if the object is a UnityEngine.Object (if not, cache the result only if we have actually found something // or we are at the root of the search; i.e. currentDepth == 0) if( objHash != null && ( result != null || unityObject != null || currentDepth == 0 ) ) { if( !searchingSourceAsset ) searchedObjects.Add( objHash, result ); else if( result != null ) { result.CopyReferencesTo( searchedObjects[objHash] ); PoolReferenceNode( result ); } } return result; } private ReferenceNode SearchGameObject( Object unityObject ) { GameObject go = (GameObject) unityObject; ReferenceNode referenceNode = PopReferenceNode( go ); // Check if this GameObject's prefab is one of the selected assets if( searchPrefabConnections ) { #if UNITY_2018_3_OR_NEWER Object prefab = PrefabUtility.GetCorrespondingObjectFromSource( go ); #else Object prefab = PrefabUtility.GetPrefabParent( go ); #endif if( objectsToSearchSet.Contains( prefab ) && assetsToSearchRootPrefabs.ContainsFast( prefab as GameObject ) ) referenceNode.AddLinkTo( GetReferenceNode( prefab ), "Prefab object" ); } // Search through all the components of the object Component[] components = go.GetComponents<Component>(); for( int i = 0; i < components.Length; i++ ) referenceNode.AddLinkTo( SearchObject( components[i] ) ); return referenceNode; } private ReferenceNode SearchComponent( Object unityObject ) { Component component = (Component) unityObject; // Ignore Transform component (no object field to search for) if( component is Transform ) return null; ReferenceNode referenceNode = PopReferenceNode( component ); if( searchMonoBehavioursForScript && component is MonoBehaviour ) { // If a searched asset is script, check if this component is an instance of it MonoScript script = MonoScript.FromMonoBehaviour( (MonoBehaviour) component ); if( objectsToSearchSet.Contains( script ) ) referenceNode.AddLinkTo( GetReferenceNode( script ) ); } else if( searchRenderers && component is Renderer ) { // If an asset is a shader, texture or material, and this component is a Renderer, // search it for references Material[] materials = ( (Renderer) component ).sharedMaterials; for( int i = 0; i < materials.Length; i++ ) referenceNode.AddLinkTo( SearchObject( materials[i] ) ); } else if( component is Animation ) { // If this component is an Animation, search its animation clips for references foreach( AnimationState anim in (Animation) component ) referenceNode.AddLinkTo( SearchObject( anim.clip ) ); // Search the objects that are animated by this Animation component for references SearchAnimatedObjects( referenceNode ); } else if( component is Animator ) { // If this component is an Animator, search its animation clips for references (via AnimatorController) referenceNode.AddLinkTo( SearchObject( ( (Animator) component ).runtimeAnimatorController ) ); // Search the objects that are animated by this Animator component for references SearchAnimatedObjects( referenceNode ); } #if UNITY_2017_2_OR_NEWER else if( component is Tilemap ) { // If this component is a Tilemap, search its tiles for references TileBase[] tiles = new TileBase[( (Tilemap) component ).GetUsedTilesCount()]; ( (Tilemap) component ).GetUsedTilesNonAlloc( tiles ); if( tiles != null ) { for( int i = 0; i < tiles.Length; i++ ) referenceNode.AddLinkTo( SearchObject( tiles[i] ), "Tile" ); } } #endif #if UNITY_2017_1_OR_NEWER else if( component is PlayableDirector ) { // If this component is a PlayableDirectory, search its PlayableAsset's scene bindings for references PlayableAsset playableAsset = ( (PlayableDirector) component ).playableAsset; if( playableAsset != null && !playableAsset.Equals( null ) ) { foreach( PlayableBinding binding in playableAsset.outputs ) referenceNode.AddLinkTo( SearchObject( ( (PlayableDirector) component ).GetGenericBinding( binding.sourceObject ) ), "Binding: " + binding.streamName ); } } #endif SearchWithSerializedObject( referenceNode ); return referenceNode; } private ReferenceNode SearchMaterial( Object unityObject ) { Material material = (Material) unityObject; ReferenceNode referenceNode = PopReferenceNode( material ); if( searchMaterialsForShader && objectsToSearchSet.Contains( material.shader ) ) referenceNode.AddLinkTo( GetReferenceNode( material.shader ), "Shader" ); if( searchMaterialsForTexture ) { // Search through all the textures attached to this material // Credit: http://answers.unity3d.com/answers/1116025/view.html Shader shader = material.shader; int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader ); for( int i = 0; i < shaderPropertyCount; i++ ) { if( ShaderUtil.GetPropertyType( shader, i ) == ShaderUtil.ShaderPropertyType.TexEnv ) { string propertyName = ShaderUtil.GetPropertyName( shader, i ); Texture assignedTexture = material.GetTexture( propertyName ); if( objectsToSearchSet.Contains( assignedTexture ) ) referenceNode.AddLinkTo( GetReferenceNode( assignedTexture ), "Shader property: " + propertyName ); } } } return referenceNode; } private ReferenceNode SearchAnimatorController( Object unityObject ) { RuntimeAnimatorController controller = (RuntimeAnimatorController) unityObject; ReferenceNode referenceNode = PopReferenceNode( controller ); if( controller is AnimatorController ) { AnimatorControllerLayer[] layers = ( (AnimatorController) controller ).layers; for( int i = 0; i < layers.Length; i++ ) { if( objectsToSearchSet.Contains( layers[i].avatarMask ) ) referenceNode.AddLinkTo( GetReferenceNode( layers[i].avatarMask ), layers[i].name + " Mask" ); referenceNode.AddLinkTo( SearchObject( layers[i].stateMachine ) ); } } else { AnimationClip[] animClips = controller.animationClips; for( int i = 0; i < animClips.Length; i++ ) referenceNode.AddLinkTo( SearchObject( animClips[i] ) ); } return referenceNode; } private ReferenceNode SearchAnimatorStateMachine( Object unityObject ) { AnimatorStateMachine animatorStateMachine = (AnimatorStateMachine) unityObject; ReferenceNode referenceNode = PopReferenceNode( animatorStateMachine ); ChildAnimatorStateMachine[] stateMachines = animatorStateMachine.stateMachines; for( int i = 0; i < stateMachines.Length; i++ ) referenceNode.AddLinkTo( SearchObject( stateMachines[i].stateMachine ), "Child State Machine" ); ChildAnimatorState[] states = animatorStateMachine.states; for( int i = 0; i < states.Length; i++ ) referenceNode.AddLinkTo( SearchObject( states[i].state ) ); if( searchMonoBehavioursForScript ) { StateMachineBehaviour[] behaviours = animatorStateMachine.behaviours; for( int i = 0; i < behaviours.Length; i++ ) { MonoScript script = MonoScript.FromScriptableObject( behaviours[i] ); if( objectsToSearchSet.Contains( script ) ) referenceNode.AddLinkTo( GetReferenceNode( script ) ); } } return referenceNode; } private ReferenceNode SearchAnimatorState( Object unityObject ) { AnimatorState animatorState = (AnimatorState) unityObject; ReferenceNode referenceNode = PopReferenceNode( animatorState ); referenceNode.AddLinkTo( SearchObject( animatorState.motion ), "Motion" ); if( searchMonoBehavioursForScript ) { StateMachineBehaviour[] behaviours = animatorState.behaviours; for( int i = 0; i < behaviours.Length; i++ ) { MonoScript script = MonoScript.FromScriptableObject( behaviours[i] ); if( objectsToSearchSet.Contains( script ) ) referenceNode.AddLinkTo( GetReferenceNode( script ) ); } } return referenceNode; } private ReferenceNode SearchAnimatorStateTransition( Object unityObject ) { // Don't search AnimatorStateTransition objects, it will just return duplicate results of SearchAnimatorStateMachine return PopReferenceNode( unityObject ); } private ReferenceNode SearchBlendTree( Object unityObject ) { BlendTree blendTree = (BlendTree) unityObject; ReferenceNode referenceNode = PopReferenceNode( blendTree ); ChildMotion[] children = blendTree.children; for( int i = 0; i < children.Length; i++ ) referenceNode.AddLinkTo( SearchObject( children[i].motion ), "Motion" ); return referenceNode; } private ReferenceNode SearchAnimationClip( Object unityObject ) { AnimationClip clip = (AnimationClip) unityObject; ReferenceNode referenceNode = PopReferenceNode( clip ); // Get all curves from animation clip EditorCurveBinding[] objectCurves = AnimationUtility.GetObjectReferenceCurveBindings( clip ); for( int i = 0; i < objectCurves.Length; i++ ) { // Search through all the keyframes in this curve ObjectReferenceKeyframe[] keyframes = AnimationUtility.GetObjectReferenceCurve( clip, objectCurves[i] ); for( int j = 0; j < keyframes.Length; j++ ) referenceNode.AddLinkTo( SearchObject( keyframes[j].value ), "Keyframe: " + keyframes[j].time ); } // Get all events from animation clip AnimationEvent[] events = AnimationUtility.GetAnimationEvents( clip ); for( int i = 0; i < events.Length; i++ ) referenceNode.AddLinkTo( SearchObject( events[i].objectReferenceParameter ), "AnimationEvent: " + events[i].time ); return referenceNode; } #if UNITY_2017_1_OR_NEWER private ReferenceNode SearchSpriteAtlas( Object unityObject ) { SpriteAtlas spriteAtlas = (SpriteAtlas) unityObject; ReferenceNode referenceNode = PopReferenceNode( spriteAtlas ); SerializedObject spriteAtlasSO = new SerializedObject( spriteAtlas ); if( spriteAtlas.isVariant ) { Object masterAtlas = spriteAtlasSO.FindProperty( "m_MasterAtlas" ).objectReferenceValue; if( objectsToSearchSet.Contains( masterAtlas ) ) referenceNode.AddLinkTo( SearchObject( masterAtlas ), "Master Atlas" ); } #if UNITY_2018_2_OR_NEWER Object[] packables = spriteAtlas.GetPackables(); if( packables != null ) { for( int i = 0; i < packables.Length; i++ ) referenceNode.AddLinkTo( SearchObject( packables[i] ), "Packed Texture" ); } #else SerializedProperty packables = spriteAtlasSO.FindProperty( "m_EditorData.packables" ); if( packables != null ) { for( int i = 0, length = packables.arraySize; i < length; i++ ) referenceNode.AddLinkTo( SearchObject( packables.GetArrayElementAtIndex( i ).objectReferenceValue ), "Packed Texture" ); } #endif return referenceNode; } #endif // Find references from an Animation/Animator component to the objects that it animates private void SearchAnimatedObjects( ReferenceNode referenceNode ) { GameObject root = ( (Component) referenceNode.nodeObject ).gameObject; AnimationClip[] clips = AnimationUtility.GetAnimationClips( root ); for( int i = 0; i < clips.Length; i++ ) { AnimationClip clip = clips[i]; bool isClipUnique = true; for( int j = i - 1; j >= 0; j-- ) { if( clips[j] == clip ) { isClipUnique = false; break; } } if( !isClipUnique ) continue; EditorCurveBinding[] uniqueBindings; if( !animationClipUniqueBindings.TryGetValue( clip, out uniqueBindings ) ) { // Calculate all the "unique" paths that the animation clip's curves have // Both float curves (GetCurveBindings) and object reference curves (GetObjectReferenceCurveBindings) are checked List<EditorCurveBinding> _uniqueBindings = new List<EditorCurveBinding>( 2 ); EditorCurveBinding[] bindings = AnimationUtility.GetCurveBindings( clip ); for( int j = 0; j < bindings.Length; j++ ) { string bindingPath = bindings[j].path; if( string.IsNullOrEmpty( bindingPath ) ) // Ignore the root animated object continue; bool isBindingUnique = true; for( int k = _uniqueBindings.Count - 1; k >= 0; k-- ) { if( bindingPath == _uniqueBindings[k].path ) { isBindingUnique = false; break; } } if( isBindingUnique ) _uniqueBindings.Add( bindings[j] ); } bindings = AnimationUtility.GetObjectReferenceCurveBindings( clip ); for( int j = 0; j < bindings.Length; j++ ) { string bindingPath = bindings[j].path; if( string.IsNullOrEmpty( bindingPath ) ) // Ignore the root animated object continue; bool isBindingUnique = true; for( int k = _uniqueBindings.Count - 1; k >= 0; k-- ) { if( bindingPath == _uniqueBindings[k].path ) { isBindingUnique = false; break; } } if( isBindingUnique ) _uniqueBindings.Add( bindings[j] ); } uniqueBindings = _uniqueBindings.ToArray(); animationClipUniqueBindings[clip] = uniqueBindings; } string clipName = clip.name; for( int j = 0; j < uniqueBindings.Length; j++ ) referenceNode.AddLinkTo( SearchObject( AnimationUtility.GetAnimatedObject( root, uniqueBindings[j] ) ), "Animated via clip: " + clipName ); } } // Search through field and properties of an object for references with SerializedObject private void SearchWithSerializedObject( ReferenceNode referenceNode ) { if( !isInPlayMode || referenceNode.nodeObject.IsAsset() ) { SerializedObject so = new SerializedObject( (Object) referenceNode.nodeObject ); SerializedProperty iterator = so.GetIterator(); if( iterator.NextVisible( true ) ) { bool enterChildren; do { ReferenceNode searchResult; switch( iterator.propertyType ) { case SerializedPropertyType.ObjectReference: searchResult = SearchObject( iterator.objectReferenceValue ); enterChildren = false; break; case SerializedPropertyType.ExposedReference: searchResult = SearchObject( iterator.exposedReferenceValue ); enterChildren = false; break; case SerializedPropertyType.Generic: searchResult = null; enterChildren = true; break; default: searchResult = null; enterChildren = false; break; } if( searchResult != null && searchResult != referenceNode ) { string propertyPath = iterator.propertyPath; // m_RD.texture is a redundant reference that shows up when searching sprites if( !propertyPath.EndsWith( "m_RD.texture", StringComparison.Ordinal ) ) referenceNode.AddLinkTo( searchResult, "Variable: " + propertyPath ); } } while( iterator.NextVisible( enterChildren ) ); return; } } // Use reflection algorithm as fallback SearchFieldsAndPropertiesOf( referenceNode ); } // Search through field and properties of an object for references private void SearchFieldsAndPropertiesOf( ReferenceNode referenceNode ) { // Get filtered variables for this object VariableGetterHolder[] variables = GetFilteredVariablesForType( referenceNode.nodeObject.GetType() ); for( int i = 0; i < variables.Length; i++ ) { // When possible, don't search non-serializable variables if( searchSerializableVariablesOnly && !variables[i].isSerializable ) continue; try { object variableValue = variables[i].Get( referenceNode.nodeObject ); if( variableValue == null ) continue; // Values stored inside ICollection objects are searched using IEnumerable, // no need to have duplicate search entries if( !( variableValue is ICollection ) ) { ReferenceNode searchResult = SearchObject( variableValue ); if( searchResult != null && searchResult != referenceNode ) referenceNode.AddLinkTo( searchResult, ( variables[i].isProperty ? "Property: " : "Variable: " ) + variables[i].name ); } if( variableValue is IEnumerable && !( variableValue is Transform ) ) { // If the field is IEnumerable (possibly an array or collection), search through members of it // Note that Transform IEnumerable (children of the transform) is not iterated int index = 0; foreach( object element in (IEnumerable) variableValue ) { ReferenceNode searchResult = SearchObject( element ); if( searchResult != null && searchResult != referenceNode ) referenceNode.AddLinkTo( searchResult, string.Concat( variables[i].isProperty ? "Property: " : "Variable: ", variables[i].name, "[", index + "]" ) ); index++; } } } catch( UnassignedReferenceException ) { } catch( MissingReferenceException ) { } catch( MissingComponentException ) { } catch( NotImplementedException ) { } } } // Get filtered variables for a type private VariableGetterHolder[] GetFilteredVariablesForType( Type type ) { VariableGetterHolder[] result; if( typeToVariables.TryGetValue( type, out result ) ) return result; // This is the first time this type of object is seen, filter and cache its variables // Variable filtering process: // 1- skip Obsolete variables // 2- skip primitive types, enums and strings // 3- skip common Unity types that can't hold any references (e.g. Vector3, Rect, Color, Quaternion) // // P.S. IsIgnoredUnityType() extension function handles steps 2) and 3) validVariables.Clear(); // Filter the fields if( fieldModifiers != ( BindingFlags.Instance | BindingFlags.DeclaredOnly ) ) { Type currType = type; while( currType != typeof( object ) ) { FieldInfo[] fields = currType.GetFields( fieldModifiers ); for( int i = 0; i < fields.Length; i++ ) { FieldInfo field = fields[i]; // Skip obsolete fields if( Attribute.IsDefined( field, typeof( ObsoleteAttribute ) ) ) continue; // Skip primitive types if( field.FieldType.IsIgnoredUnityType() ) continue; // Additional filtering for fields: // 1- Ignore "m_RectTransform", "m_CanvasRenderer" and "m_Canvas" fields of Graphic components string fieldName = field.Name; if( typeof( Graphic ).IsAssignableFrom( currType ) && ( fieldName == "m_RectTransform" || fieldName == "m_CanvasRenderer" || fieldName == "m_Canvas" ) ) continue; VariableGetVal getter = field.CreateGetter( type ); if( getter != null ) validVariables.Add( new VariableGetterHolder( field, getter, searchSerializableVariablesOnly ? field.IsSerializable() : true ) ); } currType = currType.BaseType; } } if( propertyModifiers != ( BindingFlags.Instance | BindingFlags.DeclaredOnly ) ) { Type currType = type; while( currType != typeof( object ) ) { PropertyInfo[] properties = currType.GetProperties( propertyModifiers ); for( int i = 0; i < properties.Length; i++ ) { PropertyInfo property = properties[i]; // Skip obsolete properties if( Attribute.IsDefined( property, typeof( ObsoleteAttribute ) ) ) continue; // Skip primitive types if( property.PropertyType.IsIgnoredUnityType() ) continue; // Skip properties without a getter function MethodInfo propertyGetter = property.GetGetMethod( true ); if( propertyGetter == null ) continue; // Skip indexer properties if( property.GetIndexParameters().Length > 0 ) continue; // No need to check properties with 'override' keyword if( propertyGetter.GetBaseDefinition().DeclaringType != propertyGetter.DeclaringType ) continue; // Additional filtering for properties: // 1- Ignore "gameObject", "transform", "rectTransform" and "attachedRigidbody" properties of Component's to get more useful results // 2- Ignore "canvasRenderer" and "canvas" properties of Graphic components // 3 & 4- Prevent accessing properties of Unity that instantiate an existing resource (causing memory leak) string propertyName = property.Name; if( typeof( Component ).IsAssignableFrom( currType ) && ( propertyName == "gameObject" || propertyName == "transform" || propertyName == "attachedRigidbody" || propertyName == "rectTransform" ) ) continue; else if( typeof( Graphic ).IsAssignableFrom( currType ) && ( propertyName == "canvasRenderer" || propertyName == "canvas" ) ) continue; else if( typeof( MeshFilter ).IsAssignableFrom( currType ) && propertyName == "mesh" ) continue; else if( typeof( Renderer ).IsAssignableFrom( currType ) && ( propertyName == "sharedMaterial" || propertyName == "sharedMaterials" ) ) continue; else if( ( propertyName == "material" || propertyName == "materials" ) && ( typeof( Renderer ).IsAssignableFrom( currType ) || typeof( Collider ).IsAssignableFrom( currType ) || #if !UNITY_2019_3_OR_NEWER #pragma warning disable 0618 typeof( GUIText ).IsAssignableFrom( currType ) || #pragma warning restore 0618 #endif typeof( Collider2D ).IsAssignableFrom( currType ) ) ) continue; else { VariableGetVal getter = property.CreateGetter(); if( getter != null ) validVariables.Add( new VariableGetterHolder( property, getter, searchSerializableVariablesOnly ? property.IsSerializable() : true ) ); } } currType = currType.BaseType; } } result = validVariables.ToArray(); // Cache the filtered fields typeToVariables.Add( type, result ); return result; } // Check if the asset at specified path depends on any of the references private bool AssetHasAnyReference( string assetPath ) { // "Find references of" assets can contain internal references if( assetsToSearchPathsSet.Contains( assetPath ) ) return true; CacheEntry cacheEntry; if( !assetDependencyCache.TryGetValue( assetPath, out cacheEntry ) ) { cacheEntry = new CacheEntry( assetPath ); assetDependencyCache[assetPath] = cacheEntry; } else if( !cacheEntry.verified ) cacheEntry.Verify( assetPath ); if( cacheEntry.searchResult != CacheEntry.Result.Unknown ) return cacheEntry.searchResult == CacheEntry.Result.Yes; cacheEntry.searchResult = CacheEntry.Result.No; string[] dependencies = cacheEntry.dependencies; long[] fileSizes = cacheEntry.fileSizes; for( int i = 0; i < dependencies.Length; i++ ) { // If a dependency was renamed (which doesn't affect the verified hash, unfortunately), // force refresh the asset's dependencies and search it again if( !Directory.Exists( dependencies[i] ) ) // Calling FileInfo.Length on a directory throws FileNotFoundException { FileInfo assetFile = new FileInfo( dependencies[i] ); if( !assetFile.Exists || assetFile.Length != fileSizes[i] ) { // Although not reproduced, it is reported that this section caused StackOverflowException due to infinite loop, // if that happens, log useful information to help reproduce the issue if( lastRefreshedCacheEntry == cacheEntry ) { StringBuilder sb = new StringBuilder( 1000 ); sb.AppendLine( "<b>Infinite loop while refreshing a cache entry, please report it to the author.</b>" ).AppendLine(); sb.Append( "Asset path: " ).AppendLine( assetPath ); for( int j = 0; j < 2; j++ ) { if( j == 1 ) { cacheEntry.Refresh( assetPath ); dependencies = cacheEntry.dependencies; fileSizes = cacheEntry.fileSizes; } sb.AppendLine().AppendLine( j == 0 ? "Old Dependencies:" : "New Dependencies" ); for( int k = 0; k < dependencies.Length; k++ ) { sb.Append( "- " ).Append( dependencies[k] ); if( Directory.Exists( dependencies[k] ) ) { sb.Append( " (Dir)" ); if( fileSizes[k] != 0L ) sb.Append( " WasCachedAsFile: " ).Append( fileSizes[k] ); } else { assetFile = new FileInfo( dependencies[k] ); sb.Append( " (File) " ).Append( "CachedSize: " ).Append( fileSizes[k] ); if( assetFile.Exists ) sb.Append( " RealSize: " ).Append( assetFile.Length ); else sb.Append( " NoLongerExists" ); } sb.AppendLine(); } } Debug.LogError( sb.ToString() ); return false; } cacheEntry.Refresh( assetPath ); cacheEntry.searchResult = CacheEntry.Result.Unknown; lastRefreshedCacheEntry = cacheEntry; return AssetHasAnyReference( assetPath ); } } if( assetsToSearchPathsSet.Contains( dependencies[i] ) ) { cacheEntry.searchResult = CacheEntry.Result.Yes; return true; } } for( int i = 0; i < dependencies.Length; i++ ) { if( AssetHasAnyReference( dependencies[i] ) ) { cacheEntry.searchResult = CacheEntry.Result.Yes; return true; } } return false; } // Get reference node for object private ReferenceNode GetReferenceNode( object nodeObject ) { ReferenceNode result; string hash = nodeObject.Hash(); if( !searchedObjects.TryGetValue( hash, out result ) || result == null ) { result = PopReferenceNode( nodeObject ); searchedObjects[hash] = result; } return result; } // Fetch a reference node from pool private ReferenceNode PopReferenceNode( object nodeObject ) { ReferenceNode node; if( nodesPool.Count == 0 ) node = new ReferenceNode(); else { int index = nodesPool.Count - 1; node = nodesPool[index]; nodesPool.RemoveAt( index ); } node.nodeObject = nodeObject; return node; } // Pool a reference node private void PoolReferenceNode( ReferenceNode node ) { node.Clear(); nodesPool.Add( node ); } // Retrieve the game objects listed under the DontDestroyOnLoad scene private GameObject[] GetDontDestroyOnLoadObjects() { GameObject temp = null; try { temp = new GameObject(); Object.DontDestroyOnLoad( temp ); Scene dontDestroyOnLoad = temp.scene; Object.DestroyImmediate( temp ); temp = null; return dontDestroyOnLoad.GetRootGameObjects(); } finally { if( temp != null ) Object.DestroyImmediate( temp ); } } public void SaveCache() { if( assetDependencyCache == null ) return; try { using( FileStream stream = new FileStream( CachePath, FileMode.Create ) ) using( BinaryWriter writer = new BinaryWriter( stream ) ) { writer.Write( assetDependencyCache.Count ); foreach( var keyValuePair in assetDependencyCache ) { CacheEntry cacheEntry = keyValuePair.Value; string[] dependencies = cacheEntry.dependencies; long[] fileSizes = cacheEntry.fileSizes; writer.Write( keyValuePair.Key ); writer.Write( cacheEntry.hash ); writer.Write( dependencies.Length ); for( int i = 0; i < dependencies.Length; i++ ) { writer.Write( dependencies[i] ); writer.Write( fileSizes[i] ); } } } } catch( Exception e ) { Debug.LogException( e ); } } private void LoadCache() { if( File.Exists( CachePath ) ) { using( FileStream stream = new FileStream( CachePath, FileMode.Open, FileAccess.Read ) ) using( BinaryReader reader = new BinaryReader( stream ) ) { try { int cacheSize = reader.ReadInt32(); assetDependencyCache = new Dictionary<string, CacheEntry>( cacheSize ); for( int i = 0; i < cacheSize; i++ ) { string assetPath = reader.ReadString(); string hash = reader.ReadString(); int dependenciesLength = reader.ReadInt32(); string[] dependencies = new string[dependenciesLength]; long[] fileSizes = new long[dependenciesLength]; for( int j = 0; j < dependenciesLength; j++ ) { dependencies[j] = reader.ReadString(); fileSizes[j] = reader.ReadInt64(); } assetDependencyCache[assetPath] = new CacheEntry( hash, dependencies, fileSizes ); } } catch( Exception e ) { assetDependencyCache = null; Debug.LogWarning( "Couldn't load cache (probably cache format has changed in an update), will regenerate cache.\n" + e.ToString() ); } } } // Generate cache for all assets for the first time if( assetDependencyCache == null ) { assetDependencyCache = new Dictionary<string, CacheEntry>( 1024 * 8 ); string[] allAssets = AssetDatabase.GetAllAssetPaths(); if( allAssets.Length > 0 ) { double startTime = EditorApplication.timeSinceStartup; try { for( int i = 0; i < allAssets.Length; i++ ) { if( i % 30 == 0 && EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Generating cache for the first time (optional)", (float) i / allAssets.Length ) ) { EditorUtility.ClearProgressBar(); Debug.LogWarning( "Initial cache generation cancelled, cache will be generated on the fly as more and more assets are searched." ); break; } AssetHasAnyReference( allAssets[i] ); } EditorUtility.ClearProgressBar(); Debug.Log( "Cache generated in " + ( EditorApplication.timeSinceStartup - startTime ).ToString( "F2" ) + " seconds" ); Debug.Log( "You can always reset the cache by deleting " + Path.GetFullPath( CachePath ) ); SaveCache(); } catch( Exception e ) { EditorUtility.ClearProgressBar(); Debug.LogException( e ); } } } } } }
33.904788
214
0.681804
[ "MIT" ]
FWCorey/UnityAssetUsageDetector
Plugins/AssetUsageDetector/Editor/AssetUsageDetector.cs
62,317
C#
using TestWrapper.Workers; using Unity.Burst; using Unity.Collections; namespace TestCase.Basic.Division.Simple.Optimization { [BurstCompile] public struct SimpleDivisionOptimizationLongJob : IJobExt<NativeArray<long>, NativeArray<long>, NativeArray<long>> { [ReadOnly] private NativeArray<long> _data1; [ReadOnly] private NativeArray<long> _data2; [WriteOnly] private NativeArray<long> _data3; public int DataSize { get; set; } public NativeArray<long> Data1 { get => _data1; set => _data1 = value; } public NativeArray<long> Data2 { get => _data2; set => _data2 = value; } public NativeArray<long> Data3 { get => _data3; set => _data3 = value; } public void Execute() { for (int i = 0; i < DataSize; i++) { _data3[i] = _data1[i] / _data2[i]; } } public void CustomSetUp() { } public void CustomCleanUp() { } } }
22.76
118
0.522847
[ "MIT" ]
ErikMoczi/Unity.TestRunner.Jobs
Assets/TestCase/Basic/Division/Simple/Optimization/SimpleAdditionOptimizationLongJob.cs
1,140
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace SistemasDeFilmes { /// <summary> /// Interação lógica para App.xaml /// </summary> public partial class App : Application { } }
18.333333
42
0.709091
[ "MIT" ]
Brunobagesteiro/Aula70483
SistemasDeFilmes/SistemasDeFilmes/App.xaml.cs
335
C#
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CarrotCake.CMS.Plugins.CalendarModule.Code { using System.Data.Linq; using System.Data.Linq.Mapping; using System.Data; using System.Collections.Generic; using System.Reflection; using System.Linq; using System.Linq.Expressions; using System.ComponentModel; using System; [global::System.Data.Linq.Mapping.DatabaseAttribute(Name="CarrotCakeMVC")] public partial class dbCalendarDataContext : System.Data.Linq.DataContext { private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource(); #region Extensibility Method Definitions partial void OnCreated(); partial void InserttblCalendar(tblCalendar instance); partial void UpdatetblCalendar(tblCalendar instance); partial void DeletetblCalendar(tblCalendar instance); #endregion public dbCalendarDataContext() : base(global::System.Configuration.ConfigurationManager.ConnectionStrings["CarrotwareCMSConnectionString"].ConnectionString, mappingSource) { OnCreated(); } public dbCalendarDataContext(string connection) : base(connection, mappingSource) { OnCreated(); } public dbCalendarDataContext(System.Data.IDbConnection connection) : base(connection, mappingSource) { OnCreated(); } public dbCalendarDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : base(connection, mappingSource) { OnCreated(); } public dbCalendarDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : base(connection, mappingSource) { OnCreated(); } public System.Data.Linq.Table<tblCalendar> tblCalendars { get { return this.GetTable<tblCalendar>(); } } } [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.tblCalendar")] public partial class tblCalendar : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private System.Guid _CalendarID; private System.Nullable<System.DateTime> _EventDate; private string _EventTitle; private string _EventDetail; private System.Nullable<bool> _IsActive; private System.Nullable<System.Guid> _SiteID; #region Extensibility Method Definitions partial void OnLoaded(); partial void OnValidate(System.Data.Linq.ChangeAction action); partial void OnCreated(); partial void OnCalendarIDChanging(System.Guid value); partial void OnCalendarIDChanged(); partial void OnEventDateChanging(System.Nullable<System.DateTime> value); partial void OnEventDateChanged(); partial void OnEventTitleChanging(string value); partial void OnEventTitleChanged(); partial void OnEventDetailChanging(string value); partial void OnEventDetailChanged(); partial void OnIsActiveChanging(System.Nullable<bool> value); partial void OnIsActiveChanged(); partial void OnSiteIDChanging(System.Nullable<System.Guid> value); partial void OnSiteIDChanged(); #endregion public tblCalendar() { OnCreated(); } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CalendarID", DbType="UniqueIdentifier NOT NULL", IsPrimaryKey=true)] public System.Guid CalendarID { get { return this._CalendarID; } set { if ((this._CalendarID != value)) { this.OnCalendarIDChanging(value); this.SendPropertyChanging(); this._CalendarID = value; this.SendPropertyChanged("CalendarID"); this.OnCalendarIDChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EventDate", DbType="DateTime")] public System.Nullable<System.DateTime> EventDate { get { return this._EventDate; } set { if ((this._EventDate != value)) { this.OnEventDateChanging(value); this.SendPropertyChanging(); this._EventDate = value; this.SendPropertyChanged("EventDate"); this.OnEventDateChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EventTitle", DbType="VarChar(255)")] public string EventTitle { get { return this._EventTitle; } set { if ((this._EventTitle != value)) { this.OnEventTitleChanging(value); this.SendPropertyChanging(); this._EventTitle = value; this.SendPropertyChanged("EventTitle"); this.OnEventTitleChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EventDetail", DbType="VarChar(MAX)")] public string EventDetail { get { return this._EventDetail; } set { if ((this._EventDetail != value)) { this.OnEventDetailChanging(value); this.SendPropertyChanging(); this._EventDetail = value; this.SendPropertyChanged("EventDetail"); this.OnEventDetailChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_IsActive", DbType="Bit")] public System.Nullable<bool> IsActive { get { return this._IsActive; } set { if ((this._IsActive != value)) { this.OnIsActiveChanging(value); this.SendPropertyChanging(); this._IsActive = value; this.SendPropertyChanged("IsActive"); this.OnIsActiveChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_SiteID", DbType="UniqueIdentifier")] public System.Nullable<System.Guid> SiteID { get { return this._SiteID; } set { if ((this._SiteID != value)) { this.OnSiteIDChanging(value); this.SendPropertyChanging(); this._SiteID = value; this.SendPropertyChanged("SiteID"); this.OnSiteIDChanged(); } } } public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; protected virtual void SendPropertyChanging() { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, emptyChangingEventArgs); } } protected virtual void SendPropertyChanged(String propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } } #pragma warning restore 1591
26.942308
143
0.664811
[ "MIT" ]
ninianne98/CarrotCakeCMS-MVC
PluginCalendarModule/Code/dbCalendar.designer.cs
7,007
C#
using System; namespace _12_Test_Numbers { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int m = int.Parse(Console.ReadLine()); int sumMax = int.Parse(Console.ReadLine()); int sum = 0; int counter = 0; for (int i = n; i >= 1; i--) { for (int k = 1; k <= m; k++) { sum += i * k * 3; counter++; if (sum >= sumMax) { Console.WriteLine($"{counter} combinations"); Console.WriteLine($"Sum: {sum} >= {sumMax}"); return; } } } Console.WriteLine($"{counter} combinations"); Console.WriteLine($"Sum: {sum}"); } } }
18
51
0.537037
[ "MIT" ]
alchemistbg/Software-University
02-Tech-Module/01-Programming-Fundamentals/02-Conditional-Statements-and-Loops/02-Exercises/12_Test_Numbers/Program.cs
650
C#
using GitVersion.Extensions; using GitVersion.Helpers; namespace GitVersion; public class ReferenceName : IEquatable<ReferenceName?>, IComparable<ReferenceName> { private static readonly LambdaEqualityHelper<ReferenceName> equalityHelper = new(x => x.Canonical); private static readonly LambdaKeyComparer<ReferenceName, string> comparerHelper = new(x => x.Canonical); private const string LocalBranchPrefix = "refs/heads/"; private const string RemoteTrackingBranchPrefix = "refs/remotes/"; private const string TagPrefix = "refs/tags/"; private const string PullRequestPrefix1 = "refs/pull/"; private const string PullRequestPrefix2 = "refs/pull-requests/"; public ReferenceName(string canonical) { Canonical = canonical.NotNull(); Friendly = Shorten(); WithoutRemote = RemoveRemote(); IsBranch = IsPrefixedBy(Canonical, LocalBranchPrefix); IsRemoteBranch = IsPrefixedBy(Canonical, RemoteTrackingBranchPrefix); IsTag = IsPrefixedBy(Canonical, TagPrefix); IsPullRequest = IsPrefixedBy(Canonical, PullRequestPrefix1) || IsPrefixedBy(Canonical, PullRequestPrefix2); } public static ReferenceName Parse(string canonicalName) { if (IsPrefixedBy(canonicalName, LocalBranchPrefix) || IsPrefixedBy(canonicalName, RemoteTrackingBranchPrefix) || IsPrefixedBy(canonicalName, TagPrefix) || IsPrefixedBy(canonicalName, PullRequestPrefix1) || IsPrefixedBy(canonicalName, PullRequestPrefix2)) { return new ReferenceName(canonicalName); } throw new ArgumentException($"The {nameof(canonicalName)} is not a Canonical name"); } public string Canonical { get; } public string Friendly { get; } public string WithoutRemote { get; } public bool IsBranch { get; } public bool IsRemoteBranch { get; } public bool IsTag { get; } public bool IsPullRequest { get; } public bool Equals(ReferenceName? other) => equalityHelper.Equals(this, other); public int CompareTo(ReferenceName other) => comparerHelper.Compare(this, other); public override bool Equals(object obj) => Equals((obj as ReferenceName)!); public override int GetHashCode() => equalityHelper.GetHashCode(this); public override string ToString() => Friendly; public bool EquivalentTo(string? name) => Canonical.Equals(name, StringComparison.OrdinalIgnoreCase) || Friendly.Equals(name, StringComparison.OrdinalIgnoreCase) || WithoutRemote.Equals(name, StringComparison.OrdinalIgnoreCase); private string Shorten() { if (IsPrefixedBy(Canonical, LocalBranchPrefix)) return Canonical.Substring(LocalBranchPrefix.Length); if (IsPrefixedBy(Canonical, RemoteTrackingBranchPrefix)) return Canonical.Substring(RemoteTrackingBranchPrefix.Length); if (IsPrefixedBy(Canonical, TagPrefix)) return Canonical.Substring(TagPrefix.Length); return Canonical; } private string RemoveRemote() { var isRemote = IsPrefixedBy(Canonical, RemoteTrackingBranchPrefix); return isRemote ? Friendly.Substring(Friendly.IndexOf("/", StringComparison.Ordinal) + 1) : Friendly; } private static bool IsPrefixedBy(string input, string prefix) => input.StartsWith(prefix, StringComparison.Ordinal); }
42.308642
120
0.707032
[ "MIT" ]
velkovb/GitVersion
src/GitVersion.Core/Git/ReferenceName.cs
3,427
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; namespace Azure.ResourceManager.Storage.Models { /// <summary> Metric specification of operation. </summary> public partial class MetricSpecification { /// <summary> Initializes a new instance of MetricSpecification. </summary> internal MetricSpecification() { } /// <summary> Initializes a new instance of MetricSpecification. </summary> /// <param name="name"> Name of metric specification. </param> /// <param name="displayName"> Display name of metric specification. </param> /// <param name="displayDescription"> Display description of metric specification. </param> /// <param name="unit"> Unit could be Bytes or Count. </param> /// <param name="dimensions"> Dimensions of blobs, including blob type and access tier. </param> /// <param name="aggregationType"> Aggregation type could be Average. </param> /// <param name="fillGapWithZero"> The property to decide fill gap with zero or not. </param> /// <param name="category"> The category this metric specification belong to, could be Capacity. </param> /// <param name="resourceIdDimensionNameOverride"> Account Resource Id. </param> internal MetricSpecification(string name, string displayName, string displayDescription, string unit, IReadOnlyList<Dimension> dimensions, string aggregationType, bool? fillGapWithZero, string category, string resourceIdDimensionNameOverride) { Name = name; DisplayName = displayName; DisplayDescription = displayDescription; Unit = unit; Dimensions = dimensions; AggregationType = aggregationType; FillGapWithZero = fillGapWithZero; Category = category; ResourceIdDimensionNameOverride = resourceIdDimensionNameOverride; } /// <summary> Name of metric specification. </summary> public string Name { get; } /// <summary> Display name of metric specification. </summary> public string DisplayName { get; } /// <summary> Display description of metric specification. </summary> public string DisplayDescription { get; } /// <summary> Unit could be Bytes or Count. </summary> public string Unit { get; } /// <summary> Dimensions of blobs, including blob type and access tier. </summary> public IReadOnlyList<Dimension> Dimensions { get; } /// <summary> Aggregation type could be Average. </summary> public string AggregationType { get; } /// <summary> The property to decide fill gap with zero or not. </summary> public bool? FillGapWithZero { get; } /// <summary> The category this metric specification belong to, could be Capacity. </summary> public string Category { get; } /// <summary> Account Resource Id. </summary> public string ResourceIdDimensionNameOverride { get; } } }
49.984127
250
0.663068
[ "MIT" ]
AzureDataBox/azure-sdk-for-net
sdk/storage/Azure.ResourceManager.Storage/src/Generated/Models/MetricSpecification.cs
3,149
C#
using System; using System.Collections.Generic; using System.Text; using CoreGraphics; using UIKit; using MusicPlayer.Managers; namespace MusicPlayer.iOS { internal class ProgressView : UIView { CustomProgress downloadProgess; CustomProgress sliderProgress; OBSlider slider; public Action EditingStarted {get;set;} public Action EditingEnded {get;set;} public ProgressView() { downloadProgess = new CustomProgress() { ProgressTintColor = UIColor.DarkGray, BackgroundColor = UIColor.White, }; downloadProgess.SizeToFit(); var style = this.GetStyle(); sliderProgress = new CustomProgress() { ProgressTintColor = style.AccentColorHorizontal, }; slider = new OBSlider(); slider.AccessibilityIdentifier = "Progress"; slider.BackgroundColor = UIColor.Clear; slider.MinimumTrackTintColor = style.AccentColorHorizontal; slider.MaximumTrackTintColor = UIColor.Clear; slider.SizeToFit(); slider.ValueChanged += (object sender, EventArgs e) => { sliderProgress.Progress = slider.Value; }; slider.EditingDidBegin += (object sender, EventArgs e) => {EditingStarted?.Invoke();}; slider.EditingDidEnd += (sender, args) => { EditingEnded?.Invoke(); PlaybackManager.Shared.Seek(slider.Value); }; slider.SetThumbImage(Images.GetPlaybackSliderThumb(), UIControlState.Normal); this.Frame = slider.Frame; this.AddSubview(downloadProgess); this.AddSubview(sliderProgress); this.AddSubview(slider); } public void SetAlpha(nfloat alpha) { alpha = NMath.Max(0, alpha); alpha = NMath.Min(1, alpha); slider.Alpha = alpha; sliderProgress.Alpha = 1f - alpha; } public nfloat VisibleHeight { get { return downloadProgess.Frame.Height; } } public override void LayoutSubviews() { var frame = Bounds; frame.Width += 40; slider.Frame = frame; frame = downloadProgess.Frame; //frame.X = 5; frame.Width = Bounds.Width + 5; sliderProgress.Frame = downloadProgess.Frame = frame; sliderProgress.Center = slider.Center = downloadProgess.Center = new CoreGraphics.CGPoint(Bounds.GetMidX(), Bounds.GetMidY()); } public float DownloadProgress { get { return downloadProgess.Progress; } set { downloadProgess.Progress = value; } } public float SliderProgress { get { return slider.Value; } set { if (slider.Tracking) return; slider.Position = sliderProgress.Progress = value; } } class CustomProgress : UIView { UIView progressView; UIImage progressImage; public UIImage ProgressImage { get { return progressImage; } set { progressImage = value; progressView.BackgroundColor = value == null ? UIColor.Clear : UIColor.FromPatternImage(value); } } public UIColor TrackTintColor { get { return BackgroundColor; } set { BackgroundColor = value; } } public UIColor ProgressTintColor { get { return progressView.BackgroundColor; } set { progressView.BackgroundColor = value; } } float progress; public float Progress { get { return progress; } set { progress = value; this.SetNeedsLayout(); } } public CustomProgress() : base(new CGRect(0, 0, 100, 2.5f)) { Add(progressView = new UIView()); this.ClipsToBounds = true; } public override void LayoutSubviews() { var frame = Bounds; frame.Width *= NMath.Max(progress, 0); progressView.Frame = frame; } } } }
23.449664
106
0.683171
[ "Apache-2.0" ]
Clancey/gMusic
MusicPlayer.iOS/Controls/ProgressView.cs
3,496
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; //Joshua King //Unused but functional public class ShieldPickup : MonoBehaviour { public GameObject Shield; public float thrust = 1f; private Rigidbody2D rb2d; // Use this for initialization void Start () { rb2d = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update () { } void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag ("Player")) { gameObject.SetActive (false); GameObject newShield = Instantiate (Shield, new Vector3 (0, 0, 1), Quaternion.identity); newShield.transform.localScale = new Vector3 (0.1f, 0.1f, 0.1f); int count = 100; while (count > 0) { newShield.transform.localScale += new Vector3 (1f, 1f, 1f) * (Time.deltaTime); count--; } count = 100; } } void OnTriggerStay2D (Collider2D other){ if (other.gameObject.CompareTag ("Beam") && other.gameObject.GetComponent<Renderer> ().enabled == true) { Vector2 target = new Vector2 (0, 0); Vector2 current = transform.position; Vector2 vectorToOrigin = Vector2.MoveTowards (-current, target, 3 * Time.deltaTime) * thrust; rb2d.AddForce (vectorToOrigin); } } }
24.54
107
0.696007
[ "MIT" ]
nberr/starlord
Assets/Scripts/ShieldPickup.cs
1,229
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class GroupKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public GroupKeywordRecommender() : base(SyntaxKind.GroupKeyword) { } protected override bool IsValidContext( int position, CSharpSyntaxContext context, CancellationToken cancellationToken ) { var token = context.TargetToken; // var q = from x in y // | if (!token.IntersectsWith(position) && token.IsLastTokenOfQueryClause()) { return true; } return false; } } }
29.944444
86
0.655844
[ "MIT" ]
belav/roslyn
src/Features/CSharp/Portable/Completion/KeywordRecommenders/GroupKeywordRecommender.cs
1,080
C#
using System; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace PowerUtils.AspNetCore.Attributes { /// <summary> /// Response with status code 400 (BadRequest) /// </summary> public class Response400Attribute : ProducesResponseTypeAttribute { public Response400Attribute(Type type) : base(type, StatusCodes.Status400BadRequest) { } } }
26.333333
96
0.724051
[ "MIT" ]
TechNobre/PowerUtils.AspNetCore.Attributes.ResponseTypes
src/Attributes/Response400Attribute.cs
397
C#
using System; using Bitstamp.Client.Websocket.Json; using Newtonsoft.Json; namespace Bitstamp.Client.Websocket.Responses.Books; public class OrderBook { /// <summary> /// Timestamp - datetime only seconds /// </summary> [JsonConverter(typeof(UnixDateTimeSecondsConverter))] public DateTime Timestamp { get; set; } /// <summary> /// Microtimestamp - datetime with milliseconds /// </summary> [JsonConverter(typeof(UnixDateTimeMillisecondsConverter))] public DateTime Microtimestamp { get; set; } /// <summary> /// Order book bid levels /// </summary> [JsonConverter(typeof(OrderBookLevelConverter), OrderBookSide.Bid)] public BookLevel[] Bids { get; set; } /// <summary> /// Order book ask levels /// </summary> [JsonConverter(typeof(OrderBookLevelConverter), OrderBookSide.Ask)] public BookLevel[] Asks { get; set; } }
28.25
71
0.679204
[ "Apache-2.0" ]
shaynevanasperen/bitstamp-client-websocket
src/Bitstamp.Client.Websocket/Responses/Books/OrderBook.cs
906
C#
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <info@amplify.pt> //#define SHOW_TEMPLATE_HELP_BOX using System; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace AmplifyShaderEditor { public enum HDSRPMaterialType { SubsurfaceScattering, Standard, Specular, Anisotropy, Iridescence, Translucent } public enum InvisibilityStatus { LockedInvisible, Invisible, Visible } public enum SetTemplateSource { NewShader, ShaderLoad, HotCodeReload }; [Serializable] [NodeAttributes( "Template Master Node", "Master", "Shader Generated according to template rules", null, KeyCode.None, false )] public sealed class TemplateMultiPassMasterNode : MasterNode { private const double MaxLODEditTimestamp = 1; private static int PASS_SELECTOR_VERSION = 16200; private static int PASS_UNIQUE_ID_VERSION = 16204; private const string LodNameId = "LODName"; private const string LodValueId = "LODValue"; private const string LodSubtitle = "LOD( {0} )"; private const string AdditionalLODsStr = "LODs"; private const string SubTitleFormatterStr = "(SubShader {0} Pass {1})"; private const string NoSubShaderPropertyStr = "No Sub-Shader properties available"; private const string NoPassPropertyStr = "No Pass properties available"; private const string WarningMessage = "Templates is a feature that is still heavily under development and users may experience some problems.\nPlease email support@amplify.pt if any issue occurs."; private const string OpenTemplateStr = "Edit Template"; private const string ReloadTemplateStr = "Reload Template"; private const string CommonPropertiesStr = "Common Properties "; private const string SubShaderModuleStr = "SubShader "; private const string PassModuleStr = "Pass "; private const string PassNameStr = "Name"; private const string PassNameFormateStr = "Name \"{0}\""; private const string SubShaderLODValueLabel = "LOD Value"; private const string SubShaderLODNameLabel = "LOD Name"; private bool m_reRegisterTemplateData = false; private bool m_fireTemplateChange = false; private bool m_fetchMasterNodeCategory = false; [SerializeField] private string m_templateGUID = "4e1801f860093ba4f9eb58a4b556825b"; [SerializeField] private int m_passIdx = 0; //[SerializeField] //private string m_passIdxStr = string.Empty; [SerializeField] private bool m_passFoldout = false; [SerializeField] private int m_subShaderIdx = 0; //[SerializeField] //private string m_subShaderIdxStr = string.Empty; [SerializeField] private bool m_subStringFoldout = false; [SerializeField] private bool m_lodFoldout = false; [SerializeField] private string m_mainLODName = string.Empty; //[SerializeField] //private string m_subShaderLODStr; //[SerializeField] //private bool m_mainMPMasterNode = false; [NonSerialized] private TemplateMultiPass m_templateMultiPass = null; [NonSerialized] private TemplateMultiPassMasterNode m_mainMasterNodeRef = null; [SerializeField] private TemplateModulesHelper m_subShaderModule = new TemplateModulesHelper(); [SerializeField] private TemplateModulesHelper m_passModule = new TemplateModulesHelper(); [SerializeField] private UsePassHelper m_usePass; [SerializeField] private string m_passName = string.Empty; [SerializeField] private string m_passUniqueId = string.Empty; [SerializeField] private string m_originalPassName = string.Empty; [SerializeField] private bool m_hasLinkPorts = false; [SerializeField] private InvisibilityStatus m_isInvisible = InvisibilityStatus.Visible; [SerializeField] private int m_invisibleOptions = 0; [SerializeField] private bool m_invalidNode = false; [SerializeField] private FallbackPickerHelper m_fallbackHelper = null; [SerializeField] private DependenciesHelper m_dependenciesHelper = new DependenciesHelper(); [SerializeField] private TemplateOptionsUIHelper m_subShaderOptions = new TemplateOptionsUIHelper( true ); [SerializeField] private TemplateOptionsUIHelper m_passOptions = new TemplateOptionsUIHelper( false ); [SerializeField] private TemplatePassSelectorHelper m_passSelector = new TemplatePassSelectorHelper(); [SerializeField] private TemplateOptionsDefinesContainer m_optionsDefineContainer = new TemplateOptionsDefinesContainer(); [SerializeField] private TerrainDrawInstancedHelper m_drawInstancedHelper = new TerrainDrawInstancedHelper(); // HATE THIS BELOW, MUST REMOVE HD SPECIFIC CODE FROM GENERIC MASTER NODE private const string HDSRPMaterialTypeStr = "Material Type"; private const string SRPMaterialSubsurfaceScatteringKeyword = "_MATERIAL_FEATURE_SUBSURFACE_SCATTERING 1"; private const string SRPMaterialTransmissionKeyword = "_MATERIAL_FEATURE_TRANSMISSION 1"; private const string SRPHDMaterialSpecularKeyword = "_MATERIAL_FEATURE_SPECULAR_COLOR 1"; //private const string SRPLWMaterialSpecularKeyword = "_SPECULAR_SETUP 1"; private const string SRPMaterialAnisotropyKeyword = "_MATERIAL_FEATURE_ANISOTROPY 1"; private const string SRPMaterialIridiscenceKeyword = "_MATERIAL_FEATURE_IRIDESCENCE 1"; //private const string SRPMaterialNormalMapKeyword = "_NORMALMAP 1"; //private const string SRPMaterialAlphaTestKeyword = "_ALPHATEST_ON 1"; //private const string SRPMaterialBlendModeAlphaClipThresholdKeyword = "_AlphaClip 1"; private const string SRPMaterialTransparentKeyword = "_SURFACE_TYPE_TRANSPARENT 1"; private const string SRPMaterialBlendModeAddKeyword = "_BLENDMODE_ADD 1"; private const string SRPMaterialBlendModeAlphaKeyword = "_BLENDMODE_ALPHA 1"; private const string SRPMaterialClearCoatKeyword = "_MATERIAL_FEATURE_CLEAR_COAT"; [NonSerialized] private bool m_fetchPorts = true; [NonSerialized] private InputPort m_specularPort; [NonSerialized] private InputPort m_metallicPort; [NonSerialized] private InputPort m_coatMaskPort; [NonSerialized] private InputPort m_diffusionProfilePort; [NonSerialized] private InputPort m_subsurfaceMaskPort; [NonSerialized] private InputPort m_thicknessPort; [NonSerialized] private InputPort m_anisotropyPort; [NonSerialized] private InputPort m_iridescenceThicknessPort; [NonSerialized] private InputPort m_iridescenceMaskPort; [NonSerialized] private InputPort m_indexOfRefractionPort; [NonSerialized] private InputPort m_transmittanceColorPort; [NonSerialized] private InputPort m_transmittanceAbsorptionDistancePort; [NonSerialized] private InputPort m_transmittanceMaskPort; [SerializeField] private HDSRPMaterialType m_hdSrpMaterialType = HDSRPMaterialType.Standard; [NonSerialized] private bool m_refreshLODValueMasterNodes = false; [NonSerialized] private bool m_refocusLODValueMasterNodes = false; [NonSerialized] private double m_refreshLODValueMasterNodesTimestamp; ////////////////////////////////////////////////////////////////////////// protected override void CommonInit( int uniqueId ) { base.CommonInit( uniqueId ); m_masterNodeCategory = 1;// First Template m_marginPreviewLeft = 20; m_shaderNameIsTitle = true; m_customInspectorName = string.Empty; m_customPrecision = true; } public override void ReleaseResources() { // Internal template resources ( for inline properties) are released by first node on the list // As it's also registered that way if( IsLODMainFirstPass ) m_containerGraph.ClearInternalTemplateNodes(); if( !IsLODMainMasterNode ) return; TemplateMultiPass template = ( m_templateMultiPass == null ) ? m_containerGraph.ParentWindow.TemplatesManagerInstance.GetTemplate( m_templateGUID ) as TemplateMultiPass : m_templateMultiPass; //Maintained the logic of being the main master node to unregister since this method is being called //over the main master node in multiple places //but it will unregister with unique of the first master node (pass 0) since it was the one //to register it int passUniqueId = ( m_passIdx == 0 ) ? UniqueId : ContainerGraph.MultiPassMasterNodes.NodesList[ 0 ].UniqueId; if( template != null && template.AvailableShaderProperties != null ) { // Unregister old template properties int oldPropertyCount = template.AvailableShaderProperties.Count; for( int i = 0; i < oldPropertyCount; i++ ) { UIUtils.ReleaseUniformName( passUniqueId, template.AvailableShaderProperties[ i ].PropertyName ); } } } public void CopyOptionsFrom( TemplateMultiPassMasterNode origin ) { //Copy options SubShaderOptions.CopyOptionsValuesFrom( origin.SubShaderOptions ); PassOptions.CopyOptionsValuesFrom( origin.PassOptions ); //Copy selected passes if( IsMainOutputNode ) m_passSelector.CopyFrom( origin.PassSelector ); } void RegisterProperties() { //First pass must be the one to always register properties so all modules //can extract a valid negative Id when reading inline properties if( /*!IsLODMainMasterNode*/!IsLODMainFirstPass ) { m_reRegisterTemplateData = false; return; } if( m_templateMultiPass != null ) { m_reRegisterTemplateData = false; // Register old template properties int newPropertyCount = m_templateMultiPass.AvailableShaderProperties.Count; for( int i = 0; i < newPropertyCount; i++ ) { m_containerGraph.AddInternalTemplateNode( m_templateMultiPass.AvailableShaderProperties[ i ] ); int nodeId = UIUtils.CheckUniformNameOwner( m_templateMultiPass.AvailableShaderProperties[ i ].PropertyName ); if( nodeId > -1 ) { if( UniqueId != nodeId ) { ParentNode node = m_containerGraph.GetNode( nodeId ); if( node != null ) { UIUtils.ShowMessage( string.Format( "Template requires property name {0} which is currently being used by {1}. Please rename it and reload template.", m_templateMultiPass.AvailableShaderProperties[ i ].PropertyName, node.Attributes.Name ) ); } else { UIUtils.ShowMessage( string.Format( "Template requires property name {0} which is currently being on your graph. Please rename it and reload template.", m_templateMultiPass.AvailableShaderProperties[ i ].PropertyName ) ); } } } else { UIUtils.RegisterUniformName( UniqueId, m_templateMultiPass.AvailableShaderProperties[ i ].PropertyName ); } } } } public override void OnEnable() { base.OnEnable(); m_reRegisterTemplateData = true; if( m_usePass == null ) { m_usePass = ScriptableObject.CreateInstance<UsePassHelper>(); m_usePass.Init( " Additional Use Passes" ); } if( m_fallbackHelper == null ) { m_fallbackHelper = ScriptableObject.CreateInstance<FallbackPickerHelper>(); m_fallbackHelper.Init(); } } protected override void OnUniqueIDAssigned() { base.OnUniqueIDAssigned(); if( UniqueId >= 0 ) { if( m_lodIndex == -1 ) { m_containerGraph.MultiPassMasterNodes.AddNode( this ); } else { m_containerGraph.LodMultiPassMasternodes[ m_lodIndex ].AddNode( this ); } } } public override void OnInputPortConnected( int portId, int otherNodeId, int otherPortId, bool activateNode = true ) { base.OnInputPortConnected( portId, otherNodeId, otherPortId, activateNode ); m_passOptions.CheckImediateActionsForPort( this, portId ); } public override void OnInputPortDisconnected( int portId ) { base.OnInputPortDisconnected( portId ); m_passOptions.CheckImediateActionsForPort( this, portId ); } public void ForceTemplateRefresh() { SetTemplate( null, false, true, m_subShaderIdx, m_passIdx, SetTemplateSource.HotCodeReload ); } public void SetTemplate( TemplateMultiPass template, bool writeDefaultData, bool fetchMasterNodeCategory, int subShaderIdx, int passIdx , SetTemplateSource source ) { if( subShaderIdx > -1 ) m_subShaderIdx = subShaderIdx; if( passIdx > -1 ) m_passIdx = passIdx; ReleaseResources(); bool hotCodeOrRead = ( template == null ); m_templateMultiPass = ( hotCodeOrRead ) ? m_containerGraph.ParentWindow.TemplatesManagerInstance.GetTemplate( m_templateGUID ) as TemplateMultiPass : template; if( m_templateMultiPass != null ) { string passName = string.IsNullOrEmpty( m_passUniqueId ) ? ( m_isInvisible == InvisibilityStatus.LockedInvisible ? m_passName : m_originalPassName ) : m_passUniqueId; int newPassIdx = m_passIdx; int newSubShaderIdx = m_subShaderIdx; m_templateMultiPass.GetSubShaderandPassFor( passName, ref newSubShaderIdx, ref newPassIdx ); if( newPassIdx == -1 || newSubShaderIdx == -1 ) { //m_containerGraph.MarkToDelete( this ); ContainerGraph.ParentWindow.SetOutdatedShaderFromTemplate(); m_invalidNode = true; UIUtils.ShowMessage( "Template changed drastically. Removing invalid passes." ); return; } else { if( m_passIdx != newPassIdx ) m_passIdx = newPassIdx; if( m_subShaderIdx != newSubShaderIdx ) m_subShaderIdx = newSubShaderIdx; } m_containerGraph.CurrentSRPType = m_templateMultiPass.SRPtype; if( m_templateMultiPass.IsSinglePass ) { SetAdditonalTitleText( string.Empty ); } else if( m_templateMultiPass.SubShaders[ 0 ].MainPass != m_passIdx ) { SetAdditonalTitleText( string.Format( SubTitleFormatterStr, m_subShaderIdx, m_passIdx ) ); } m_invalidNode = false; if( m_subShaderIdx >= m_templateMultiPass.SubShaders.Count || m_passIdx >= m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes.Count ) { if( DebugConsoleWindow.DeveloperMode ) Debug.LogFormat( "Inexisting pass {0}. Cancelling template fetch", m_originalPassName ); return; } m_isMainOutputNode = m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].IsMainPass; if( m_isMainOutputNode ) { // We cannot use UIUtils.MasterNodeOnTexture.height since this method can be // called before UIUtils is initialized m_insideSize.y = 55; } else { m_insideSize.y = 0; } //IsMainOutputNode = m_mainMPMasterNode; if( source != SetTemplateSource.HotCodeReload ) { //Only set this if no hotcode reload happens ( via new shader or load ) m_isInvisible = m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].IsInvisible ? InvisibilityStatus.LockedInvisible : InvisibilityStatus.Visible; } else { // On hot code reload we only need to verify if template pass visibility data changes // and change accordingly if( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].IsInvisible ) { if( m_isInvisible != InvisibilityStatus.LockedInvisible ) m_isInvisible = InvisibilityStatus.LockedInvisible; } else { if( m_isInvisible == InvisibilityStatus.LockedInvisible ) { m_isInvisible = InvisibilityStatus.Visible; } } } m_invisibleOptions = m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].InvisibleOptions; m_originalPassName = m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].PassNameContainer.Data; if( !hotCodeOrRead ) { if( m_templateMultiPass.SubShaders[ m_subShaderIdx ].LODContainer.Index > -1 ) { //m_subShaderLODStr = m_templateMultiPass.SubShaders[ m_subShaderIdx ].LODContainer.Id; ShaderLOD = Convert.ToInt32( m_templateMultiPass.SubShaders[ m_subShaderIdx ].LODContainer.Data ); } else { ShaderLOD = 0; } } m_shaderNameIsTitle = IsMainOutputNode; m_fetchMasterNodeCategory = fetchMasterNodeCategory; m_templateGUID = m_templateMultiPass.GUID; UpdatePortInfo(); RegisterProperties(); // template is null when hot code reloading or loading from file so inspector name shouldn't be changed if( !hotCodeOrRead ) { m_customInspectorName = m_templateMultiPass.CustomInspectorContainer.Data; if( m_isMainOutputNode ) { m_passSelector.Clear(); m_passSelector.Setup( m_templateMultiPass.SubShaders[ m_subShaderIdx ] ); } } else { //Hotcode reload or ReadFromString // Setup is only made if internal pass array is null if( m_isMainOutputNode ) { m_passSelector.Setup( m_templateMultiPass.SubShaders[ m_subShaderIdx ] ); } } SetupCustomOptionsFromTemplate( template != null ); if( string.IsNullOrEmpty( m_fallbackHelper.RawFallbackShader ) ) m_fallbackHelper.RawFallbackShader = m_templateMultiPass.FallbackContainer.Data; //bool updateInfofromTemplate = UpdatePortInfo(); //if( updateInfofromTemplate ) //{ m_subShaderModule.FetchDataFromTemplate( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Modules ); m_passModule.FetchDataFromTemplate( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules ); //} //RegisterProperties(); if( writeDefaultData ) { //ShaderName = m_templateMultiPass.DefaultShaderName; ShaderName = m_shaderName; m_passName = m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].PassNameContainer.Data; if( !m_templateMultiPass.IsSinglePass /*&& !m_shaderNameIsTitle*/ ) { if( m_templateMultiPass.SubShaders[ 0 ].MainPass != m_passIdx ) SetClippedTitle( m_passName ); } } UpdateSubShaderPassStr(); if( m_isMainOutputNode ) m_fireTemplateChange = true; } else { m_invalidNode = true; } } public override void OnRefreshLinkedPortsComplete() { if( m_invalidNode ) return; if( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.SRPIsPBRHD ) ConfigHDPorts(); SetReadOptions(); } public void SetReadOptions() { m_passOptions.SetReadOptions(); if( m_isMainOutputNode ) m_subShaderOptions.SetReadOptions(); } bool UpdatePortInfo() { List<TemplateInputData> inputDataList = m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].InputDataList; int count = inputDataList.Count; if( count != m_inputPorts.Count ) { DeleteAllInputConnections( true ); for( int i = 0; i < count; i++ ) { InputPort port = AddInputPort( inputDataList[ i ].DataType, false, inputDataList[ i ].PortName, inputDataList[ i ].OrderId, inputDataList[ i ].PortCategory, inputDataList[ i ].PortUniqueId ); port.ExternalLinkId = inputDataList[ i ].LinkId; m_hasLinkPorts = m_hasLinkPorts || !string.IsNullOrEmpty( inputDataList[ i ].LinkId ); } return true; } else { for( int i = 0; i < count; i++ ) { m_inputPorts[ i ].ChangeProperties( inputDataList[ i ].PortName, inputDataList[ i ].DataType, false ); m_inputPorts[ i ].ExternalLinkId = inputDataList[ i ].LinkId; } return false; } } public void SetPropertyActionFromItem( TemplateModulesHelper module, TemplateActionItem item ) { TemplateModulesHelper subShaderModule = m_isMainOutputNode ? m_subShaderModule : m_mainMasterNodeRef.SubShaderModule; switch( item.PropertyAction ) { case PropertyActionsEnum.CullMode: { if( item.CopyFromSubShader ) { module.CullModeHelper.CurrentCullMode = subShaderModule.CullModeHelper.CurrentCullMode; } else { module.CullModeHelper.CurrentCullMode = item.ActionCullMode; } } break; case PropertyActionsEnum.ColorMask: { if( item.CopyFromSubShader ) module.ColorMaskHelper.ColorMask = subShaderModule.ColorMaskHelper.ColorMask; else module.ColorMaskHelper.ColorMask = item.ColorMask.GetColorMask( module.ColorMaskHelper.ColorMask ); } break; case PropertyActionsEnum.ColorMask1: { if( item.CopyFromSubShader ) module.ColorMaskHelper1.ColorMask = subShaderModule.ColorMaskHelper1.ColorMask; else module.ColorMaskHelper1.ColorMask = item.ColorMask1.GetColorMask( module.ColorMaskHelper1.ColorMask ); } break; case PropertyActionsEnum.ColorMask2: { if( item.CopyFromSubShader ) module.ColorMaskHelper2.ColorMask = subShaderModule.ColorMaskHelper2.ColorMask; else module.ColorMaskHelper2.ColorMask = item.ColorMask2.GetColorMask( module.ColorMaskHelper2.ColorMask ); } break; case PropertyActionsEnum.ColorMask3: { if( item.CopyFromSubShader ) module.ColorMaskHelper3.ColorMask = subShaderModule.ColorMaskHelper3.ColorMask; else module.ColorMaskHelper3.ColorMask = item.ColorMask3.GetColorMask( module.ColorMaskHelper3.ColorMask ); } break; case PropertyActionsEnum.ZWrite: { if( item.CopyFromSubShader ) { module.DepthOphelper.ZWriteModeValue = subShaderModule.DepthOphelper.ZWriteModeValue; } else { module.DepthOphelper.ZWriteModeValue = item.ActionZWrite; } } break; case PropertyActionsEnum.ZTest: { if( item.CopyFromSubShader ) { module.DepthOphelper.ZTestModeValue = subShaderModule.DepthOphelper.ZTestModeValue; } else { module.DepthOphelper.ZTestModeValue = item.ActionZTest; } } break; case PropertyActionsEnum.ZOffsetFactor: { if( item.CopyFromSubShader ) { module.DepthOphelper.OffsetFactorValue = subShaderModule.DepthOphelper.OffsetFactorValue; } else { module.DepthOphelper.OffsetFactorValue = item.ActionZOffsetFactor; } } break; case PropertyActionsEnum.ZOffsetUnits: { if( item.CopyFromSubShader ) { module.DepthOphelper.OffsetUnitsValue = subShaderModule.DepthOphelper.OffsetUnitsValue; } else { module.DepthOphelper.OffsetUnitsValue = item.ActionZOffsetUnits; } } break; case PropertyActionsEnum.BlendRGB: { if( item.CopyFromSubShader ) { module.BlendOpHelper.SourceFactorRGB = subShaderModule.BlendOpHelper.SourceFactorRGB; module.BlendOpHelper.DestFactorRGB = subShaderModule.BlendOpHelper.DestFactorRGB; } else { module.BlendOpHelper.SourceFactorRGB = item.ActionBlendRGBSource; module.BlendOpHelper.DestFactorRGB = item.ActionBlendRGBDest; } } break; case PropertyActionsEnum.BlendRGB1: { if( item.CopyFromSubShader ) { module.BlendOpHelper1.SourceFactorRGB = subShaderModule.BlendOpHelper1.SourceFactorRGB; module.BlendOpHelper1.DestFactorRGB = subShaderModule.BlendOpHelper1.DestFactorRGB; } else { module.BlendOpHelper1.SourceFactorRGB = item.ActionBlendRGBSource1; module.BlendOpHelper1.DestFactorRGB = item.ActionBlendRGBDest1; } } break; case PropertyActionsEnum.BlendRGB2: { if( item.CopyFromSubShader ) { module.BlendOpHelper2.SourceFactorRGB = subShaderModule.BlendOpHelper2.SourceFactorRGB; module.BlendOpHelper2.DestFactorRGB = subShaderModule.BlendOpHelper2.DestFactorRGB; } else { module.BlendOpHelper2.SourceFactorRGB = item.ActionBlendRGBSource2; module.BlendOpHelper2.DestFactorRGB = item.ActionBlendRGBDest2; } } break; case PropertyActionsEnum.BlendRGB3: { if( item.CopyFromSubShader ) { module.BlendOpHelper3.SourceFactorRGB = subShaderModule.BlendOpHelper3.SourceFactorRGB; module.BlendOpHelper3.DestFactorRGB = subShaderModule.BlendOpHelper3.DestFactorRGB; } else { module.BlendOpHelper3.SourceFactorRGB = item.ActionBlendRGBSource3; module.BlendOpHelper3.DestFactorRGB = item.ActionBlendRGBDest3; } } break; case PropertyActionsEnum.BlendAlpha: { if( item.CopyFromSubShader ) { module.BlendOpHelper.SourceFactorAlpha = subShaderModule.BlendOpHelper.SourceFactorAlpha; module.BlendOpHelper.DestFactorAlpha = subShaderModule.BlendOpHelper.DestFactorAlpha; } else { module.BlendOpHelper.CurrentAlphaIndex = 1; module.BlendOpHelper.SourceFactorAlpha = item.ActionBlendAlphaSource; module.BlendOpHelper.DestFactorAlpha = item.ActionBlendAlphaDest; } } break; case PropertyActionsEnum.BlendAlpha1: { if( item.CopyFromSubShader ) { module.BlendOpHelper1.SourceFactorAlpha = subShaderModule.BlendOpHelper1.SourceFactorAlpha; module.BlendOpHelper1.DestFactorAlpha = subShaderModule.BlendOpHelper1.DestFactorAlpha; } else { module.BlendOpHelper1.CurrentAlphaIndex = 1; module.BlendOpHelper1.SourceFactorAlpha = item.ActionBlendAlphaSource1; module.BlendOpHelper1.DestFactorAlpha = item.ActionBlendAlphaDest1; } } break; case PropertyActionsEnum.BlendAlpha2: { if( item.CopyFromSubShader ) { module.BlendOpHelper2.SourceFactorAlpha = subShaderModule.BlendOpHelper2.SourceFactorAlpha; module.BlendOpHelper2.DestFactorAlpha = subShaderModule.BlendOpHelper2.DestFactorAlpha; } else { module.BlendOpHelper2.CurrentAlphaIndex = 1; module.BlendOpHelper2.SourceFactorAlpha = item.ActionBlendAlphaSource2; module.BlendOpHelper2.DestFactorAlpha = item.ActionBlendAlphaDest2; } } break; case PropertyActionsEnum.BlendAlpha3: { if( item.CopyFromSubShader ) { module.BlendOpHelper3.SourceFactorAlpha = subShaderModule.BlendOpHelper3.SourceFactorAlpha; module.BlendOpHelper3.DestFactorAlpha = subShaderModule.BlendOpHelper3.DestFactorAlpha; } else { module.BlendOpHelper3.CurrentAlphaIndex = 1; module.BlendOpHelper3.SourceFactorAlpha = item.ActionBlendAlphaSource3; module.BlendOpHelper3.DestFactorAlpha = item.ActionBlendAlphaDest3; } } break; case PropertyActionsEnum.BlendOpRGB: { if( item.CopyFromSubShader ) { module.BlendOpHelper.BlendOpRGB = subShaderModule.BlendOpHelper.BlendOpRGB; } else { module.BlendOpHelper.BlendOpRGB = item.ActionBlendOpRGB; } } break; case PropertyActionsEnum.BlendOpAlpha: { if( item.CopyFromSubShader ) { module.BlendOpHelper.BlendOpAlpha = subShaderModule.BlendOpHelper.BlendOpAlpha; } else { module.BlendOpHelper.BlendOpAlpha = item.ActionBlendOpAlpha; } } break; case PropertyActionsEnum.StencilReference: { if( item.CopyFromSubShader ) { module.StencilBufferHelper.ReferenceValue = subShaderModule.StencilBufferHelper.ReferenceValue; } else { module.StencilBufferHelper.ReferenceValue = item.ActionStencilReference; } } break; case PropertyActionsEnum.StencilReadMask: { if( item.CopyFromSubShader ) { module.StencilBufferHelper.ReadMaskValue = subShaderModule.StencilBufferHelper.ReadMaskValue; } else { module.StencilBufferHelper.ReadMaskValue = item.ActionStencilReadMask; } } break; case PropertyActionsEnum.StencilWriteMask: { if( item.CopyFromSubShader ) { module.StencilBufferHelper.WriteMaskValue = subShaderModule.StencilBufferHelper.WriteMaskValue; } else { module.StencilBufferHelper.WriteMaskValue = item.ActionStencilWriteMask; } } break; case PropertyActionsEnum.StencilComparison: { if( item.CopyFromSubShader ) { module.StencilBufferHelper.ComparisonFunctionIdxValue = subShaderModule.StencilBufferHelper.ComparisonFunctionIdxValue; } else { module.StencilBufferHelper.ComparisonFunctionIdxValue = item.ActionStencilComparison; } } break; case PropertyActionsEnum.StencilPass: { if( item.CopyFromSubShader ) { module.StencilBufferHelper.PassStencilOpIdxValue = subShaderModule.StencilBufferHelper.PassStencilOpIdxValue; } else { module.StencilBufferHelper.PassStencilOpIdxValue = item.ActionStencilPass; } } break; case PropertyActionsEnum.StencilFail: { if( item.CopyFromSubShader ) { module.StencilBufferHelper.FailStencilOpIdxValue = subShaderModule.StencilBufferHelper.FailStencilOpIdxValue; } else { module.StencilBufferHelper.FailStencilOpIdxValue = item.ActionStencilFail; } } break; case PropertyActionsEnum.StencilZFail: { if( item.CopyFromSubShader ) { module.StencilBufferHelper.ZFailStencilOpIdxValue = subShaderModule.StencilBufferHelper.ZFailStencilOpIdxValue; } else { module.StencilBufferHelper.ZFailStencilOpIdxValue = item.ActionStencilZFail; } } break; case PropertyActionsEnum.RenderType: { module.TagsHelper.AddSpecialTag( TemplateSpecialTags.RenderType, item ); } break; case PropertyActionsEnum.RenderQueue: { module.TagsHelper.AddSpecialTag( TemplateSpecialTags.Queue, item ); } break; } } public void OnCustomPassOptionSelected( bool isRefreshing, bool invertAction, TemplateOptionUIItem uiItem, params TemplateActionItem[] validActions ) { m_passOptions.OnCustomOptionSelected( isRefreshing, invertAction, this, uiItem, validActions ); } public void OnCustomSubShaderOptionSelected( bool isRefreshing, bool invertAction, TemplateOptionUIItem uiItem, params TemplateActionItem[] validActions ) { if( m_isMainOutputNode ) m_subShaderOptions.OnCustomOptionSelected( isRefreshing, invertAction, this, uiItem, validActions ); } void SetupCustomOptionsFromTemplate( bool newTemplate ) { m_passOptions.SetupCustomOptionsFromTemplate( this, newTemplate ); if( m_isMainOutputNode ) m_subShaderOptions.SetupCustomOptionsFromTemplate( this, newTemplate ); } void SetPassCustomOptionsInfo( TemplateMultiPassMasterNode masterNode ) { TemplateMultiPassMasterNode mainMasterNode = masterNode.IsMainOutputNode ? masterNode : ( m_containerGraph.CurrentMasterNode as TemplateMultiPassMasterNode ); mainMasterNode.SubShaderOptions.SetSubShaderCustomOptionsPortsInfo( masterNode, ref m_currentDataCollector ); masterNode.PassOptions.SetCustomOptionsInfo( masterNode, ref m_currentDataCollector ); } void RefreshCustomOptionsDict() { m_passOptions.RefreshCustomOptionsDict(); if( m_isMainOutputNode ) m_subShaderOptions.RefreshCustomOptionsDict(); } void SetCategoryIdxFromTemplate() { int templateCount = m_containerGraph.ParentWindow.TemplatesManagerInstance.TemplateCount; for( int i = 0; i < templateCount; i++ ) { int idx = i + 1; TemplateMultiPass templateData = m_containerGraph.ParentWindow.TemplatesManagerInstance.GetTemplate( i ) as TemplateMultiPass; if( templateData != null && m_templateMultiPass != null && m_templateMultiPass.GUID.Equals( templateData.GUID ) ) m_masterNodeCategory = idx; } } public void CheckTemplateChanges() { if( m_invalidNode ) return; if( IsLODMainMasterNode ) { if( m_containerGraph.MultiPassMasterNodes.Count != m_templateMultiPass.MasterNodesRequired ) { if( m_availableCategories == null ) RefreshAvailableCategories(); if( DebugConsoleWindow.DeveloperMode ) Debug.Log( "Template Pass amount was changed. Rebuiling master nodes" ); m_containerGraph.ParentWindow.ReplaceMasterNode( m_availableCategories[ m_masterNodeCategory ], true ); } } } public override void OnNodeLogicUpdate( DrawInfo drawInfo ) { if( m_invalidNode ) { return; } base.OnNodeLogicUpdate( drawInfo ); if( m_templateMultiPass == null ) { // Hotcode reload has happened SetTemplate( null, false, true, m_subShaderIdx, m_passIdx , SetTemplateSource.HotCodeReload ); CheckTemplateChanges(); } if( m_reRegisterTemplateData ) { RegisterProperties(); } if( m_fetchMasterNodeCategory ) { if( m_availableCategories != null ) { m_fetchMasterNodeCategory = false; SetCategoryIdxFromTemplate(); } } if( m_fireTemplateChange ) { m_fireTemplateChange = false; m_containerGraph.FireMasterNodeReplacedEvent(); } if( m_subShaderModule.HasValidData ) { m_subShaderModule.OnLogicUpdate( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Modules ); } if( m_passModule.HasValidData ) { m_passModule.OnLogicUpdate( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules ); } if( !m_isMainOutputNode && m_mainMasterNodeRef == null ) { m_mainMasterNodeRef = m_containerGraph.CurrentMasterNode as TemplateMultiPassMasterNode; } if( m_refreshLODValueMasterNodes && ( EditorApplication.timeSinceStartup - m_refreshLODValueMasterNodesTimestamp ) > MaxLODEditTimestamp ) { m_refreshLODValueMasterNodes = false; m_refocusLODValueMasterNodes = true; m_containerGraph.SortLODMasterNodes(); } } public override void Draw( DrawInfo drawInfo ) { if( m_isInvisible == InvisibilityStatus.Visible ) { base.Draw( drawInfo ); } } public override void OnNodeLayout( DrawInfo drawInfo ) { if( m_invalidNode ) { if( m_isMainOutputNode ) { UIUtils.ShowMessage( "Invalid current template. Switching to Standard Surface", MessageSeverity.Error ); m_shaderModelIdx = 0; m_masterNodeCategory = 0; m_containerGraph.ParentWindow.ReplaceMasterNode( new MasterNodeCategoriesData( AvailableShaderTypes.SurfaceShader, m_shaderName ), false ); } return; } if( m_isInvisible != InvisibilityStatus.Visible ) { return; } if( !IsMainOutputNode ) { if( !IsInvisible && Docking ) { m_useSquareNodeTitle = true; TemplateMultiPassMasterNode master = ContainerGraph.CurrentMasterNode as TemplateMultiPassMasterNode; m_position = master.TruePosition; m_position.height = 32; int masterIndex = ContainerGraph.MultiPassMasterNodes.NodesList.IndexOf( master ); int index = ContainerGraph.MultiPassMasterNodes.GetNodeRegisterIdx( UniqueId ); if( index > masterIndex ) { int backTracking = 0; for( int i = index - 1; i > masterIndex; i-- ) { if( !ContainerGraph.MultiPassMasterNodes.NodesList[ i ].IsInvisible && ContainerGraph.MultiPassMasterNodes.NodesList[ i ].Docking ) backTracking++; } m_position.y = master.TruePosition.yMax + 1 + 33 * ( backTracking );// ContainerGraph.MultiPassMasterNodes.NodesList[ index - 1 ].TruePosition.yMax; base.OnNodeLayout( drawInfo ); } else { int forwardTracking = 1; for( int i = index + 1; i < masterIndex; i++ ) { if( !ContainerGraph.MultiPassMasterNodes.NodesList[ i ].IsInvisible && ContainerGraph.MultiPassMasterNodes.NodesList[ i ].Docking ) forwardTracking++; } m_position.y = master.TruePosition.y - 33 * ( forwardTracking );// ContainerGraph.MultiPassMasterNodes.NodesList[ index - 1 ].TruePosition.yMax; base.OnNodeLayout( drawInfo ); } } else { m_useSquareNodeTitle = false; base.OnNodeLayout( drawInfo ); } } else { base.OnNodeLayout( drawInfo ); } } public override void OnNodeRepaint( DrawInfo drawInfo ) { base.OnNodeRepaint( drawInfo ); if( m_invalidNode ) return; if( m_isInvisible == InvisibilityStatus.Visible ) { if( m_containerGraph.IsInstancedShader ) { DrawInstancedIcon( drawInfo ); } } } public override void UpdateFromShader( Shader newShader ) { if( m_currentMaterial != null && m_currentMaterial.shader != newShader ) { m_currentMaterial.shader = newShader; } CurrentShader = newShader; } public override void UpdateMasterNodeMaterial( Material material ) { m_currentMaterial = material; FireMaterialChangedEvt(); } void DrawReloadButton() { if( GUILayout.Button( ReloadTemplateStr ) && m_templateMultiPass != null ) { m_templateMultiPass.Reload(); } } void DrawOpenTemplateButton() { GUILayout.BeginHorizontal(); { if( GUILayout.Button( OpenTemplateStr ) && m_templateMultiPass != null ) { try { string pathname = AssetDatabase.GUIDToAssetPath( m_templateMultiPass.GUID ); if( !string.IsNullOrEmpty( pathname ) ) { Shader selectedTemplate = AssetDatabase.LoadAssetAtPath<Shader>( pathname ); if( selectedTemplate != null ) { AssetDatabase.OpenAsset( selectedTemplate, 1 ); } } } catch( Exception e ) { Debug.LogException( e ); } } if( GUILayout.Button( "\u25C4", GUILayout.Width( 18 ), GUILayout.Height( 18 ) ) && m_templateMultiPass != null ) { try { string pathname = AssetDatabase.GUIDToAssetPath( m_templateMultiPass.GUID ); if( !string.IsNullOrEmpty( pathname ) ) { Shader selectedTemplate = AssetDatabase.LoadAssetAtPath<Shader>( pathname ); if( selectedTemplate != null ) { Event.current.Use(); Selection.activeObject = selectedTemplate; EditorGUIUtility.PingObject( Selection.activeObject ); } } } catch( Exception e ) { Debug.LogException( e ); } } } GUILayout.EndHorizontal(); } public override void DrawProperties() { base.DrawProperties(); if( m_invalidNode ) return; NodeUtils.DrawPropertyGroup( ref m_propertiesFoldout, CommonPropertiesStr, DrawCommonProperties ); NodeUtils.DrawPropertyGroup( ref m_subStringFoldout, SubShaderModuleStr, DrawSubShaderProperties ); NodeUtils.DrawPropertyGroup( ref m_passFoldout, PassModuleStr, DrawPassProperties ); DrawMaterialInputs( UIUtils.MenuItemToolbarStyle, false ); if( m_propertyOrderChanged ) { List<TemplateMultiPassMasterNode> mpNodes = UIUtils.CurrentWindow.CurrentGraph.MultiPassMasterNodes.NodesList; int count = mpNodes.Count; for( int i = 0; i < count; i++ ) { if( mpNodes[ i ].UniqueId != UniqueId ) { mpNodes[ i ].CopyPropertyListFrom( this ); } } } #if SHOW_TEMPLATE_HELP_BOX EditorGUILayout.HelpBox( WarningMessage, MessageType.Warning ); #endif } // this will be removed later when PBR options are created void SetExtraDefine( string define ) { List<TemplateMultiPassMasterNode> nodes = this.ContainerGraph.MultiPassMasterNodes.NodesList; int count = nodes.Count; for( int nodeIdx = 0; nodeIdx < count; nodeIdx++ ) { nodes[ nodeIdx ].OptionsDefineContainer.AddDefine( "#define " + define, false ); } } void AddHDKeywords() { if( m_templateMultiPass.CustomTemplatePropertyUI == CustomTemplatePropertyUIEnum.None ) return; if( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Modules.SRPType != TemplateSRPType.HD || !m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.SRPIsPBR ) return; switch( m_hdSrpMaterialType ) { case HDSRPMaterialType.SubsurfaceScattering: { SetExtraDefine( SRPMaterialSubsurfaceScatteringKeyword ); //m_currentDataCollector.AddToDefines( UniqueId, SRPMaterialSubsurfaceScatteringKeyword ); if( m_thicknessPort != null && m_thicknessPort.HasOwnOrLinkConnection ) { SetExtraDefine( SRPMaterialTransmissionKeyword ); //m_currentDataCollector.AddToDefines( UniqueId, SRPMaterialTransmissionKeyword ); } } break; case HDSRPMaterialType.Standard: break; case HDSRPMaterialType.Specular: { SetExtraDefine( SRPHDMaterialSpecularKeyword ); //m_currentDataCollector.AddToDefines( UniqueId, SRPHDMaterialSpecularKeyword ); } break; case HDSRPMaterialType.Anisotropy: { SetExtraDefine( SRPMaterialAnisotropyKeyword ); //m_currentDataCollector.AddToDefines( UniqueId, SRPMaterialAnisotropyKeyword ); } break; case HDSRPMaterialType.Iridescence: { SetExtraDefine( SRPMaterialIridiscenceKeyword ); //m_currentDataCollector.AddToDefines( UniqueId, SRPMaterialIridiscenceKeyword ); } break; case HDSRPMaterialType.Translucent: { SetExtraDefine( SRPMaterialTransmissionKeyword ); //m_currentDataCollector.AddToDefines( UniqueId, SRPMaterialTransmissionKeyword ); } break; } if( m_coatMaskPort != null && m_coatMaskPort.HasOwnOrLinkConnection ) { SetExtraDefine( SRPMaterialClearCoatKeyword ); //m_currentDataCollector.AddToDefines( UniqueId, SRPMaterialClearCoatKeyword ); } } void FetchHDPorts() { if( m_fetchPorts ) { m_fetchPorts = false; if( m_inputPorts.Count > 4 ) { m_specularPort = GetInputPortByUniqueId( 3 ); m_metallicPort = GetInputPortByUniqueId( 4 ); m_coatMaskPort = GetInputPortByUniqueId( 11 ); m_diffusionProfilePort = GetInputPortByUniqueId( 12 ); m_subsurfaceMaskPort = GetInputPortByUniqueId( 13 ); m_thicknessPort = GetInputPortByUniqueId( 14 ); m_anisotropyPort = GetInputPortByUniqueId( 15 ); m_iridescenceThicknessPort = GetInputPortByUniqueId( 16 ); m_iridescenceMaskPort = GetInputPortByUniqueId( 17 ); m_indexOfRefractionPort = GetInputPortByUniqueId( 18 ); m_transmittanceColorPort = GetInputPortByUniqueId( 19 ); m_transmittanceAbsorptionDistancePort = GetInputPortByUniqueId( 20 ); m_transmittanceMaskPort = GetInputPortByUniqueId( 21 ); } } } void ConfigHDPorts() { if( m_templateMultiPass.CustomTemplatePropertyUI == CustomTemplatePropertyUIEnum.None ) return; if( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Modules.SRPType != TemplateSRPType.HD || !m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.SRPIsPBR ) return; FetchHDPorts(); if( m_inputPorts.Count > 4 ) { switch( m_hdSrpMaterialType ) { case HDSRPMaterialType.SubsurfaceScattering: { m_specularPort.Visible = false; m_metallicPort.Visible = false; m_coatMaskPort.Visible = true; m_diffusionProfilePort.Visible = true; m_subsurfaceMaskPort.Visible = true; m_thicknessPort.Visible = true; m_anisotropyPort.Visible = false; m_iridescenceThicknessPort.Visible = false; m_iridescenceMaskPort.Visible = false; m_indexOfRefractionPort.Visible = false; m_transmittanceColorPort.Visible = false; m_transmittanceAbsorptionDistancePort.Visible = false; m_transmittanceMaskPort.Visible = false; } break; case HDSRPMaterialType.Standard: { m_specularPort.Visible = false; m_metallicPort.Visible = true; m_coatMaskPort.Visible = true; m_diffusionProfilePort.Visible = false; m_subsurfaceMaskPort.Visible = false; m_thicknessPort.Visible = false; m_anisotropyPort.Visible = false; m_iridescenceThicknessPort.Visible = false; m_iridescenceMaskPort.Visible = false; m_indexOfRefractionPort.Visible = false; m_transmittanceColorPort.Visible = false; m_transmittanceAbsorptionDistancePort.Visible = false; m_transmittanceMaskPort.Visible = false; } break; case HDSRPMaterialType.Specular: { m_specularPort.Visible = true; m_metallicPort.Visible = false; m_coatMaskPort.Visible = true; m_diffusionProfilePort.Visible = false; m_subsurfaceMaskPort.Visible = false; m_thicknessPort.Visible = false; m_anisotropyPort.Visible = false; m_iridescenceThicknessPort.Visible = false; m_iridescenceMaskPort.Visible = false; m_indexOfRefractionPort.Visible = false; m_transmittanceColorPort.Visible = false; m_transmittanceAbsorptionDistancePort.Visible = false; m_transmittanceMaskPort.Visible = false; } break; case HDSRPMaterialType.Anisotropy: { m_specularPort.Visible = false; m_metallicPort.Visible = true; m_coatMaskPort.Visible = true; m_diffusionProfilePort.Visible = false; m_subsurfaceMaskPort.Visible = false; m_thicknessPort.Visible = false; m_anisotropyPort.Visible = true; m_iridescenceThicknessPort.Visible = false; m_iridescenceMaskPort.Visible = false; m_indexOfRefractionPort.Visible = false; m_transmittanceColorPort.Visible = false; m_transmittanceAbsorptionDistancePort.Visible = false; m_transmittanceMaskPort.Visible = false; } break; case HDSRPMaterialType.Iridescence: { m_specularPort.Visible = false; m_metallicPort.Visible = true; m_coatMaskPort.Visible = true; m_diffusionProfilePort.Visible = false; m_subsurfaceMaskPort.Visible = false; m_thicknessPort.Visible = false; m_anisotropyPort.Visible = false; m_iridescenceThicknessPort.Visible = true; m_iridescenceMaskPort.Visible = true; m_indexOfRefractionPort.Visible = false; m_transmittanceColorPort.Visible = false; m_transmittanceAbsorptionDistancePort.Visible = false; m_transmittanceMaskPort.Visible = false; } break; case HDSRPMaterialType.Translucent: { m_specularPort.Visible = false; m_metallicPort.Visible = false; m_coatMaskPort.Visible = false; m_diffusionProfilePort.Visible = true; m_subsurfaceMaskPort.Visible = false; m_thicknessPort.Visible = true; m_anisotropyPort.Visible = false; m_iridescenceThicknessPort.Visible = false; m_iridescenceMaskPort.Visible = false; m_indexOfRefractionPort.Visible = false; m_transmittanceColorPort.Visible = false; m_transmittanceAbsorptionDistancePort.Visible = false; m_transmittanceMaskPort.Visible = false; } break; } } m_sizeIsDirty = ( m_isInvisible == InvisibilityStatus.Visible ); } public void SetShaderLODValueAndLabel( int value ) { if( ShaderLOD != value ) ShaderLOD = value; if( ContainerGraph.HasLODs ) { SetClippedAdditionalTitle( string.Format( LodSubtitle, ShaderLOD ) ); } else { SetAdditonalTitleText( string.Empty ); } } void DrawLODAddRemoveButtons() { DrawLODAddRemoveButtons( -2 , true ); } void DrawLODAddRemoveButtons( int index , bool showRemove ) { if( GUILayoutButton( string.Empty, UIUtils.PlusStyle, GUILayout.Width( 15 ) ) ) { Vector2 minPos = Vec2Position; //bool newNodePositionMode = false; //if( newNodePositionMode ) //{ // for( int lod = 0; lod < ContainerGraph.LodMultiPassMasternodes.Count; lod++ ) // { // if( ContainerGraph.LodMultiPassMasternodes[ lod ].Count != 0 ) // { // Vector2 currPos = ContainerGraph.LodMultiPassMasternodes[ lod ].NodesList[ m_passIdx ].Vec2Position; // if( currPos.y > minPos.y ) // { // minPos = currPos; // } // } // else // { // if( index < 0 ) // { // index = lod; // } // break; // } // } //} //else //{ for( int lod = ContainerGraph.LodMultiPassMasternodes.Count - 1 ; lod >= 0; lod-- ) { if( ContainerGraph.LodMultiPassMasternodes[ lod ].Count != 0 ) { minPos = ContainerGraph.LodMultiPassMasternodes[ lod ].NodesList[ m_passIdx ].Vec2Position; break; } } //} minPos.y += HeightEstimate + 10; ContainerGraph.CreateLodMasterNodes( m_templateMultiPass, index, minPos ); } if( showRemove && GUILayoutButton( string.Empty, UIUtils.MinusStyle, GUILayout.Width( 15 ) ) ) { ContainerGraph.DestroyLodMasterNodes( index ); } } void SetupLODNodeName() { if( IsMainOutputNode ) { if( string.IsNullOrEmpty( m_mainLODName ) ) { m_shaderNameIsTitle = true; m_content.text = GenerateClippedTitle( m_croppedShaderName ); } else { m_shaderNameIsTitle = false; m_content.text = GenerateClippedTitle( m_mainLODName ); } } else { m_shaderNameIsTitle = false; m_content.text = GenerateClippedTitle( m_passName ); } } public void DrawLodRowItem(bool listMode) { float labelWidthBuffer = EditorGUIUtility.labelWidth; EditorGUILayout.BeginHorizontal(); if( listMode ) { if( GUILayout.Button( "\u25b6", GUILayout.Width( 18 ), GUILayout.Height( 18 ) ) ) { m_containerGraph.ParentWindow.FocusOnNode( this, 1, false, true ); } EditorGUI.BeginChangeCheck(); GUI.SetNextControlName( LodValueId + m_lodIndex ); m_shaderLOD = EditorGUILayoutIntField( string.Empty, m_shaderLOD, GUILayout.Width( 50 ) ); } else { EditorGUI.BeginChangeCheck(); EditorGUIUtility.labelWidth = 45; GUI.SetNextControlName( LodValueId + m_lodIndex ); m_shaderLOD = EditorGUILayoutIntField( "LOD", ShaderLOD, GUILayout.Width(100)); EditorGUIUtility.labelWidth = labelWidthBuffer; } if( EditorGUI.EndChangeCheck() ) { m_refreshLODValueMasterNodes = true; m_refreshLODValueMasterNodesTimestamp = EditorApplication.timeSinceStartup; if( ContainerGraph.HasLODs ) SetClippedAdditionalTitle( string.Format( LodSubtitle, ShaderLOD ) ); } EditorGUI.BeginChangeCheck(); GUI.SetNextControlName( LodNameId + ShaderLOD ); if( listMode ) { m_mainLODName = EditorGUILayoutTextField( string.Empty, m_mainLODName, GUILayout.Width( 100 ) ); } else { GUILayout.Space( -15 ); EditorGUIUtility.labelWidth = 45; m_mainLODName = EditorGUILayoutTextField( string.Empty, m_mainLODName ); EditorGUIUtility.labelWidth = labelWidthBuffer; } if( EditorGUI.EndChangeCheck() ) { // If reorder is scheduled make sure it doesn't happen when editing LOD name if( m_refreshLODValueMasterNodes ) m_refreshLODValueMasterNodesTimestamp = EditorApplication.timeSinceStartup; SetupLODNodeName(); } if( listMode ) DrawLODAddRemoveButtons( m_lodIndex, ( m_lodIndex >= 0) ); EditorGUILayout.EndHorizontal(); if( m_refocusLODValueMasterNodes ) { m_refocusLODValueMasterNodes = false; string focusedControl = GUI.GetNameOfFocusedControl(); if( focusedControl.Contains( LodValueId ) ) { GUI.FocusControl( LodValueId + m_lodIndex ); TextEditor te = (TextEditor)GUIUtility.GetStateObject( typeof( TextEditor ), GUIUtility.keyboardControl ); if( te != null ) { te.SelectTextEnd(); } } else if( focusedControl.Contains( LodNameId ) ) { GUI.FocusControl( LodNameId + m_lodIndex ); TextEditor te = (TextEditor)GUIUtility.GetStateObject( typeof( TextEditor ), GUIUtility.keyboardControl ); if( te != null ) { te.SelectTextEnd(); } } } } void DrawLOD() { if( m_templateMultiPass.CanAddLODs && m_lodIndex == -1 ) { EditorGUILayout.Space(); DrawLodRowItem(true); EditorGUILayout.Space(); for( int i = 0; i < ContainerGraph.LodMultiPassMasternodes.Count; i++ ) { if( ContainerGraph.LodMultiPassMasternodes[ i ].NodesList.Count > 0 ) { TemplateMultiPassMasterNode masterNode = m_containerGraph.LodMultiPassMasternodes[ i ].NodesList[ m_passIdx ]; masterNode.DrawLodRowItem( true ); EditorGUILayout.Space(); } } EditorGUILayout.Space(); } } void DrawCommonProperties() { if( m_isMainOutputNode ) { //if( m_templateMultiPass.CanAddLODs && m_lodIndex == -1 ) //{ // if( GUILayoutButton( string.Empty, UIUtils.PlusStyle, GUILayout.Width( 15 ) ) ) // { // ContainerGraph.CreateLodMasterNodes( m_templateMultiPass, Vec2Position ); // } // if( GUILayoutButton( string.Empty, UIUtils.MinusStyle, GUILayout.Width( 15 ) ) ) // { // ContainerGraph.DestroyLodMasterNodes(); // } //} //EditorGUILayout.LabelField( "LOD: " + m_lodIndex ); DrawShaderName(); DrawCurrentShaderType(); if( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.SRPIsPBRHD ) { if( m_templateMultiPass.CustomTemplatePropertyUI == CustomTemplatePropertyUIEnum.HDPBR ) { EditorGUI.BeginChangeCheck(); CurrentHDMaterialType = (HDSRPMaterialType)EditorGUILayoutEnumPopup( HDSRPMaterialTypeStr, m_hdSrpMaterialType ); if( EditorGUI.EndChangeCheck() ) ConfigHDPorts(); } } EditorGUI.BeginChangeCheck(); DrawPrecisionProperty( false ); if( EditorGUI.EndChangeCheck() ) ContainerGraph.CurrentPrecision = m_currentPrecisionType; EditorGUI.BeginChangeCheck(); DrawSamplingMacros(); if( EditorGUI.EndChangeCheck() ) ContainerGraph.SamplingMacros = SamplingMacros; m_drawInstancedHelper.Draw( this ); m_fallbackHelper.Draw( this ); DrawCustomInspector( m_templateMultiPass.SRPtype != TemplateSRPType.BuiltIn ); m_subShaderOptions.DrawCustomOptions( this ); m_dependenciesHelper.Draw( this, true ); } //EditorGUILayout.LabelField( m_subShaderIdxStr ); //EditorGUILayout.LabelField( m_passIdxStr ); if( IsLODMainMasterNode && m_templateMultiPass.CanAddLODs ) { NodeUtils.DrawNestedPropertyGroup( ref m_lodFoldout, AdditionalLODsStr, DrawLOD, DrawLODAddRemoveButtons ); } DrawOpenTemplateButton(); if( DebugConsoleWindow.DeveloperMode ) DrawReloadButton(); } public void DrawSubShaderProperties() { if( !m_isMainOutputNode ) { m_mainMasterNodeRef.DrawSubShaderProperties(); return; } bool noValidData = true; if( ShaderLOD > 0 ) { noValidData = false; if( m_templateMultiPass.CanAddLODs && m_containerGraph.LodMultiPassMasternodes[0].Count > 0 ) { DrawLodRowItem( false ); } else { ShaderLOD = EditorGUILayoutIntField( SubShaderLODValueLabel, ShaderLOD ); } } if( m_subShaderModule.HasValidData ) { noValidData = false; m_subShaderModule.Draw( this, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Modules ); //if( m_subShaderModule.IsDirty ) //{ // List<TemplateMultiPassMasterNode> mpNodes = UIUtils.CurrentWindow.CurrentGraph.MultiPassMasterNodes.NodesList; // int count = mpNodes.Count; // for( int i = 0; i < count; i++ ) // { // if( mpNodes[ i ].SubShaderIdx == m_subShaderIdx && mpNodes[ i ].UniqueId != UniqueId ) // { // mpNodes[ i ].SubShaderModule.CopyFrom( m_subShaderModule ); // } // } // m_subShaderModule.IsDirty = false; //} } m_passSelector.Draw( this ); if( noValidData ) { EditorGUILayout.HelpBox( NoSubShaderPropertyStr, MessageType.Info ); } } void DrawPassProperties() { EditorGUI.BeginChangeCheck(); m_passName = EditorGUILayoutTextField( PassNameStr, m_passName ); if( EditorGUI.EndChangeCheck() ) { if( m_passName.Length > 0 ) { m_passName = UIUtils.RemoveShaderInvalidCharacters( m_passName ); } else { m_passName = m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].PassNameContainer.Data; } //if( !m_templateMultiPass.IsSinglePass ) // SetClippedTitle( m_passName ); } EditorGUILayout.LabelField( Pass.Modules.PassUniqueName ); if( m_passModule.HasValidData ) { m_passModule.Draw( this, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules, m_subShaderModule ); } m_usePass.Draw( this, false ); m_passOptions.DrawCustomOptions( this ); } bool CreateInstructionsForList( TemplateData templateData, ref List<InputPort> ports, ref string shaderBody, ref List<string> vertexInstructions, ref List<string> fragmentInstructions ) { if( ports.Count == 0 ) return true; AddHDKeywords(); bool isValid = true; //UIUtils.CurrentWindow.CurrentGraph.ResetNodesLocalVariables(); for( int i = 0; i < ports.Count; i++ ) { TemplateInputData inputData = templateData.InputDataFromId( ports[ i ].PortId ); if( ports[ i ].HasOwnOrLinkConnection ) { //if( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Modules.SRPType == TemplateSRPType.Lightweight ) //{ // if( ports[ i ].Name.Contains( "Normal" ) ) // { // m_currentDataCollector.AddToDirectives( SRPMaterialNormalMapKeyword, -1, AdditionalLineType.Define ); // } // if( ports[ i ].Name.Contains( "Alpha Clip Threshold" ) ) // { // m_currentDataCollector.AddToDirectives( SRPMaterialBlendModeAlphaClipThresholdKeyword, -1, AdditionalLineType.Define ); // } // if( ports[ i ].Name.Contains( "Specular" ) ) // { // m_currentDataCollector.AddToDirectives( SRPLWMaterialSpecularKeyword, -1, AdditionalLineType.Define ); // } //} //else if( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Modules.SRPType == TemplateSRPType.HD ) //{ // if( ports[ i ].Name.Contains( "Normal" ) ) // { // //m_currentDataCollector.AddToDefines( UniqueId, SRPMaterialNormalMapKeyword ); // } // if( ports[ i ].Name.Contains( "Alpha Clip Threshold" ) ) // { // //m_currentDataCollector.AddToDefines( UniqueId, SRPMaterialAlphaTestKeyword ); // } //} m_currentDataCollector.ResetInstructions(); m_currentDataCollector.ResetVertexInstructions(); m_currentDataCollector.PortCategory = ports[ i ].Category; string newPortInstruction = ports[ i ].GeneratePortInstructions( ref m_currentDataCollector ); if( m_currentDataCollector.DirtySpecialLocalVariables ) { string cleanVariables = m_currentDataCollector.SpecialLocalVariables.Replace( "\t", string.Empty ); m_currentDataCollector.AddInstructions( cleanVariables, false ); m_currentDataCollector.ClearSpecialLocalVariables(); } if( m_currentDataCollector.DirtyVertexVariables ) { string cleanVariables = m_currentDataCollector.VertexLocalVariables.Replace( "\t", string.Empty ); m_currentDataCollector.AddVertexInstruction( cleanVariables, UniqueId, false ); m_currentDataCollector.ClearVertexLocalVariables(); } // fill functions for( int j = 0; j < m_currentDataCollector.InstructionsList.Count; j++ ) { fragmentInstructions.Add( m_currentDataCollector.InstructionsList[ j ].PropertyName ); } for( int j = 0; j < m_currentDataCollector.VertexDataList.Count; j++ ) { vertexInstructions.Add( m_currentDataCollector.VertexDataList[ j ].PropertyName ); } m_templateMultiPass.SetPassInputData( m_subShaderIdx, m_passIdx, ports[ i ].PortId, newPortInstruction ); isValid = m_templateMultiPass.FillTemplateBody( m_subShaderIdx, m_passIdx, inputData.TagId, ref shaderBody, newPortInstruction ) && isValid; } else { m_templateMultiPass.SetPassInputData( m_subShaderIdx, m_passIdx, ports[ i ].PortId, inputData.DefaultValue ); isValid = m_templateMultiPass.FillTemplateBody( m_subShaderIdx, m_passIdx, inputData.TagId, ref shaderBody, inputData.DefaultValue ) && isValid; } } return isValid; } public string BuildShaderBody( MasterNodeDataCollector inDataCollector, ref MasterNodeDataCollector outDataCollector ) { List<TemplateMultiPassMasterNode> list = UIUtils.CurrentWindow.CurrentGraph.MultiPassMasterNodes.NodesList; int currentSubshader = list[ 0 ].SubShaderIdx; m_templateMultiPass.SetShaderName( string.Format( TemplatesManager.NameFormatter, m_shaderName ) ); if( string.IsNullOrEmpty( m_customInspectorName ) ) { m_templateMultiPass.SetCustomInspector( string.Empty ); } else { m_templateMultiPass.SetCustomInspector( CustomInspectorFormatted ); } m_templateMultiPass.SetFallback( m_fallbackHelper.FallbackShader ); m_templateMultiPass.SetDependencies( m_dependenciesHelper.GenerateDependencies() ); if( inDataCollector != null ) outDataCollector.CopyPropertiesFromDataCollector( inDataCollector ); outDataCollector.TemplateDataCollectorInstance.CurrentSRPType = m_templateMultiPass.SRPtype; int lastActivePass = m_passSelector.LastActivePass; int count = list.Count; for( int i = 0; i < count; i++ ) { bool removePass = !m_passSelector.IsVisible( i ); list[ 0 ].CurrentTemplate.IdManager.SetPassIdUsage( i, removePass ); if( removePass ) continue; list[ i ].CollectData(); list[ i ].FillPassData( this, outDataCollector.TemplateDataCollectorInstance ); if( list[ i ].SubShaderIdx == currentSubshader ) { outDataCollector.CopyPropertiesFromDataCollector( list[ i ].CurrentDataCollector ); } else { list[ i - 1 ].FillPropertyData( outDataCollector ); list[ i - 1 ].FillSubShaderData(); outDataCollector.Destroy(); outDataCollector = new MasterNodeDataCollector(); outDataCollector.CopyPropertiesFromDataCollector( list[ i ].CurrentDataCollector ); currentSubshader = list[ i ].SubShaderIdx; } // Last element must the one filling subshader data // as only there all properties are caught //if( i == ( count - 1 ) ) if( i == lastActivePass ) { list[ i ].FillPropertyData( outDataCollector ); } if( list[ i ].IsMainOutputNode ) list[ i ].FillSubShaderData(); } outDataCollector.TemplateDataCollectorInstance.BuildCBuffer( -1 ); //Fill uniforms is set on last since we need to collect all srp batcher data ( if needed ) //To set it into each pass for( int i = 0; i < count; i++ ) { bool removePass = !m_passSelector.IsVisible( i ); if( removePass ) continue; list[ i ].FillUniforms( outDataCollector.TemplateDataCollectorInstance ); } return list[ 0 ].CurrentTemplate.IdManager.BuildShader(); } public string BuildLOD( MasterNodeDataCollector inDataCollector, ref MasterNodeDataCollector outDataCollector ) { UsageListTemplateMultiPassMasterNodes bufferNodesList = ContainerGraph.MultiPassMasterNodes; int bufferMasterNodeId = ContainerGraph.CurrentMasterNodeId; ContainerGraph.MultiPassMasterNodes = ContainerGraph.LodMultiPassMasternodes[ m_lodIndex ]; ContainerGraph.CurrentMasterNodeId = UniqueId; m_templateMultiPass.ResetState(); base.Execute( string.Empty, false ); string shaderBody = BuildShaderBody( inDataCollector, ref outDataCollector ); ContainerGraph.MultiPassMasterNodes = bufferNodesList; ContainerGraph.CurrentMasterNodeId = bufferMasterNodeId; return shaderBody; } public override Shader Execute( string pathname, bool isFullPath ) { ForceReordering(); MasterNodeDataCollector overallDataCollector = new MasterNodeDataCollector(); //BUILD LOD string allLodSubShaders = string.Empty; if( ContainerGraph.HasLODs ) { for( int lod = 0; lod < ContainerGraph.LodMultiPassMasternodes.Count; lod++ ) { if( ContainerGraph.LodMultiPassMasternodes[ lod ].Count == 0 ) break; TemplateMultiPassMasterNode newMasterNode = ContainerGraph.LodMultiPassMasternodes[ lod ].NodesList.Find( ( x ) => x.IsMainOutputNode ); string lodSubShaders = newMasterNode.BuildLOD( null, ref overallDataCollector ); lodSubShaders = TemplateHelperFunctions.GetSubShaderFrom( lodSubShaders ) + "\n"; allLodSubShaders += lodSubShaders; } } //BUILD MAIN m_templateMultiPass.ResetState(); base.Execute( pathname, isFullPath ); MasterNodeDataCollector dummy = new MasterNodeDataCollector(); string shaderBody = BuildShaderBody( overallDataCollector, ref dummy ); //COMBINE LOD WITH MAIN if( !string.IsNullOrEmpty( allLodSubShaders ) ) shaderBody = shaderBody.Replace( TemplatesManager.TemplateLODsTag, allLodSubShaders ); UpdateShaderAsset( ref pathname, ref shaderBody, isFullPath ); return m_currentShader; } public void CollectData() { if( m_inputPorts.Count == 0 ) return; ContainerGraph.ResetNodesLocalVariables(); m_optionsDefineContainer.RemoveTemporaries(); m_currentDataCollector = new MasterNodeDataCollector( this ); m_currentDataCollector.TemplateDataCollectorInstance.SetMultipassInfo( m_templateMultiPass, m_subShaderIdx, m_passIdx, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Modules.SRPType ); m_currentDataCollector.TemplateDataCollectorInstance.FillSpecialVariables( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ] ); SetupNodeCategories(); if( m_containerGraph.IsInstancedShader ) { string blockName = UIUtils.RemoveInvalidCharacters( ContainerGraph.GetMainMasterNodeOfLOD( -1 ).ShaderName ); m_currentDataCollector.SetupInstancePropertiesBlock( blockName ); } TemplateData templateData = m_templateMultiPass.CreateTemplateData( m_shaderName, string.Empty, m_subShaderIdx, m_passIdx ); m_currentDataCollector.TemplateDataCollectorInstance.BuildFromTemplateData( m_currentDataCollector, templateData ); if( m_currentDataCollector.TemplateDataCollectorInstance.InterpData.DynamicMax ) { int interpolatorAmount = -1; if( m_passModule.ShaderModelHelper.ValidData ) { interpolatorAmount = m_passModule.ShaderModelHelper.InterpolatorAmount; } else { TemplateModulesHelper subShaderModule = IsMainOutputNode ? m_subShaderModule : ( m_containerGraph.CurrentMasterNode as TemplateMultiPassMasterNode ).SubShaderModule; if( subShaderModule.ShaderModelHelper.ValidData ) { interpolatorAmount = subShaderModule.ShaderModelHelper.InterpolatorAmount; } } if( interpolatorAmount > -1 ) { m_currentDataCollector.TemplateDataCollectorInstance.InterpData.RecalculateAvailableInterpolators( interpolatorAmount ); } } //Copy Properties { int shaderPropertiesAmount = m_templateMultiPass.AvailableShaderProperties.Count; for( int i = 0; i < shaderPropertiesAmount; i++ ) { m_currentDataCollector.SoftRegisterUniform( m_templateMultiPass.AvailableShaderProperties[ i ] ); } } //Copy Globals from SubShader level { int subShaderGlobalAmount = m_templateMultiPass.SubShaders[ m_subShaderIdx ].AvailableShaderGlobals.Count; for( int i = 0; i < subShaderGlobalAmount; i++ ) { m_currentDataCollector.SoftRegisterUniform( m_templateMultiPass.SubShaders[ m_subShaderIdx ].AvailableShaderGlobals[ i ] ); } } //Copy Globals from Pass Level { int passGlobalAmount = m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].AvailableShaderGlobals.Count; for( int i = 0; i < passGlobalAmount; i++ ) { m_currentDataCollector.SoftRegisterUniform( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].AvailableShaderGlobals[ i ] ); } } // Check Current Options for property changes on subshader if( m_isMainOutputNode ) { CheckPropertyChangesOnOptions( m_subShaderOptions ); } // Check Current Options for property changes on pass CheckPropertyChangesOnOptions( m_passOptions ); //Set SRP info #if UNITY_2018_3_OR_NEWER if( m_templateMultiPass.SRPtype != TemplateSRPType.BuiltIn ) ASEPackageManagerHelper.SetSRPInfoOnDataCollector( ref m_currentDataCollector ); #endif RegisterStandaloneFuntions(); m_containerGraph.CheckPropertiesAutoRegister( ref m_currentDataCollector ); //Sort ports by both List<InputPort> fragmentPorts = new List<InputPort>(); List<InputPort> vertexPorts = new List<InputPort>(); SortInputPorts( ref vertexPorts, ref fragmentPorts ); string shaderBody = templateData.TemplateBody; List<string> vertexInstructions = new List<string>(); List<string> fragmentInstructions = new List<string>(); bool validBody = true; //validBody = CreateInstructionsForList( templateData, ref fragmentPorts, ref shaderBody, ref vertexInstructions, ref fragmentInstructions ) && validBody; //ContainerGraph.ResetNodesLocalVariablesIfNot( MasterNodePortCategory.Vertex ); //validBody = CreateInstructionsForList( templateData, ref vertexPorts, ref shaderBody, ref vertexInstructions, ref fragmentInstructions ) && validBody; validBody = CreateInstructionsForList( templateData, ref vertexPorts, ref shaderBody, ref vertexInstructions, ref fragmentInstructions ) && validBody; validBody = CreateInstructionsForList( templateData, ref fragmentPorts, ref shaderBody, ref vertexInstructions, ref fragmentInstructions ) && validBody; if( !m_isMainOutputNode && m_mainMasterNodeRef == null ) { m_mainMasterNodeRef = m_containerGraph.CurrentMasterNode as TemplateMultiPassMasterNode; } TerrainDrawInstancedHelper drawInstanced = m_isMainOutputNode ? m_drawInstancedHelper : m_mainMasterNodeRef.DrawInstancedHelperInstance; drawInstanced.UpdateDataCollectorForTemplates( ref m_currentDataCollector, ref vertexInstructions ); templateData.ResetTemplateUsageData(); // Fill vertex interpolators assignment for( int i = 0; i < m_currentDataCollector.VertexInterpDeclList.Count; i++ ) { vertexInstructions.Add( m_currentDataCollector.VertexInterpDeclList[ i ] ); } vertexInstructions.AddRange( m_currentDataCollector.TemplateDataCollectorInstance.GetInterpUnusedChannels() ); //Fill common local variables and operations validBody = m_templateMultiPass.FillVertexInstructions( m_subShaderIdx, m_passIdx, vertexInstructions.ToArray() ) && validBody; validBody = m_templateMultiPass.FillFragmentInstructions( m_subShaderIdx, m_passIdx, fragmentInstructions.ToArray() ) && validBody; vertexInstructions.Clear(); vertexInstructions = null; fragmentInstructions.Clear(); fragmentInstructions = null; // Add Instanced Properties if( m_containerGraph.IsInstancedShader ) { m_currentDataCollector.OptimizeInstancedProperties(); m_currentDataCollector.TabifyInstancedVars(); //string cbufferBegin = m_currentDataCollector.IsSRP ? // string.Format( IOUtils.SRPInstancedPropertiesBegin, "UnityPerMaterial" ) : // string.Format( IOUtils.InstancedPropertiesBegin, m_currentDataCollector.InstanceBlockName ); //string cBufferEnd = m_currentDataCollector.IsSRP ? ( string.Format( IOUtils.SRPInstancedPropertiesEnd, m_currentDataCollector.InstanceBlockName ) ) : IOUtils.InstancedPropertiesEnd; string cbufferBegin = m_currentDataCollector.IsSRP ? string.Format( IOUtils.LWSRPInstancedPropertiesBegin, m_currentDataCollector.InstanceBlockName ) : string.Format( IOUtils.InstancedPropertiesBegin, m_currentDataCollector.InstanceBlockName ); string cBufferEnd = m_currentDataCollector.IsSRP ? ( string.Format( IOUtils.LWSRPInstancedPropertiesEnd, m_currentDataCollector.InstanceBlockName ) ) : IOUtils.InstancedPropertiesEnd; m_currentDataCollector.InstancedPropertiesList.Insert( 0, new PropertyDataCollector( -1, cbufferBegin ) ); m_currentDataCollector.InstancedPropertiesList.Add( new PropertyDataCollector( -1, cBufferEnd ) ); m_currentDataCollector.UniformsList.AddRange( m_currentDataCollector.InstancedPropertiesList ); } if( m_currentDataCollector.DotsPropertiesList.Count > 0 ) { m_currentDataCollector.DotsPropertiesList.Insert( 0, new PropertyDataCollector( -1, "UNITY_DOTS_INSTANCING_START(MaterialPropertyMetadata)" ) ); m_currentDataCollector.DotsPropertiesList.Insert( 0, new PropertyDataCollector( -1, "#ifdef UNITY_DOTS_INSTANCING_ENABLED" ) ); m_currentDataCollector.DotsPropertiesList.Insert( 0, new PropertyDataCollector( -1, "" ) ); m_currentDataCollector.DotsPropertiesList.Add( new PropertyDataCollector( -1, "UNITY_DOTS_INSTANCING_END(MaterialPropertyMetadata)" ) ); m_currentDataCollector.DotsDefinesList.Add( new PropertyDataCollector( -1, "#endif" ) ); m_currentDataCollector.UniformsList.AddRange( m_currentDataCollector.DotsPropertiesList ); m_currentDataCollector.UniformsList.AddRange( m_currentDataCollector.DotsDefinesList ); } TemplateShaderModelModule shaderModelModule = m_isMainOutputNode ? m_subShaderModule.ShaderModelHelper : m_mainMasterNodeRef.SubShaderModule.ShaderModelHelper; string shaderModel = string.Empty; if( m_passModule.ShaderModelHelper.ValidData ) { shaderModel = m_passModule.ShaderModelHelper.CurrentShaderModel; } else if( shaderModelModule.ValidData ) { shaderModel = shaderModelModule.CurrentShaderModel; } else if( m_templateMultiPass.GlobalShaderModel.IsValid ) { shaderModel = m_templateMultiPass.GlobalShaderModel.Value; } else { shaderModel = ( m_templateMultiPass.SRPtype == TemplateSRPType.HD ) ? "4.5" : "3.0"; } m_currentDataCollector.TemplateDataCollectorInstance.CheckInterpolatorOverflow( shaderModel, m_passName ); } public void CheckPropertyChangesOnOptions( TemplateOptionsUIHelper optionsUI ) { //Only Main LOD master node can change shader properties if( !IsLODMainMasterNode ) return; List<TemplateOptionUIItem> options = optionsUI.PassCustomOptionsUI; for( int optionIdx = 0; optionIdx < options.Count; optionIdx++ ) { if( options[ optionIdx ].IsVisible ) { TemplateActionItem[] actionItems = options[ optionIdx ].CurrentOptionActions.Columns; for( int actionIdx = 0; actionIdx < actionItems.Length; actionIdx++ ) { if( actionItems[ actionIdx ].ActionType == AseOptionsActionType.SetShaderProperty && !string.IsNullOrEmpty( actionItems[ actionIdx ].ActionBuffer ) ) { TemplateShaderPropertyData data = m_templateMultiPass.GetShaderPropertyData( actionItems[ actionIdx ].ActionData ); if( data != null ) { string newPropertyValue = data.CreatePropertyForValue( actionItems[ actionIdx ].ActionBuffer ); CurrentTemplate.IdManager.SetReplacementText( data.FullValue, newPropertyValue ); } } } if( options[ optionIdx ].Options.Type == AseOptionsType.Field ) { foreach( var item in CurrentTemplate.IdManager.RegisteredTags ) { if( item.Output.Equals( options[ optionIdx ].Options.FieldInlineName ) ) { var node = options[ optionIdx ].Options.FieldValue.GetPropertyNode(); if( node != null && ( node.IsConnected || node.AutoRegister ) && options[ optionIdx ].Options.FieldValue.Active ) { item.Replacement = node.PropertyName; } } } } } } } public void FillPropertyData( MasterNodeDataCollector dataCollector = null ) { MasterNodeDataCollector currDataCollector = ( dataCollector == null ) ? m_currentDataCollector : dataCollector; #if UNITY_2019_2_OR_NEWER // Temporary hack if( m_templateMultiPass.SRPtype != TemplateSRPType.BuiltIn && ASEPackageManagerHelper.CurrentHDVersion > ASESRPVersions.ASE_SRP_6_9_0 ) { if( m_templateMultiPass.AvailableShaderProperties.Find( x => x.PropertyName.Equals( "_AlphaCutoff" ) ) == null ) { if( !currDataCollector.ContainsProperty("_AlphaCutoff") ) { currDataCollector.AddToProperties( UniqueId, "[HideInInspector] _AlphaCutoff(\"Alpha Cutoff \", Range(0, 1)) = 0.5", -1 ); } } if( m_templateMultiPass.AvailableShaderProperties.Find( x => x.PropertyName.Equals( "_EmissionColor" ) ) == null ) { if( !currDataCollector.ContainsProperty( "_EmissionColor" ) ) { currDataCollector.AddToProperties( UniqueId, "[HideInInspector] _EmissionColor(\"Emission Color\", Color) = (1,1,1,1)", -1 ); } } } #endif m_templateMultiPass.SetPropertyData( currDataCollector.BuildUnformatedPropertiesStringArr() ); } public void FillSubShaderData( /*MasterNodeDataCollector dataCollector = null */) { //MasterNodeDataCollector currDataCollector = ( dataCollector == null ) ? m_currentDataCollector : dataCollector; //// SubShader Data //m_templateMultiPass.SetPropertyData( currDataCollector.BuildUnformatedPropertiesStringArr() ); //templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModulePass, m_subShaderIdx, currDataCollector.GrabPassList ); if( ShaderLOD > -1 ) { string lodUniqueId = m_templateMultiPass.SubShaders[ m_subShaderIdx ].UniquePrefix + "Module" + m_templateMultiPass.SubShaders[ m_subShaderIdx ].LODContainer.Id; m_templateMultiPass.IdManager.SetReplacementText( lodUniqueId, "LOD " + ShaderLOD ); } SetModuleData( m_subShaderModule, true ); } public void FillPassData( TemplateMultiPassMasterNode masterNode, TemplateDataCollector mainTemplateDataCollector ) { if( m_isInvisible != InvisibilityStatus.Visible ) { if( masterNode.UniqueId != UniqueId ) { if( ( m_invisibleOptions & (int)InvisibleOptionsEnum.SyncProperties ) > 0 ) { PassModule.SyncWith( masterNode.PassModule ); } } int inputCount = m_inputPorts.Count; for( int i = 0; i < inputCount; i++ ) { if( m_inputPorts[ i ].HasExternalLink ) { TemplateMultiPassMasterNode linkedNode = m_inputPorts[ i ].ExternalLinkNode as TemplateMultiPassMasterNode; if( linkedNode != null ) { SetLinkedModuleData( linkedNode.PassModule ); } } } } SetModuleData( m_passModule, false ); if( m_currentDataCollector != null ) { if( Pass.CustomOptionsContainer.CopyOptionsFromMainPass ) { SetPassCustomOptionsInfo( m_containerGraph.CurrentMasterNode as TemplateMultiPassMasterNode ); } else { SetPassCustomOptionsInfo( this ); } var inputArray = m_currentDataCollector.VertexInputList.ToArray(); m_templateMultiPass.SetPassData( TemplateModuleDataType.PassVertexData, m_subShaderIdx, m_passIdx, inputArray ); m_templateMultiPass.SetPassData( TemplateModuleDataType.PassInterpolatorData, m_subShaderIdx, m_passIdx, m_currentDataCollector.InterpolatorList.ToArray() ); SetHDInfoOnPass(); List<PropertyDataCollector> afterNativesIncludePragmaDefineList = new List<PropertyDataCollector>(); afterNativesIncludePragmaDefineList.AddRange( m_currentDataCollector.IncludesList ); afterNativesIncludePragmaDefineList.AddRange( m_currentDataCollector.DefinesList ); //includePragmaDefineList.AddRange( m_optionsDefineContainer.DefinesList ); afterNativesIncludePragmaDefineList.AddRange( m_currentDataCollector.PragmasList ); m_currentDataCollector.AddASEMacros(); afterNativesIncludePragmaDefineList.AddRange( m_currentDataCollector.AfterNativeDirectivesList ); //includePragmaDefineList.AddRange( m_currentDataCollector.MiscList ); List<PropertyDataCollector> beforeNatives = new List<PropertyDataCollector>(); beforeNatives.AddRange( m_optionsDefineContainer.DefinesList ); beforeNatives.AddRange( m_currentDataCollector.BeforeNativeDirectivesList ); m_templateMultiPass.SetPassData( TemplateModuleDataType.ModulePragmaBefore, m_subShaderIdx, m_passIdx, beforeNatives ); m_templateMultiPass.SetPassData( TemplateModuleDataType.ModulePragma, m_subShaderIdx, m_passIdx, afterNativesIncludePragmaDefineList ); m_currentDataCollector.TemplateDataCollectorInstance.CloseLateDirectives(); //Add Functions if( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.FunctionsTag.IsValid ) { m_currentDataCollector.FunctionsList.InsertRange( 0, m_currentDataCollector.TemplateDataCollectorInstance.LateDirectivesList ); m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleFunctions, m_subShaderIdx, m_passIdx, m_currentDataCollector.FunctionsList ); } else { m_currentDataCollector.UniformsList.InsertRange( 0, m_currentDataCollector.TemplateDataCollectorInstance.LateDirectivesList ); m_currentDataCollector.UniformsList.AddRange( m_currentDataCollector.FunctionsList ); } //copy srp batch if present //if( m_currentDataCollector.IsSRP ) //{ // m_currentDataCollector.UniformsList.AddRange( mainTemplateDataCollector.SrpBatcherPropertiesList ); //} //m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleGlobals, m_subShaderIdx, m_passIdx, m_currentDataCollector.UniformsList ); m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleInputVert, m_subShaderIdx, m_passIdx, m_currentDataCollector.TemplateDataCollectorInstance.VertexInputParamsStr ); m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleInputFrag, m_subShaderIdx, m_passIdx, m_currentDataCollector.TemplateDataCollectorInstance.FragInputParamsStr ); if( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].TessVControlTag != null && m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].TessVControlTag.IsValid ) m_templateMultiPass.SetPassData( TemplateModuleDataType.VControl, m_subShaderIdx, m_passIdx, inputArray ); if( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].TessControlData != null && m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].TessControlData.IsValid ) m_templateMultiPass.SetPassData( TemplateModuleDataType.ControlData, m_subShaderIdx, m_passIdx, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].TessControlData.GenerateControl( m_currentDataCollector.TemplateDataCollectorInstance.VertexDataDict, m_currentDataCollector.VertexInputList ) ); if( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].TessDomainData != null && m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].TessDomainData.IsValid ) m_templateMultiPass.SetPassData( TemplateModuleDataType.DomainData, m_subShaderIdx, m_passIdx, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].TessDomainData.GenerateDomain( m_currentDataCollector.TemplateDataCollectorInstance.VertexDataDict, m_currentDataCollector.VertexInputList ) ); afterNativesIncludePragmaDefineList.Clear(); afterNativesIncludePragmaDefineList = null; beforeNatives.Clear(); beforeNatives = null; } m_templateMultiPass.SetPassData( TemplateModuleDataType.PassNameData, m_subShaderIdx, m_passIdx, string.Format( PassNameFormateStr, m_passName ) ); } public List<PropertyDataCollector> CrossCheckSoftRegisteredUniformList( List<PropertyDataCollector> uniformList ) { List<PropertyDataCollector> newItems = new List<PropertyDataCollector>(); for( int i = 0; i < uniformList.Count; i++ ) { if( !m_currentDataCollector.CheckIfSoftRegistered( uniformList[ i ].PropertyName ) ) { newItems.Add( uniformList[ i ] ); } } return newItems; } public void FillUniforms( TemplateDataCollector mainTemplateDataCollector ) { if( m_currentDataCollector.IsSRP ) { if( m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.SRPBatcherTag.IsValid ) { List<PropertyDataCollector> finalList = CrossCheckSoftRegisteredUniformList( mainTemplateDataCollector.SrpBatcherPropertiesList ); m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleSRPBatcher, m_subShaderIdx, m_passIdx, finalList ); finalList.Clear(); finalList = null; } else { List<PropertyDataCollector> finalList = CrossCheckSoftRegisteredUniformList( mainTemplateDataCollector.FullSrpBatcherPropertiesList ); m_currentDataCollector.UniformsList.AddRange( finalList ); finalList.Clear(); finalList = null; } } m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleGlobals, m_subShaderIdx, m_passIdx, m_currentDataCollector.UniformsList ); } void SetHDInfoOnPass() { #if UNITY_2019_3_OR_NEWER if( ASEPackageManagerHelper.CurrentHDVersion > ASESRPVersions.ASE_SRP_6_9_1 ) return; #endif if( m_currentDataCollector.TemplateDataCollectorInstance.CurrentSRPType == TemplateSRPType.HD ) { TemplateModulesHelper subShaderHelper = null; TemplateModulesHelper passHelper = null; if( m_isMainOutputNode ) { subShaderHelper = m_subShaderModule; passHelper = m_passModule; } else { TemplateMultiPassMasterNode masterNode = m_containerGraph.CurrentMasterNode as TemplateMultiPassMasterNode; if( masterNode != null ) { subShaderHelper = masterNode.SubShaderModule; passHelper = masterNode.PassModule; } else { subShaderHelper = m_subShaderModule; passHelper = m_passModule; } } RenderQueue renderQueue = RenderQueue.Geometry; RenderType renderType = RenderType.Opaque; if( passHelper.TagsHelper.HasRenderInfo( ref renderType, ref renderQueue ) || subShaderHelper.TagsHelper.HasRenderInfo( ref renderType, ref renderQueue ) ) { if( renderType == RenderType.Transparent && renderQueue == RenderQueue.Transparent ) { SetExtraDefine( SRPMaterialTransparentKeyword ); //m_currentDataCollector.AddToDefines( UniqueId, SRPMaterialTransparentKeyword ); TemplatesBlendModule blendOpHelper = passHelper.BlendOpHelper.ValidBlendMode ? passHelper.BlendOpHelper : subShaderHelper.BlendOpHelper; if( blendOpHelper.IsAdditiveRGB ) { SetExtraDefine( SRPMaterialBlendModeAddKeyword ); //m_currentDataCollector.AddToDefines( UniqueId, SRPMaterialBlendModeAddKeyword ); } else if( blendOpHelper.IsAlphaBlendRGB ) { SetExtraDefine( SRPMaterialBlendModeAlphaKeyword ); //m_currentDataCollector.AddToDefines( UniqueId, SRPMaterialBlendModeAlphaKeyword ); } } } } } void SetLinkedModuleData( TemplateModulesHelper linkedModule ) { //if( linkedModule.AdditionalPragmas.ValidData ) //{ // linkedModule.AdditionalPragmas.AddToDataCollector( ref m_currentDataCollector, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.IncludePragmaContainer ); //} //if( linkedModule.AdditionalIncludes.ValidData ) //{ // linkedModule.AdditionalIncludes.AddToDataCollector( ref m_currentDataCollector, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.IncludePragmaContainer ); //} //if( linkedModule.AdditionalDefines.ValidData ) //{ // linkedModule.AdditionalDefines.AddToDataCollector( ref m_currentDataCollector, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.IncludePragmaContainer ); //} if( linkedModule.AdditionalDirectives.ValidData ) { linkedModule.AdditionalDirectives.AddAllToDataCollector( ref m_currentDataCollector, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.IncludePragmaContainer ); } } void SetModuleData( TemplateModulesHelper module, bool isSubShader ) { if( isSubShader ) { //if ( module.AdditionalPragmas.ValidData ) //{ // module.AdditionalPragmas.AddToDataCollector( ref m_currentDataCollector, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Modules.IncludePragmaContainer ); //} //if ( module.AdditionalIncludes.ValidData ) //{ // module.AdditionalIncludes.AddToDataCollector( ref m_currentDataCollector, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Modules.IncludePragmaContainer ); //} //if ( module.AdditionalDefines.ValidData ) //{ // module.AdditionalDefines.AddToDataCollector( ref m_currentDataCollector, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Modules.IncludePragmaContainer ); //} if( module.AdditionalDirectives.ValidData ) { module.AdditionalDirectives.AddAllToDataCollector( ref m_currentDataCollector, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Modules.IncludePragmaContainer ); } if( module.TagsHelper.ValidData ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleTag, m_subShaderIdx, module.TagsHelper.GenerateTags() ); } if( module.AllModulesMode ) { string body = module.GenerateAllModulesString( isSubShader ); m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.AllModules, m_subShaderIdx, body.Split( '\n' ) ); } if( module.ShaderModelHelper.ValidAndIndependent ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleShaderModel, m_subShaderIdx, module.ShaderModelHelper.GenerateShaderData( isSubShader ) ); } if( module.BlendOpHelper.IndependentModule && module.BlendOpHelper.ValidBlendMode ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleBlendMode, m_subShaderIdx, module.BlendOpHelper.CurrentBlendFactor ); } if( module.BlendOpHelper1.IndependentModule && module.BlendOpHelper1.ValidBlendMode ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleBlendMode1, m_subShaderIdx, module.BlendOpHelper1.CurrentBlendFactor ); } if( module.BlendOpHelper2.IndependentModule && module.BlendOpHelper2.ValidBlendMode ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleBlendMode2, m_subShaderIdx, module.BlendOpHelper2.CurrentBlendFactor ); } if( module.BlendOpHelper3.IndependentModule && module.BlendOpHelper3.ValidBlendMode ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleBlendMode3, m_subShaderIdx, module.BlendOpHelper3.CurrentBlendFactor ); } if( module.BlendOpHelper.IndependentModule && module.BlendOpHelper.ValidBlendOp ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleBlendOp, m_subShaderIdx, module.BlendOpHelper.CurrentBlendOp ); } if( module.BlendOpHelper1.IndependentModule && module.BlendOpHelper1.ValidBlendOp ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleBlendOp1, m_subShaderIdx, module.BlendOpHelper1.CurrentBlendOp ); } if( module.BlendOpHelper2.IndependentModule && module.BlendOpHelper2.ValidBlendOp ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleBlendOp2, m_subShaderIdx, module.BlendOpHelper2.CurrentBlendOp ); } if( module.BlendOpHelper3.IndependentModule && module.BlendOpHelper3.ValidBlendOp ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleBlendOp3, m_subShaderIdx, module.BlendOpHelper3.CurrentBlendOp ); } if( module.AlphaToMaskHelper.ValidAndIndependent ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleAlphaToMask, m_subShaderIdx, module.AlphaToMaskHelper.GenerateShaderData( isSubShader ) ); } if( module.CullModeHelper.ValidAndIndependent ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleCullMode, m_subShaderIdx, module.CullModeHelper.GenerateShaderData( isSubShader ) ); } if( module.ColorMaskHelper.ValidAndIndependent ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleColorMask, m_subShaderIdx, module.ColorMaskHelper.GenerateShaderData( isSubShader ) ); } if( module.ColorMaskHelper1.ValidAndIndependent ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleColorMask1, m_subShaderIdx, module.ColorMaskHelper1.GenerateShaderData( isSubShader ) ); } if( module.ColorMaskHelper2.ValidAndIndependent ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleColorMask2, m_subShaderIdx, module.ColorMaskHelper2.GenerateShaderData( isSubShader ) ); } if( module.ColorMaskHelper3.ValidAndIndependent ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleColorMask3, m_subShaderIdx, module.ColorMaskHelper3.GenerateShaderData( isSubShader ) ); } if( module.DepthOphelper.IndependentModule && module.DepthOphelper.ValidZTest ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleZTest, m_subShaderIdx, module.DepthOphelper.CurrentZTestMode ); } if( module.DepthOphelper.IndependentModule && module.DepthOphelper.ValidZWrite ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleZwrite, m_subShaderIdx, module.DepthOphelper.CurrentZWriteMode ); } if( module.DepthOphelper.IndependentModule && module.DepthOphelper.ValidOffset ) { m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleZOffset, m_subShaderIdx, module.DepthOphelper.CurrentOffset ); } if( module.StencilBufferHelper.ValidAndIndependent ) { CullMode cullMode = ( module.CullModeHelper.ValidData ) ? module.CullModeHelper.CurrentCullMode : CullMode.Back; string value = module.StencilBufferHelper.CreateStencilOp( cullMode ); m_templateMultiPass.SetSubShaderData( TemplateModuleDataType.ModuleStencil, m_subShaderIdx, value.Split( '\n' ) ); } } else { //if ( module.AdditionalPragmas.ValidData ) //{ // module.AdditionalPragmas.AddToDataCollector( ref m_currentDataCollector, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.IncludePragmaContainer ); //} //if ( module.AdditionalIncludes.ValidData ) //{ // module.AdditionalIncludes.AddToDataCollector( ref m_currentDataCollector, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.IncludePragmaContainer ); //} //if ( module.AdditionalDefines.ValidData ) //{ // module.AdditionalDefines.AddToDataCollector( ref m_currentDataCollector, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.IncludePragmaContainer ); //} List<PropertyDataCollector> aboveUsePass = new List<PropertyDataCollector>(); List<PropertyDataCollector> belowUsePass = new List<PropertyDataCollector>(); m_usePass.BuildUsePassInfo( m_currentDataCollector, ref aboveUsePass, ref belowUsePass ); //TODO Must place this on the correct place aboveUsePass.AddRange( belowUsePass ); //adding grab pass after use pass on purpose, so it wont be caught by them aboveUsePass.AddRange( m_currentDataCollector.GrabPassList ); m_templateMultiPass.SetPassData( TemplateModuleDataType.ModulePass, m_subShaderIdx, m_passIdx, aboveUsePass ); //m_templateMultiPass.SetPassData( TemplateModuleDataType.EndPass, m_subShaderIdx, m_passIdx, bellowUsePass); if( module.AdditionalDirectives.ValidData ) { module.AdditionalDirectives.AddAllToDataCollector( ref m_currentDataCollector, m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.IncludePragmaContainer ); } if( module.TagsHelper.ValidData ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleTag, m_subShaderIdx, m_passIdx, module.TagsHelper.GenerateTags() ); } if( module.AllModulesMode ) { string body = module.GenerateAllModulesString( isSubShader ); m_templateMultiPass.SetPassData( TemplateModuleDataType.AllModules, m_subShaderIdx, m_passIdx, body.Split( '\n' ) ); } if( module.ShaderModelHelper.ValidAndIndependent ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleShaderModel, m_subShaderIdx, m_passIdx, module.ShaderModelHelper.GenerateShaderData( isSubShader ) ); } if( module.BlendOpHelper.IndependentModule && module.BlendOpHelper.ValidBlendMode ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleBlendMode, m_subShaderIdx, m_passIdx, module.BlendOpHelper.CurrentBlendFactor ); } if( module.BlendOpHelper1.IndependentModule && module.BlendOpHelper1.ValidBlendMode ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleBlendMode1, m_subShaderIdx, m_passIdx, module.BlendOpHelper1.CurrentBlendFactor ); } if( module.BlendOpHelper2.IndependentModule && module.BlendOpHelper2.ValidBlendMode ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleBlendMode2, m_subShaderIdx, m_passIdx, module.BlendOpHelper2.CurrentBlendFactor ); } if( module.BlendOpHelper3.IndependentModule && module.BlendOpHelper3.ValidBlendMode ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleBlendMode3, m_subShaderIdx, m_passIdx, module.BlendOpHelper3.CurrentBlendFactor ); } if( module.BlendOpHelper.IndependentModule && module.BlendOpHelper.ValidBlendOp ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleBlendOp, m_subShaderIdx, m_passIdx, module.BlendOpHelper.CurrentBlendOp ); } if( module.BlendOpHelper1.IndependentModule && module.BlendOpHelper1.ValidBlendOp ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleBlendOp1, m_subShaderIdx, m_passIdx, module.BlendOpHelper1.CurrentBlendOp ); } if( module.BlendOpHelper2.IndependentModule && module.BlendOpHelper2.ValidBlendOp ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleBlendOp2, m_subShaderIdx, m_passIdx, module.BlendOpHelper2.CurrentBlendOp ); } if( module.BlendOpHelper3.IndependentModule && module.BlendOpHelper3.ValidBlendOp ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleBlendOp3, m_subShaderIdx, m_passIdx, module.BlendOpHelper3.CurrentBlendOp ); } if( module.AlphaToMaskHelper.ValidAndIndependent ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleAlphaToMask, m_subShaderIdx, m_passIdx, module.AlphaToMaskHelper.GenerateShaderData( isSubShader ) ); } if( module.CullModeHelper.ValidAndIndependent ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleCullMode, m_subShaderIdx, m_passIdx, module.CullModeHelper.GenerateShaderData( isSubShader ) ); } if( module.ColorMaskHelper.ValidAndIndependent ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleColorMask, m_subShaderIdx, m_passIdx, module.ColorMaskHelper.GenerateShaderData( isSubShader ) ); } if( module.ColorMaskHelper1.ValidAndIndependent ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleColorMask1, m_subShaderIdx, m_passIdx, module.ColorMaskHelper1.GenerateShaderData( isSubShader ) ); } if( module.ColorMaskHelper2.ValidAndIndependent ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleColorMask2, m_subShaderIdx, m_passIdx, module.ColorMaskHelper2.GenerateShaderData( isSubShader ) ); } if( module.ColorMaskHelper3.ValidAndIndependent ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleColorMask3, m_subShaderIdx, m_passIdx, module.ColorMaskHelper3.GenerateShaderData( isSubShader ) ); } if( module.DepthOphelper.IndependentModule && module.DepthOphelper.ValidZTest ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleZTest, m_subShaderIdx, m_passIdx, module.DepthOphelper.CurrentZTestMode ); } if( module.DepthOphelper.IndependentModule && module.DepthOphelper.ValidZWrite ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleZwrite, m_subShaderIdx, m_passIdx, module.DepthOphelper.CurrentZWriteMode ); } if( module.DepthOphelper.IndependentModule && module.DepthOphelper.ValidOffset ) { m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleZOffset, m_subShaderIdx, m_passIdx, module.DepthOphelper.CurrentOffset ); } if( module.StencilBufferHelper.ValidAndIndependent ) { CullMode cullMode = ( module.CullModeHelper.ValidData ) ? module.CullModeHelper.CurrentCullMode : CullMode.Back; string value = module.StencilBufferHelper.CreateStencilOp( cullMode ); m_templateMultiPass.SetPassData( TemplateModuleDataType.ModuleStencil, m_subShaderIdx, m_passIdx, value.Split( '\n' ) ); } } } public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar ) { return "0"; } public override void Destroy() { base.Destroy(); m_drawInstancedHelper = null; m_optionsDefineContainer.Destroy(); m_optionsDefineContainer = null; m_passSelector.Destroy(); m_passSelector = null; m_subShaderOptions.Destroy(); m_passOptions.Destroy(); m_fallbackHelper.Destroy(); GameObject.DestroyImmediate( m_fallbackHelper ); m_fallbackHelper = null; m_usePass.Destroy(); GameObject.DestroyImmediate( m_usePass ); m_usePass = null; m_dependenciesHelper.Destroy(); m_dependenciesHelper = null; m_subShaderModule.Destroy(); m_subShaderModule = null; m_passModule.Destroy(); m_passModule = null; if( m_lodIndex == -1 ) { ContainerGraph.MultiPassMasterNodes.RemoveNode( this ); } else { ContainerGraph.LodMultiPassMasternodes[ m_lodIndex ].RemoveNode( this ); } } void UpdateSubShaderPassStr() { //m_subShaderIdxStr = SubShaderModuleStr + m_templateMultiPass.SubShaders[ m_subShaderIdx ].Idx; //m_passIdxStr = PassModuleStr + m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Idx; } public override void ReadFromString( ref string[] nodeParams ) { base.ReadFromString( ref nodeParams ); try { string currShaderName = GetCurrentParam( ref nodeParams ); if( currShaderName.Length > 0 ) currShaderName = UIUtils.RemoveShaderInvalidCharacters( currShaderName ); m_templateGUID = GetCurrentParam( ref nodeParams ); bool hasUniqueName = false; if( UIUtils.CurrentShaderVersion() > PASS_UNIQUE_ID_VERSION ) { hasUniqueName = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) ); } if( hasUniqueName ) m_passUniqueId = GetCurrentParam( ref nodeParams ); m_subShaderIdx = Convert.ToInt32( GetCurrentParam( ref nodeParams ) ); m_passIdx = Convert.ToInt32( GetCurrentParam( ref nodeParams ) ); if( UIUtils.CurrentShaderVersion() > LOD_SUBSHADER_VERSION ) { if( m_lodIndex != -1 ) { m_containerGraph.MultiPassMasterNodes.RemoveNode( this ); m_containerGraph.LodMultiPassMasternodes[ m_lodIndex ].AddNode( this ); } } m_passName = GetCurrentParam( ref nodeParams ); SetTemplate( null, false, true, m_subShaderIdx, m_passIdx, SetTemplateSource.ShaderLoad ); ////If value gotten from template is > -1 then it contains the LOD field ////and we can properly write the value //if( m_subShaderLOD > -1 ) //{ // m_subShaderLOD = subShaderLOD; //} // only in here, after SetTemplate, we know if shader name is to be used as title or not ShaderName = currShaderName; m_visiblePorts = Convert.ToInt32( GetCurrentParam( ref nodeParams ) ); m_subShaderModule.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); m_passModule.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); if( UIUtils.CurrentShaderVersion() > 15308 ) { m_fallbackHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); m_dependenciesHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); } if( UIUtils.CurrentShaderVersion() > 15402 ) { m_usePass.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); } if( UIUtils.CurrentShaderVersion() > 15409 ) { m_hdSrpMaterialType = (HDSRPMaterialType)Enum.Parse( typeof( HDSRPMaterialType ), GetCurrentParam( ref nodeParams ) ); } if( UIUtils.CurrentShaderVersion() > 15501 ) { if( m_isMainOutputNode && UIUtils.CurrentShaderVersion() > PASS_SELECTOR_VERSION ) m_subShaderOptions.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); m_passOptions.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); } if( m_isMainOutputNode && UIUtils.CurrentShaderVersion() > PASS_SELECTOR_VERSION ) { m_passSelector.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); } if( m_isMainOutputNode && UIUtils.CurrentShaderVersion() > 16203 ) { m_drawInstancedHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); } if( m_isMainOutputNode && UIUtils.CurrentShaderVersion() > LOD_SUBSHADER_VERSION ) { m_mainLODName = GetCurrentParam( ref nodeParams ); SetupLODNodeName(); } else { m_content.text = GenerateClippedTitle( m_passName ); } if( UIUtils.CurrentShaderVersion() > 18302 ) m_samplingMacros = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) ); else m_samplingMacros = false; //if( m_templateMultiPass != null && !m_templateMultiPass.IsSinglePass ) //{ // SetClippedTitle( m_passName ); //} } catch( Exception e ) { Debug.LogException( e, this ); } m_containerGraph.CurrentCanvasMode = NodeAvailability.TemplateShader; m_containerGraph.CurrentPrecision = m_currentPrecisionType; m_containerGraph.SamplingMacros = m_samplingMacros; } public override void WriteToString( ref string nodeInfo, ref string connectionsInfo ) { base.WriteToString( ref nodeInfo, ref connectionsInfo ); IOUtils.AddFieldValueToString( ref nodeInfo, ShaderName ); IOUtils.AddFieldValueToString( ref nodeInfo, m_templateGUID ); bool hasUniquePassName = Pass.Modules.HasPassUniqueName; IOUtils.AddFieldValueToString( ref nodeInfo, hasUniquePassName ); if( hasUniquePassName ) { IOUtils.AddFieldValueToString( ref nodeInfo, Pass.Modules.PassUniqueName ); } IOUtils.AddFieldValueToString( ref nodeInfo, m_subShaderIdx ); IOUtils.AddFieldValueToString( ref nodeInfo, m_passIdx ); IOUtils.AddFieldValueToString( ref nodeInfo, m_passName ); IOUtils.AddFieldValueToString( ref nodeInfo, m_visiblePorts ); m_subShaderModule.WriteToString( ref nodeInfo ); m_passModule.WriteToString( ref nodeInfo ); m_fallbackHelper.WriteToString( ref nodeInfo ); m_dependenciesHelper.WriteToString( ref nodeInfo ); m_usePass.WriteToString( ref nodeInfo ); IOUtils.AddFieldValueToString( ref nodeInfo, m_hdSrpMaterialType ); if( m_isMainOutputNode ) m_subShaderOptions.WriteToString( ref nodeInfo ); m_passOptions.WriteToString( ref nodeInfo ); if( m_isMainOutputNode ) { m_passSelector.WriteToString( ref nodeInfo ); m_drawInstancedHelper.WriteToString( ref nodeInfo ); } if( m_isMainOutputNode ) IOUtils.AddFieldValueToString( ref nodeInfo, m_mainLODName ); IOUtils.AddFieldValueToString( ref nodeInfo, m_samplingMacros ); } public override void ReadFromDeprecated( ref string[] nodeParams, Type oldType = null ) { base.ReadFromString( ref nodeParams ); try { string currShaderName = GetCurrentParam( ref nodeParams ); if( currShaderName.Length > 0 ) currShaderName = UIUtils.RemoveShaderInvalidCharacters( currShaderName ); string templateGUID = GetCurrentParam( ref nodeParams ); string templateShaderName = string.Empty; if( UIUtils.CurrentShaderVersion() > 13601 ) { templateShaderName = GetCurrentParam( ref nodeParams ); } TemplateMultiPass template = m_containerGraph.ParentWindow.TemplatesManagerInstance.GetTemplate( templateGUID ) as TemplateMultiPass; if( template != null ) { m_templateGUID = templateGUID; SetTemplate( null, false, true, 0, 0,SetTemplateSource.ShaderLoad ); } else { template = m_containerGraph.ParentWindow.TemplatesManagerInstance.GetTemplateByName( templateShaderName ) as TemplateMultiPass; if( template != null ) { m_templateGUID = template.GUID; SetTemplate( null, false, true, 0, 0, SetTemplateSource.ShaderLoad ); } else { m_masterNodeCategory = -1; } } if( m_invalidNode ) return; // only in here, after SetTemplate, we know if shader name is to be used as title or not ShaderName = currShaderName; if( UIUtils.CurrentShaderVersion() > 13902 ) { //BLEND MODULE if( m_templateMultiPass.SubShaders[ 0 ].Modules.BlendData.ValidBlendMode ) { m_subShaderModule.BlendOpHelper.ReadBlendModeFromString( ref m_currentReadParamIdx, ref nodeParams ); } else if( m_templateMultiPass.SubShaders[ 0 ].Passes[ 0 ].Modules.BlendData.ValidBlendMode ) { m_passModule.BlendOpHelper.ReadBlendModeFromString( ref m_currentReadParamIdx, ref nodeParams ); } if( m_templateMultiPass.SubShaders[ 0 ].Modules.BlendData.ValidBlendOp ) { m_subShaderModule.BlendOpHelper.ReadBlendOpFromString( ref m_currentReadParamIdx, ref nodeParams ); } else if( m_templateMultiPass.SubShaders[ 0 ].Passes[ 0 ].Modules.BlendData.ValidBlendOp ) { m_passModule.BlendOpHelper.ReadBlendOpFromString( ref m_currentReadParamIdx, ref nodeParams ); } //CULL MODE if( m_templateMultiPass.SubShaders[ 0 ].Modules.CullModeData.DataCheck == TemplateDataCheck.Valid ) { m_subShaderModule.CullModeHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); } else if( m_templateMultiPass.SubShaders[ 0 ].Passes[ 0 ].Modules.CullModeData.DataCheck == TemplateDataCheck.Valid ) { m_passModule.CullModeHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); } //COLOR MASK if( m_templateMultiPass.SubShaders[ 0 ].Modules.ColorMaskData.DataCheck == TemplateDataCheck.Valid ) { m_subShaderModule.ColorMaskHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); } else if( m_templateMultiPass.SubShaders[ 0 ].Passes[ 0 ].Modules.ColorMaskData.DataCheck == TemplateDataCheck.Valid ) { m_passModule.ColorMaskHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); } //STENCIL BUFFER if( m_templateMultiPass.SubShaders[ 0 ].Modules.StencilData.DataCheck == TemplateDataCheck.Valid ) { m_subShaderModule.StencilBufferHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); } else if( m_templateMultiPass.SubShaders[ 0 ].Passes[ 0 ].Modules.StencilData.DataCheck == TemplateDataCheck.Valid ) { m_passModule.StencilBufferHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); } } if( UIUtils.CurrentShaderVersion() > 14202 ) { //DEPTH OPTIONS if( m_templateMultiPass.SubShaders[ 0 ].Modules.DepthData.ValidZWrite ) { m_subShaderModule.DepthOphelper.ReadZWriteFromString( ref m_currentReadParamIdx, ref nodeParams ); } else if( m_templateMultiPass.SubShaders[ 0 ].Passes[ 0 ].Modules.DepthData.ValidZWrite ) { m_passModule.DepthOphelper.ReadZWriteFromString( ref m_currentReadParamIdx, ref nodeParams ); } if( m_templateMultiPass.SubShaders[ 0 ].Modules.DepthData.ValidZTest ) { m_subShaderModule.DepthOphelper.ReadZTestFromString( ref m_currentReadParamIdx, ref nodeParams ); } else if( m_templateMultiPass.SubShaders[ 0 ].Passes[ 0 ].Modules.DepthData.ValidZTest ) { m_subShaderModule.DepthOphelper.ReadZTestFromString( ref m_currentReadParamIdx, ref nodeParams ); } if( m_templateMultiPass.SubShaders[ 0 ].Modules.DepthData.ValidOffset ) { m_subShaderModule.DepthOphelper.ReadOffsetFromString( ref m_currentReadParamIdx, ref nodeParams ); } else if( m_templateMultiPass.SubShaders[ 0 ].Passes[ 0 ].Modules.DepthData.ValidOffset ) { m_passModule.DepthOphelper.ReadOffsetFromString( ref m_currentReadParamIdx, ref nodeParams ); } } //TAGS if( UIUtils.CurrentShaderVersion() > 14301 ) { if( m_templateMultiPass.SubShaders[ 0 ].Modules.TagData.DataCheck == TemplateDataCheck.Valid ) { m_subShaderModule.TagsHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); } else if( m_templateMultiPass.SubShaders[ 0 ].Passes[ 0 ].Modules.TagData.DataCheck == TemplateDataCheck.Valid ) { m_passModule.TagsHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams ); } } m_samplingMacros = false; } catch( Exception e ) { Debug.LogException( e, this ); } m_containerGraph.CurrentCanvasMode = NodeAvailability.TemplateShader; } public void ForceOptionsRefresh() { m_passOptions.Refresh(); if( m_isMainOutputNode ) m_subShaderOptions.Refresh(); } public void SetPassVisible( string passName, bool visible ) { TemplateMultiPassMasterNode node = m_containerGraph.GetMasterNodeOfPass( passName, m_lodIndex ); if( node != null ) { m_passSelector.SetPassVisible( passName, visible ); node.IsInvisible = !visible; } } public override void RefreshExternalReferences() { if( m_invalidNode ) return; base.RefreshExternalReferences(); if( IsLODMainMasterNode ) { SetMasterNodeCategoryFromGUID( m_templateGUID ); } CheckTemplateChanges(); if( m_templateMultiPass != null && m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].Modules.SRPIsPBRHD && UIUtils.CurrentShaderVersion() < 15410 ) { FetchHDPorts(); m_hdSrpMaterialType = ( m_specularPort != null && m_specularPort.HasOwnOrLinkConnection ) ? HDSRPMaterialType.Specular : HDSRPMaterialType.Standard; ConfigHDPorts(); } if( ContainerGraph.HasLODs ) { SetClippedAdditionalTitle( string.Format( LodSubtitle, ShaderLOD ) ); } if( m_isMainOutputNode ) { List<TemplateMultiPassMasterNode> masterNodes = ( m_lodIndex == -1 ) ? m_containerGraph.MultiPassMasterNodes.NodesList : m_containerGraph.LodMultiPassMasternodes[ m_lodIndex ].NodesList; masterNodes.Sort( ( x, y ) => ( x.PassIdx.CompareTo( y.PassIdx ) )); int passAmount = m_templateMultiPass.SubShaders[ m_subShaderIdx ].PassAmount; if( passAmount != masterNodes.Count ) { UIUtils.ShowMessage( "Template master nodes amount was modified. Could not set correctly its visibility options." ); } else { for( int i = 0; i < passAmount; i++ ) { if( i != m_passIdx ) { masterNodes[ i ].IsInvisible = !m_passSelector.IsVisible( i ); } } } } } public override void ReadInputDataFromString( ref string[] nodeParams ) { //For a Template Master Node an input port data must be set by its template and not meta data if( UIUtils.CurrentShaderVersion() > 17007 ) return; int count = 0; if( UIUtils.CurrentShaderVersion() > 7003 ) { try { count = Convert.ToInt32( nodeParams[ m_currentReadParamIdx++ ] ); } catch( Exception e ) { Debug.LogException( e ); } } else { count = ( m_oldInputCount < 0 ) ? m_inputPorts.Count : m_oldInputCount; } for( int i = 0; i < count && i < nodeParams.Length && m_currentReadParamIdx < nodeParams.Length; i++ ) { if( UIUtils.CurrentShaderVersion() < 5003 ) { int newId = VersionConvertInputPortId( i ); if( UIUtils.CurrentShaderVersion() > 23 ) { m_currentReadParamIdx++; } m_currentReadParamIdx++; if( m_inputPorts[ newId ].IsEditable && UIUtils.CurrentShaderVersion() >= 3100 && m_currentReadParamIdx < nodeParams.Length ) { m_currentReadParamIdx++; } } else { m_currentReadParamIdx++; m_currentReadParamIdx++; m_currentReadParamIdx++; bool isEditable = Convert.ToBoolean( nodeParams[ m_currentReadParamIdx++ ] ); if( isEditable && m_currentReadParamIdx < nodeParams.Length ) { m_currentReadParamIdx++; } } } } //For a Template Master Node an input port data must be set by its template and not meta data public override void WriteInputDataToString( ref string nodeInfo ) { } public override float HeightEstimate { get { float heightEstimate = 0; heightEstimate = 32 + Constants.INPUT_PORT_DELTA_Y; if( m_templateMultiPass != null && !m_templateMultiPass.IsSinglePass ) { heightEstimate += 22; } float internalPortSize = 0; for( int i = 0; i < InputPorts.Count; i++ ) { if( InputPorts[ i ].Visible ) internalPortSize += 18 + Constants.INPUT_PORT_DELTA_Y; } return heightEstimate + Mathf.Max( internalPortSize, m_insideSize.y ); } } public HDSRPMaterialType CurrentHDMaterialType { get { return m_hdSrpMaterialType; } set { m_hdSrpMaterialType = value; if( m_isMainOutputNode ) { List<TemplateMultiPassMasterNode> mpNodes = UIUtils.CurrentWindow.CurrentGraph.MultiPassMasterNodes.NodesList; int count = mpNodes.Count; for( int i = 0; i < count; i++ ) { if( mpNodes[ i ].UniqueId != UniqueId ) { mpNodes[ i ].CurrentHDMaterialType = value; } } } } } public TemplateSubShader SubShader { get { return m_templateMultiPass.SubShaders[ m_subShaderIdx ]; } } public TemplatePass Pass { get { return m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ]; } } public int SubShaderIdx { get { return m_subShaderIdx; } } public int PassIdx { get { return m_passIdx; } } public TemplateMultiPass CurrentTemplate { get { return m_templateMultiPass; } } public TemplateModulesHelper SubShaderModule { get { return m_subShaderModule; } } public TemplateModulesHelper PassModule { get { return m_passModule; } } public string PassName { get { return m_templateMultiPass.SubShaders[ m_subShaderIdx ].Passes[ m_passIdx ].PassNameContainer.Data; } } public string PassUniqueName { get { return string.IsNullOrEmpty( m_passUniqueId ) ? m_originalPassName : m_passUniqueId; } } public string OriginalPassName { get { return m_originalPassName; } } public bool HasLinkPorts { get { return m_hasLinkPorts; } } public bool IsInvisible { get { return m_isInvisible != InvisibilityStatus.Visible; } set { if( m_isInvisible != InvisibilityStatus.LockedInvisible && !m_isMainOutputNode ) { m_isInvisible = value ? InvisibilityStatus.Invisible : InvisibilityStatus.Visible; if( value ) { for( int i = 0; i < m_inputPorts.Count; i++ ) { m_inputPorts[ i ].FullDeleteConnections(); } } } } } public TemplatePassSelectorHelper PassSelector { get { return m_passSelector; } } public TemplateOptionsUIHelper PassOptions { get { return m_passOptions; } } public TemplateOptionsUIHelper SubShaderOptions { get { return m_subShaderOptions; } } public TemplateOptionsDefinesContainer OptionsDefineContainer { get { return m_optionsDefineContainer; } } public TerrainDrawInstancedHelper DrawInstancedHelperInstance { get { return m_drawInstancedHelper; } } public bool InvalidNode { get { return m_invalidNode; } } public override void SetName( string name ) { ShaderName = name; } public bool IsLODMainFirstPass { get { return m_passIdx == 0 && m_lodIndex == -1; } } } }
35.595188
315
0.730275
[ "MIT" ]
NEUGameDeveloper/SimpleRPG
Client/Assets/ThirdParty/AmplifyShaderEditor/Plugins/Editor/Templates/TemplateMultiPassMasterNode.cs
118,354
C#
using System; using System.Threading; using Akka.Actor; using Akka.Quartz.Actor.Commands; using Akka.Quartz.Actor.Events; using Akka.Quartz.Actor.Exceptions; using Quartz; using Xunit; namespace Akka.Quartz.Actor.Tests { public class QuartzPersistentActorSpec : TestKit.Xunit2.TestKit { [Fact] public void QuartzPersistentActor_Should_Create_Job() { var probe = CreateTestProbe(Sys); var quartzActor = Sys.ActorOf(Props.Create(() => new QuartzPersistentActor()), "QuartzActor"); quartzActor.Tell(new CreatePersistentJob(probe.Ref.Path, "Hello", TriggerBuilder.Create().WithCronSchedule("*0/10 * * * * ?").Build())); ExpectMsg<JobCreated>(); probe.ExpectMsg("Hello", TimeSpan.FromSeconds(11)); Thread.Sleep(TimeSpan.FromSeconds(10)); probe.ExpectMsg("Hello"); Sys.Stop(quartzActor); } [Fact] public void QuartzPersistentActor_Should_Remove_Job() { var probe = CreateTestProbe(Sys); var quartzActor = Sys.ActorOf(Props.Create(() => new QuartzPersistentActor()), "QuartzActor"); quartzActor.Tell(new CreatePersistentJob(probe.Ref.Path, "Hello remove", TriggerBuilder.Create().WithCronSchedule("0/10 * * * * ?").Build())); var jobCreated = ExpectMsg<JobCreated>(); probe.ExpectMsg("Hello remove", TimeSpan.FromSeconds(11)); quartzActor.Tell(new RemoveJob(jobCreated.JobKey, jobCreated.TriggerKey)); ExpectMsg<JobRemoved>(); Thread.Sleep(TimeSpan.FromSeconds(10)); probe.ExpectNoMsg(TimeSpan.FromSeconds(10)); Sys.Stop(quartzActor); } [Fact] public void QuartzPersistentActor_Should_Fail_With_Null_Trigger() { var probe = CreateTestProbe(Sys); var quartzActor = Sys.ActorOf(Props.Create(() => new QuartzPersistentActor()), "QuartzActor"); quartzActor.Tell(new CreatePersistentJob(probe.Ref.Path, "Hello", null)); var failedJob = ExpectMsg<CreateJobFail>(); Assert.NotNull(failedJob.Reason); Sys.Stop(quartzActor); } [Fact] public void QuartzPersistentActor_Should_Fail_With_Null_Actor() { var quartzActor = Sys.ActorOf(Props.Create(() => new QuartzPersistentActor()), "QuartzActor"); quartzActor.Tell(new CreatePersistentJob(null, "Hello", TriggerBuilder.Create().WithCronSchedule(" * * * * * ?").Build())); var failedJob = ExpectMsg<CreateJobFail>(); Assert.NotNull(failedJob.Reason); Sys.Stop(quartzActor); } [Fact] public void QuartzPersistentActor_Should_Not_Remove_UnExisting_Job() { var probe = CreateTestProbe(Sys); var quartzActor = Sys.ActorOf(Props.Create(() => new QuartzPersistentActor()), "QuartzActor"); quartzActor.Tell(new RemoveJob(new JobKey("key"), new TriggerKey("key"))); var failure=ExpectMsg<RemoveJobFail>(); Assert.IsType<JobNotFoundException>(failure.Reason); Sys.Stop(quartzActor); } [Fact] public void QuartzPersistentActor_Should_Handle_New_Incarnations() { // setup first system var firstSystem = ActorSystem.Create("test", DefaultConfig); var firstProbe = CreateTestProbe(firstSystem); var firstIncarnation = firstSystem.ActorOf(Props.Create(() => new Relaying(firstProbe)), "relay"); Watch(firstIncarnation); var firstQuartz = firstSystem.ActorOf(Props.Create(() => new QuartzPersistentActor()), "QuartzActor"); firstQuartz.Tell(new CreatePersistentJob(firstIncarnation.Path, "Hello", TriggerBuilder.Create().WithCronSchedule("0/2 * * * * ?").Build())); ExpectMsg<JobCreated>(); firstProbe.ExpectMsg("Hello", TimeSpan.FromSeconds(10)); firstSystem.Stop(firstIncarnation); ExpectTerminated(firstIncarnation, TimeSpan.FromSeconds(10)); // simulate a restart // use the same quartz scheduler which simulates retrieval from quartz jobstore var secondSystem = ActorSystem.Create("test", DefaultConfig); secondSystem.ActorOf(Props.Create(() => new QuartzPersistentActor()), "QuartzActor"); var secondProbe = CreateTestProbe(secondSystem); var secondIncarnation = secondSystem.ActorOf(Props.Create(() => new Relaying(secondProbe)), "relay"); secondProbe.ExpectMsgFrom(secondIncarnation, "Hello", TimeSpan.FromSeconds(10)); firstSystem.Terminate(); secondSystem.Terminate(); } private class Relaying : ReceiveActor { private IActorRef _relay; public Relaying(IActorRef relay) { _relay = relay; ReceiveAny(msg => _relay.Tell(msg)); } } } }
44.298246
154
0.625545
[ "Apache-2.0" ]
Ikendiken/Akka.Quartz.Actor
src/Akka.Quartz.Actor.Tests.Orig/QuartzPersistentActorSpec.cs
5,052
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Simple.OData.Client.Tests.Entities { public class Mammal : Animal { } }
16.307692
44
0.740566
[ "MIT" ]
3-PRO/Simple.OData.Client
src/Simple.OData.Client.UnitTests/Entities/Mammal.cs
214
C#
using Caf.CafModelingMetricCropSyst.Core.Interfaces; using Caf.CafModelingMetricCropSyst.Core.Models; using Caf.CafModelingMetricCropSyst.Infrastructure; using McMaster.Extensions.CommandLineUtils; using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Text; namespace Caf.CafModelingMetricCropSyst.Cli { /// <summary> /// Represents a poor man's dependency injector of sorts /// </summary> public static class Container { /// <summary> /// Wires up all dependencies, called by composition root /// </summary> /// <returns>Engine that runs the program</returns> public static Engine ResolveCafEEFluxCli() { string b = GetBaseAddress(); HttpClient c = ResolveHttpClient(); var m = ResolveImageTypeToUriMap(); IEEFluxClient<HttpResponseMessage> f = new EEFluxClientWebApi(c, b, m); CommandLineApplication a = getConfiguredCli(); IParseParameters<CommandOption> p = new CommandLineUtilParameterParser(); return new Engine(f, a, p); } public static HttpClient ResolveHttpClient() { HttpClient c = new HttpClient(); c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); c.Timeout = TimeSpan.FromMinutes(30); return c; } public static string GetBaseAddress() { return "https://eeflux-level1.appspot.com"; } public static Dictionary<EEFluxImageTypes, string> ResolveImageTypeToUriMap() { MapImageTypeToUrlPath imageTypeToUriMap = new MapImageTypeToUrlPath(); return imageTypeToUriMap.map; } private static CommandLineApplication getConfiguredCli() { // Learned how to use CommandLineApplication from here: https://gist.github.com/iamarcel/8047384bfbe9941e52817cf14a79dc34 // Using updated version, not Microsofts: https://github.com/natemcmaster/CommandLineUtils CommandLineApplication a = new CommandLineApplication(); a.Name = "eeflux"; a.HelpOption("-?|-h|--help"); a.OnExecute(() => { Console.WriteLine("Please specify a command to run"); return 0; }); return a; } } }
36.314286
134
0.611723
[ "CC0-1.0" ]
caf-ltar/CafModelingMetricCropSyst_DotNet_CafEEFlux
Cli/Container.cs
2,544
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fie.MasterPage { public class RootMenuItem { public RootMenuItem() { target = typeof(Pages.HomePage); title = Pages.HomePage.TITLE; } public string title { get; set; } public Type target { get; set; } } }
21
44
0.629073
[ "Apache-2.0" ]
DoumanAsh/Fie.mobile
Fie/Fie/MasterPage/RootMenuItem.cs
401
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.imm.Transform; using Aliyun.Acs.imm.Transform.V20170906; namespace Aliyun.Acs.imm.Model.V20170906 { public class PutProjectRequest : RpcAcsRequest<PutProjectResponse> { public PutProjectRequest() : base("imm", "2017-09-06", "PutProject", "imm", "openAPI") { } private int? cU; private string serviceRole; private string project; private string billingType; private string type; public int? CU { get { return cU; } set { cU = value; DictionaryUtil.Add(QueryParameters, "CU", value.ToString()); } } public string ServiceRole { get { return serviceRole; } set { serviceRole = value; DictionaryUtil.Add(QueryParameters, "ServiceRole", value); } } public string Project { get { return project; } set { project = value; DictionaryUtil.Add(QueryParameters, "Project", value); } } public string BillingType { get { return billingType; } set { billingType = value; DictionaryUtil.Add(QueryParameters, "BillingType", value); } } public string Type { get { return type; } set { type = value; DictionaryUtil.Add(QueryParameters, "Type", value); } } public override bool CheckShowJsonItemName() { return false; } public override PutProjectResponse GetResponse(UnmarshallerContext unmarshallerContext) { return PutProjectResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
21.325203
95
0.650782
[ "Apache-2.0" ]
fossabot/aliyun-openapi-net-sdk
aliyun-net-sdk-imm/Imm/Model/V20170906/PutProjectRequest.cs
2,623
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class PauseMenu : MonoBehaviour { public static bool GameIsPaused = false; public GameObject PauseMenuUI; void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { if (GameIsPaused) { Resume(); } else { Pause(); } } } public void Resume() { PauseMenuUI.SetActive(false); Time.timeScale = 1f; GameIsPaused = false; } void Pause() { PauseMenuUI.SetActive(true); Time.timeScale = 0f; GameIsPaused = true; } public void LoadMenu() { SceneManager.LoadScene("Menu"); } public void QuitGame() { Application.Quit(); } }
17.176471
45
0.552511
[ "Apache-2.0" ]
ShiroixD/WatchOutAsteroids
Assets/Scripts/Menus/PauseMenu.cs
878
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace Shashlik.EventBus.SqlServer.Tests.Efcore.Migrations { public partial class init : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Users", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(maxLength: 8, nullable: false) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.Id); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Users"); } } }
30.533333
78
0.514192
[ "MIT" ]
dotnet-shashlik/shashlik.eventbus
src/Shashlik.EventBus.SqlServer.Tests/Efcore/Migrations/20201128024153_init.cs
918
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v5/services/ad_group_label_service.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V5.Services { /// <summary>Holder for reflection information generated from google/ads/googleads/v5/services/ad_group_label_service.proto</summary> public static partial class AdGroupLabelServiceReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v5/services/ad_group_label_service.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AdGroupLabelServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cj1nb29nbGUvYWRzL2dvb2dsZWFkcy92NS9zZXJ2aWNlcy9hZF9ncm91cF9s", "YWJlbF9zZXJ2aWNlLnByb3RvEiBnb29nbGUuYWRzLmdvb2dsZWFkcy52NS5z", "ZXJ2aWNlcxo2Z29vZ2xlL2Fkcy9nb29nbGVhZHMvdjUvcmVzb3VyY2VzL2Fk", "X2dyb3VwX2xhYmVsLnByb3RvGhxnb29nbGUvYXBpL2Fubm90YXRpb25zLnBy", "b3RvGhdnb29nbGUvYXBpL2NsaWVudC5wcm90bxofZ29vZ2xlL2FwaS9maWVs", "ZF9iZWhhdmlvci5wcm90bxoZZ29vZ2xlL2FwaS9yZXNvdXJjZS5wcm90bxoX", "Z29vZ2xlL3JwYy9zdGF0dXMucHJvdG8iXgoWR2V0QWRHcm91cExhYmVsUmVx", "dWVzdBJECg1yZXNvdXJjZV9uYW1lGAEgASgJQi3gQQL6QScKJWdvb2dsZWFk", "cy5nb29nbGVhcGlzLmNvbS9BZEdyb3VwTGFiZWwiuAEKGk11dGF0ZUFkR3Jv", "dXBMYWJlbHNSZXF1ZXN0EhgKC2N1c3RvbWVyX2lkGAEgASgJQgPgQQISUAoK", "b3BlcmF0aW9ucxgCIAMoCzI3Lmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY1LnNl", "cnZpY2VzLkFkR3JvdXBMYWJlbE9wZXJhdGlvbkID4EECEhcKD3BhcnRpYWxf", "ZmFpbHVyZRgDIAEoCBIVCg12YWxpZGF0ZV9vbmx5GAQgASgIInkKFUFkR3Jv", "dXBMYWJlbE9wZXJhdGlvbhJBCgZjcmVhdGUYASABKAsyLy5nb29nbGUuYWRz", "Lmdvb2dsZWFkcy52NS5yZXNvdXJjZXMuQWRHcm91cExhYmVsSAASEAoGcmVt", "b3ZlGAIgASgJSABCCwoJb3BlcmF0aW9uIp0BChtNdXRhdGVBZEdyb3VwTGFi", "ZWxzUmVzcG9uc2USMQoVcGFydGlhbF9mYWlsdXJlX2Vycm9yGAMgASgLMhIu", "Z29vZ2xlLnJwYy5TdGF0dXMSSwoHcmVzdWx0cxgCIAMoCzI6Lmdvb2dsZS5h", "ZHMuZ29vZ2xlYWRzLnY1LnNlcnZpY2VzLk11dGF0ZUFkR3JvdXBMYWJlbFJl", "c3VsdCIxChhNdXRhdGVBZEdyb3VwTGFiZWxSZXN1bHQSFQoNcmVzb3VyY2Vf", "bmFtZRgBIAEoCTLnAwoTQWRHcm91cExhYmVsU2VydmljZRLFAQoPR2V0QWRH", "cm91cExhYmVsEjguZ29vZ2xlLmFkcy5nb29nbGVhZHMudjUuc2VydmljZXMu", "R2V0QWRHcm91cExhYmVsUmVxdWVzdBovLmdvb2dsZS5hZHMuZ29vZ2xlYWRz", "LnY1LnJlc291cmNlcy5BZEdyb3VwTGFiZWwiR4LT5JMCMRIvL3Y1L3tyZXNv", "dXJjZV9uYW1lPWN1c3RvbWVycy8qL2FkR3JvdXBMYWJlbHMvKn3aQQ1yZXNv", "dXJjZV9uYW1lEuoBChNNdXRhdGVBZEdyb3VwTGFiZWxzEjwuZ29vZ2xlLmFk", "cy5nb29nbGVhZHMudjUuc2VydmljZXMuTXV0YXRlQWRHcm91cExhYmVsc1Jl", "cXVlc3QaPS5nb29nbGUuYWRzLmdvb2dsZWFkcy52NS5zZXJ2aWNlcy5NdXRh", "dGVBZEdyb3VwTGFiZWxzUmVzcG9uc2UiVoLT5JMCNyIyL3Y1L2N1c3RvbWVy", "cy97Y3VzdG9tZXJfaWQ9Kn0vYWRHcm91cExhYmVsczptdXRhdGU6ASraQRZj", "dXN0b21lcl9pZCxvcGVyYXRpb25zGhvKQRhnb29nbGVhZHMuZ29vZ2xlYXBp", "cy5jb21C/wEKJGNvbS5nb29nbGUuYWRzLmdvb2dsZWFkcy52NS5zZXJ2aWNl", "c0IYQWRHcm91cExhYmVsU2VydmljZVByb3RvUAFaSGdvb2dsZS5nb2xhbmcu", "b3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvYWRzL2dvb2dsZWFkcy92NS9zZXJ2", "aWNlcztzZXJ2aWNlc6ICA0dBQaoCIEdvb2dsZS5BZHMuR29vZ2xlQWRzLlY1", "LlNlcnZpY2VzygIgR29vZ2xlXEFkc1xHb29nbGVBZHNcVjVcU2VydmljZXPq", "AiRHb29nbGU6OkFkczo6R29vZ2xlQWRzOjpWNTo6U2VydmljZXNiBnByb3Rv", "Mw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Ads.GoogleAds.V5.Resources.AdGroupLabelReflection.Descriptor, global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Api.ClientReflection.Descriptor, global::Google.Api.FieldBehaviorReflection.Descriptor, global::Google.Api.ResourceReflection.Descriptor, global::Google.Rpc.StatusReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V5.Services.GetAdGroupLabelRequest), global::Google.Ads.GoogleAds.V5.Services.GetAdGroupLabelRequest.Parser, new[]{ "ResourceName" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V5.Services.MutateAdGroupLabelsRequest), global::Google.Ads.GoogleAds.V5.Services.MutateAdGroupLabelsRequest.Parser, new[]{ "CustomerId", "Operations", "PartialFailure", "ValidateOnly" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V5.Services.AdGroupLabelOperation), global::Google.Ads.GoogleAds.V5.Services.AdGroupLabelOperation.Parser, new[]{ "Create", "Remove" }, new[]{ "Operation" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V5.Services.MutateAdGroupLabelsResponse), global::Google.Ads.GoogleAds.V5.Services.MutateAdGroupLabelsResponse.Parser, new[]{ "PartialFailureError", "Results" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V5.Services.MutateAdGroupLabelResult), global::Google.Ads.GoogleAds.V5.Services.MutateAdGroupLabelResult.Parser, new[]{ "ResourceName" }, null, null, null, null) })); } #endregion } #region Messages /// <summary> /// Request message for [AdGroupLabelService.GetAdGroupLabel][google.ads.googleads.v5.services.AdGroupLabelService.GetAdGroupLabel]. /// </summary> public sealed partial class GetAdGroupLabelRequest : pb::IMessage<GetAdGroupLabelRequest> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<GetAdGroupLabelRequest> _parser = new pb::MessageParser<GetAdGroupLabelRequest>(() => new GetAdGroupLabelRequest()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetAdGroupLabelRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V5.Services.AdGroupLabelServiceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetAdGroupLabelRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetAdGroupLabelRequest(GetAdGroupLabelRequest other) : this() { resourceName_ = other.resourceName_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetAdGroupLabelRequest Clone() { return new GetAdGroupLabelRequest(this); } /// <summary>Field number for the "resource_name" field.</summary> public const int ResourceNameFieldNumber = 1; private string resourceName_ = ""; /// <summary> /// Required. The resource name of the ad group label to fetch. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ResourceName { get { return resourceName_; } set { resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetAdGroupLabelRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetAdGroupLabelRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ResourceName != other.ResourceName) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ResourceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetAdGroupLabelRequest other) { if (other == null) { return; } if (other.ResourceName.Length != 0) { ResourceName = other.ResourceName; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { ResourceName = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { ResourceName = input.ReadString(); break; } } } } #endif } /// <summary> /// Request message for [AdGroupLabelService.MutateAdGroupLabels][google.ads.googleads.v5.services.AdGroupLabelService.MutateAdGroupLabels]. /// </summary> public sealed partial class MutateAdGroupLabelsRequest : pb::IMessage<MutateAdGroupLabelsRequest> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<MutateAdGroupLabelsRequest> _parser = new pb::MessageParser<MutateAdGroupLabelsRequest>(() => new MutateAdGroupLabelsRequest()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MutateAdGroupLabelsRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V5.Services.AdGroupLabelServiceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MutateAdGroupLabelsRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MutateAdGroupLabelsRequest(MutateAdGroupLabelsRequest other) : this() { customerId_ = other.customerId_; operations_ = other.operations_.Clone(); partialFailure_ = other.partialFailure_; validateOnly_ = other.validateOnly_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MutateAdGroupLabelsRequest Clone() { return new MutateAdGroupLabelsRequest(this); } /// <summary>Field number for the "customer_id" field.</summary> public const int CustomerIdFieldNumber = 1; private string customerId_ = ""; /// <summary> /// Required. ID of the customer whose ad group labels are being modified. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string CustomerId { get { return customerId_; } set { customerId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "operations" field.</summary> public const int OperationsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Ads.GoogleAds.V5.Services.AdGroupLabelOperation> _repeated_operations_codec = pb::FieldCodec.ForMessage(18, global::Google.Ads.GoogleAds.V5.Services.AdGroupLabelOperation.Parser); private readonly pbc::RepeatedField<global::Google.Ads.GoogleAds.V5.Services.AdGroupLabelOperation> operations_ = new pbc::RepeatedField<global::Google.Ads.GoogleAds.V5.Services.AdGroupLabelOperation>(); /// <summary> /// Required. The list of operations to perform on ad group labels. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Ads.GoogleAds.V5.Services.AdGroupLabelOperation> Operations { get { return operations_; } } /// <summary>Field number for the "partial_failure" field.</summary> public const int PartialFailureFieldNumber = 3; private bool partialFailure_; /// <summary> /// If true, successful operations will be carried out and invalid /// operations will return errors. If false, all operations will be carried /// out in one transaction if and only if they are all valid. /// Default is false. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool PartialFailure { get { return partialFailure_; } set { partialFailure_ = value; } } /// <summary>Field number for the "validate_only" field.</summary> public const int ValidateOnlyFieldNumber = 4; private bool validateOnly_; /// <summary> /// If true, the request is validated but not executed. Only errors are /// returned, not results. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool ValidateOnly { get { return validateOnly_; } set { validateOnly_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MutateAdGroupLabelsRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MutateAdGroupLabelsRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (CustomerId != other.CustomerId) return false; if(!operations_.Equals(other.operations_)) return false; if (PartialFailure != other.PartialFailure) return false; if (ValidateOnly != other.ValidateOnly) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (CustomerId.Length != 0) hash ^= CustomerId.GetHashCode(); hash ^= operations_.GetHashCode(); if (PartialFailure != false) hash ^= PartialFailure.GetHashCode(); if (ValidateOnly != false) hash ^= ValidateOnly.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (CustomerId.Length != 0) { output.WriteRawTag(10); output.WriteString(CustomerId); } operations_.WriteTo(output, _repeated_operations_codec); if (PartialFailure != false) { output.WriteRawTag(24); output.WriteBool(PartialFailure); } if (ValidateOnly != false) { output.WriteRawTag(32); output.WriteBool(ValidateOnly); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (CustomerId.Length != 0) { output.WriteRawTag(10); output.WriteString(CustomerId); } operations_.WriteTo(ref output, _repeated_operations_codec); if (PartialFailure != false) { output.WriteRawTag(24); output.WriteBool(PartialFailure); } if (ValidateOnly != false) { output.WriteRawTag(32); output.WriteBool(ValidateOnly); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (CustomerId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(CustomerId); } size += operations_.CalculateSize(_repeated_operations_codec); if (PartialFailure != false) { size += 1 + 1; } if (ValidateOnly != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MutateAdGroupLabelsRequest other) { if (other == null) { return; } if (other.CustomerId.Length != 0) { CustomerId = other.CustomerId; } operations_.Add(other.operations_); if (other.PartialFailure != false) { PartialFailure = other.PartialFailure; } if (other.ValidateOnly != false) { ValidateOnly = other.ValidateOnly; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { CustomerId = input.ReadString(); break; } case 18: { operations_.AddEntriesFrom(input, _repeated_operations_codec); break; } case 24: { PartialFailure = input.ReadBool(); break; } case 32: { ValidateOnly = input.ReadBool(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { CustomerId = input.ReadString(); break; } case 18: { operations_.AddEntriesFrom(ref input, _repeated_operations_codec); break; } case 24: { PartialFailure = input.ReadBool(); break; } case 32: { ValidateOnly = input.ReadBool(); break; } } } } #endif } /// <summary> /// A single operation (create, remove) on an ad group label. /// </summary> public sealed partial class AdGroupLabelOperation : pb::IMessage<AdGroupLabelOperation> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<AdGroupLabelOperation> _parser = new pb::MessageParser<AdGroupLabelOperation>(() => new AdGroupLabelOperation()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<AdGroupLabelOperation> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V5.Services.AdGroupLabelServiceReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AdGroupLabelOperation() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AdGroupLabelOperation(AdGroupLabelOperation other) : this() { switch (other.OperationCase) { case OperationOneofCase.Create: Create = other.Create.Clone(); break; case OperationOneofCase.Remove: Remove = other.Remove; break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AdGroupLabelOperation Clone() { return new AdGroupLabelOperation(this); } /// <summary>Field number for the "create" field.</summary> public const int CreateFieldNumber = 1; /// <summary> /// Create operation: No resource name is expected for the new ad group /// label. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Ads.GoogleAds.V5.Resources.AdGroupLabel Create { get { return operationCase_ == OperationOneofCase.Create ? (global::Google.Ads.GoogleAds.V5.Resources.AdGroupLabel) operation_ : null; } set { operation_ = value; operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.Create; } } /// <summary>Field number for the "remove" field.</summary> public const int RemoveFieldNumber = 2; /// <summary> /// Remove operation: A resource name for the ad group label /// being removed, in this format: /// /// `customers/{customer_id}/adGroupLabels/{ad_group_id}~{label_id}` /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Remove { get { return operationCase_ == OperationOneofCase.Remove ? (string) operation_ : ""; } set { operation_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); operationCase_ = OperationOneofCase.Remove; } } private object operation_; /// <summary>Enum of possible cases for the "operation" oneof.</summary> public enum OperationOneofCase { None = 0, Create = 1, Remove = 2, } private OperationOneofCase operationCase_ = OperationOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OperationOneofCase OperationCase { get { return operationCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearOperation() { operationCase_ = OperationOneofCase.None; operation_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as AdGroupLabelOperation); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(AdGroupLabelOperation other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Create, other.Create)) return false; if (Remove != other.Remove) return false; if (OperationCase != other.OperationCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (operationCase_ == OperationOneofCase.Create) hash ^= Create.GetHashCode(); if (operationCase_ == OperationOneofCase.Remove) hash ^= Remove.GetHashCode(); hash ^= (int) operationCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (operationCase_ == OperationOneofCase.Create) { output.WriteRawTag(10); output.WriteMessage(Create); } if (operationCase_ == OperationOneofCase.Remove) { output.WriteRawTag(18); output.WriteString(Remove); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (operationCase_ == OperationOneofCase.Create) { output.WriteRawTag(10); output.WriteMessage(Create); } if (operationCase_ == OperationOneofCase.Remove) { output.WriteRawTag(18); output.WriteString(Remove); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (operationCase_ == OperationOneofCase.Create) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Create); } if (operationCase_ == OperationOneofCase.Remove) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Remove); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(AdGroupLabelOperation other) { if (other == null) { return; } switch (other.OperationCase) { case OperationOneofCase.Create: if (Create == null) { Create = new global::Google.Ads.GoogleAds.V5.Resources.AdGroupLabel(); } Create.MergeFrom(other.Create); break; case OperationOneofCase.Remove: Remove = other.Remove; break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { global::Google.Ads.GoogleAds.V5.Resources.AdGroupLabel subBuilder = new global::Google.Ads.GoogleAds.V5.Resources.AdGroupLabel(); if (operationCase_ == OperationOneofCase.Create) { subBuilder.MergeFrom(Create); } input.ReadMessage(subBuilder); Create = subBuilder; break; } case 18: { Remove = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { global::Google.Ads.GoogleAds.V5.Resources.AdGroupLabel subBuilder = new global::Google.Ads.GoogleAds.V5.Resources.AdGroupLabel(); if (operationCase_ == OperationOneofCase.Create) { subBuilder.MergeFrom(Create); } input.ReadMessage(subBuilder); Create = subBuilder; break; } case 18: { Remove = input.ReadString(); break; } } } } #endif } /// <summary> /// Response message for an ad group labels mutate. /// </summary> public sealed partial class MutateAdGroupLabelsResponse : pb::IMessage<MutateAdGroupLabelsResponse> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<MutateAdGroupLabelsResponse> _parser = new pb::MessageParser<MutateAdGroupLabelsResponse>(() => new MutateAdGroupLabelsResponse()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MutateAdGroupLabelsResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V5.Services.AdGroupLabelServiceReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MutateAdGroupLabelsResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MutateAdGroupLabelsResponse(MutateAdGroupLabelsResponse other) : this() { partialFailureError_ = other.partialFailureError_ != null ? other.partialFailureError_.Clone() : null; results_ = other.results_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MutateAdGroupLabelsResponse Clone() { return new MutateAdGroupLabelsResponse(this); } /// <summary>Field number for the "partial_failure_error" field.</summary> public const int PartialFailureErrorFieldNumber = 3; private global::Google.Rpc.Status partialFailureError_; /// <summary> /// Errors that pertain to operation failures in the partial failure mode. /// Returned only when partial_failure = true and all errors occur inside the /// operations. If any errors occur outside the operations (e.g. auth errors), /// we return an RPC level error. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Rpc.Status PartialFailureError { get { return partialFailureError_; } set { partialFailureError_ = value; } } /// <summary>Field number for the "results" field.</summary> public const int ResultsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Ads.GoogleAds.V5.Services.MutateAdGroupLabelResult> _repeated_results_codec = pb::FieldCodec.ForMessage(18, global::Google.Ads.GoogleAds.V5.Services.MutateAdGroupLabelResult.Parser); private readonly pbc::RepeatedField<global::Google.Ads.GoogleAds.V5.Services.MutateAdGroupLabelResult> results_ = new pbc::RepeatedField<global::Google.Ads.GoogleAds.V5.Services.MutateAdGroupLabelResult>(); /// <summary> /// All results for the mutate. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Ads.GoogleAds.V5.Services.MutateAdGroupLabelResult> Results { get { return results_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MutateAdGroupLabelsResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MutateAdGroupLabelsResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(PartialFailureError, other.PartialFailureError)) return false; if(!results_.Equals(other.results_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (partialFailureError_ != null) hash ^= PartialFailureError.GetHashCode(); hash ^= results_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else results_.WriteTo(output, _repeated_results_codec); if (partialFailureError_ != null) { output.WriteRawTag(26); output.WriteMessage(PartialFailureError); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { results_.WriteTo(ref output, _repeated_results_codec); if (partialFailureError_ != null) { output.WriteRawTag(26); output.WriteMessage(PartialFailureError); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (partialFailureError_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(PartialFailureError); } size += results_.CalculateSize(_repeated_results_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MutateAdGroupLabelsResponse other) { if (other == null) { return; } if (other.partialFailureError_ != null) { if (partialFailureError_ == null) { PartialFailureError = new global::Google.Rpc.Status(); } PartialFailureError.MergeFrom(other.PartialFailureError); } results_.Add(other.results_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 18: { results_.AddEntriesFrom(input, _repeated_results_codec); break; } case 26: { if (partialFailureError_ == null) { PartialFailureError = new global::Google.Rpc.Status(); } input.ReadMessage(PartialFailureError); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 18: { results_.AddEntriesFrom(ref input, _repeated_results_codec); break; } case 26: { if (partialFailureError_ == null) { PartialFailureError = new global::Google.Rpc.Status(); } input.ReadMessage(PartialFailureError); break; } } } } #endif } /// <summary> /// The result for an ad group label mutate. /// </summary> public sealed partial class MutateAdGroupLabelResult : pb::IMessage<MutateAdGroupLabelResult> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<MutateAdGroupLabelResult> _parser = new pb::MessageParser<MutateAdGroupLabelResult>(() => new MutateAdGroupLabelResult()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MutateAdGroupLabelResult> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V5.Services.AdGroupLabelServiceReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MutateAdGroupLabelResult() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MutateAdGroupLabelResult(MutateAdGroupLabelResult other) : this() { resourceName_ = other.resourceName_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MutateAdGroupLabelResult Clone() { return new MutateAdGroupLabelResult(this); } /// <summary>Field number for the "resource_name" field.</summary> public const int ResourceNameFieldNumber = 1; private string resourceName_ = ""; /// <summary> /// Returned for successful operations. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ResourceName { get { return resourceName_; } set { resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MutateAdGroupLabelResult); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MutateAdGroupLabelResult other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ResourceName != other.ResourceName) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ResourceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MutateAdGroupLabelResult other) { if (other == null) { return; } if (other.ResourceName.Length != 0) { ResourceName = other.ResourceName; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { ResourceName = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { ResourceName = input.ReadString(); break; } } } } #endif } #endregion } #endregion Designer generated code
37.245252
371
0.680361
[ "Apache-2.0" ]
PierrickVoulet/google-ads-dotnet
src/V5/Services/AdGroupLabelService.cs
45,104
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace SandboxDatabaseManager.Models { public class CopyDatabaseDetails { public string SourceDatabaseServer { get; set; } public string SourceDatabaseName { get; set; } public decimal SourceDatabaseSizeGB { get; set; } public string SourceDatabaseRecoveryModel { get; set; } public string TargetDatabaseServer { get; set; } [Required] [Display(Name = "Target Database Name")] [MaxLength(100)] public string TargetDatabaseName { get; set; } public string LastWarningMessage { get; set; } [MaxLength(255)] public string DatabaseComment { get; set; } public bool RecoveryModelChangeToSimple { get; set; } } }
33.192308
63
0.673233
[ "MIT" ]
TomaszM81/SandboxDatabaseManager
SandboxDatabaseManager/SandboxDatabaseManager/Models/CopyDatabaseDetails.cs
865
C#
using System; using Horse.Messaging.Protocol; using Horse.Messaging.Server.Cache; using Horse.Messaging.Server.Channels; using Horse.Messaging.Server.Clients; using Horse.Messaging.Server.Direct; using Horse.Messaging.Server.Network; using Horse.Messaging.Server.Options; using Horse.Messaging.Server.Queues; using Horse.Messaging.Server.Routing; using Horse.Server; namespace Horse.Messaging.Server { /// <summary> /// Extension Methods for Horse.Messaging.Server /// </summary> public static class HorseRiderExtensions { #region Use Horse /// <summary> /// Uses Horse.Messaging.Server Messaging Queue server /// </summary> public static HorseServer UseRider(this HorseServer server, HorseRider horseRider) { HorseNetworkHandler handler = new HorseNetworkHandler(horseRider); horseRider.Server = server; horseRider.NodeManager.ConnectionHandler = new NodeConnectionHandler(horseRider.NodeManager, handler); server.UseHorseProtocol(handler); if (horseRider.NodeManager != null) horseRider.NodeManager.SubscribeStartStop(server); return server; } /// <summary> /// Uses Horse.Messaging.Server Messaging Queue server /// </summary> public static HorseRider UseRider(this HorseServer server, Action<HorseRiderBuilder> cfg) { HorseRider rider = new HorseRider(); HorseNetworkHandler handler = new HorseNetworkHandler(rider); rider.Server = server; rider.NodeManager.ConnectionHandler = new NodeConnectionHandler(rider.NodeManager, handler); server.UseHorseProtocol(handler); if (rider.NodeManager != null) rider.NodeManager.SubscribeStartStop(server); HorseRiderBuilder builder = new HorseRiderBuilder(); builder.Rider = rider; cfg(builder); rider.Initialize(); return rider; } #endregion #region Options /// <summary> /// Sets Horse MQ Options /// </summary> public static HorseRiderBuilder ConfigureOptions(this HorseRiderBuilder builder, Action<HorseRiderOptions> options) { if (builder.Rider.Options == null) builder.Rider.Options = new HorseRiderOptions(); options(builder.Rider.Options); return builder; } /// <summary> /// Uses Custom Client Id Generator. /// Default is DefaultUniqueIdGenerator. /// </summary> public static HorseRiderBuilder UseClientIdGenerator<TUniqueIdGenerator>(this HorseRiderBuilder builder) where TUniqueIdGenerator : IUniqueIdGenerator, new() { builder.Rider.Client.ClientIdGenerator = new TUniqueIdGenerator(); return builder; } /// <summary> /// Uses Custom Client Id Generator. /// Default is DefaultUniqueIdGenerator. /// </summary> public static HorseRiderBuilder UseClientIdGenerator(this HorseRiderBuilder builder, IUniqueIdGenerator generator) { builder.Rider.Client.ClientIdGenerator = generator; return builder; } /// <summary> /// Uses Custom Message Id Generator. /// Default is DefaultUniqueIdGenerator. /// </summary> public static HorseRiderBuilder UseMessageIdGenerator<TUniqueIdGenerator>(this HorseRiderBuilder builder) where TUniqueIdGenerator : IUniqueIdGenerator, new() { builder.Rider.MessageIdGenerator = new TUniqueIdGenerator(); return builder; } /// <summary> /// Uses Custom Message Id Generator. /// Default is DefaultUniqueIdGenerator. /// </summary> public static HorseRiderBuilder UseMessageIdGenerator(this HorseRiderBuilder builder, IUniqueIdGenerator generator) { builder.Rider.MessageIdGenerator = generator; return builder; } #endregion /// <summary> /// Configure clients /// </summary> public static HorseRiderBuilder ConfigureClients(this HorseRiderBuilder builder, Action<HorseClientConfigurator> cfg) { HorseClientConfigurator configurator = new HorseClientConfigurator(builder.Rider); cfg(configurator); return builder; } /// <summary> /// Configure cache /// </summary> public static HorseRiderBuilder ConfigureCache(this HorseRiderBuilder builder, Action<HorseCacheConfigurator> cfg) { HorseCacheConfigurator configurator = new HorseCacheConfigurator(builder.Rider); cfg(configurator); return builder; } /// <summary> /// Configure channels /// </summary> public static HorseRiderBuilder ConfigureChannels(this HorseRiderBuilder builder, Action<HorseChannelConfigurator> cfg) { HorseChannelConfigurator configurator = new HorseChannelConfigurator(builder.Rider); cfg(configurator); return builder; } /// <summary> /// Configure routers /// </summary> public static HorseRiderBuilder ConfigureRouters(this HorseRiderBuilder builder, Action<HorseRouterConfigurator> cfg) { HorseRouterConfigurator configurator = new HorseRouterConfigurator(builder.Rider); cfg(configurator); return builder; } /// <summary> /// Configure queues /// </summary> public static HorseRiderBuilder ConfigureQueues(this HorseRiderBuilder builder, Action<HorseQueueConfigurator> cfg) { HorseQueueConfigurator configurator = new HorseQueueConfigurator(builder.Rider); cfg(configurator); return builder; } /// <summary> /// Configure direct messages /// </summary> public static HorseRiderBuilder ConfigureDirect(this HorseRiderBuilder builder, Action<HorseDirectConfigurator> cfg) { HorseDirectConfigurator configurator = new HorseDirectConfigurator(builder.Rider); cfg(configurator); return builder; } #region Events /// <summary> /// Adds error handler /// </summary> public static HorseRiderBuilder AddErrorHandler<TErrorHandler>(this HorseRiderBuilder builder) where TErrorHandler : IErrorHandler, new() { builder.Rider.ErrorHandlers.Add(new TErrorHandler()); return builder; } /// <summary> /// Adds error handler /// </summary> public static HorseRiderBuilder AddErrorHandler(this HorseRiderBuilder builder, IErrorHandler errorHandler) { builder.Rider.ErrorHandlers.Add(errorHandler); return builder; } /// <summary> /// Uses server type message event handler /// </summary> public static HorseRiderBuilder AddServerMessageHandler<TServerMessageHandler>(this HorseRiderBuilder builder) where TServerMessageHandler : IServerMessageHandler, new() { builder.Rider.ServerMessageHandlers.Add(new TServerMessageHandler()); return builder; } /// <summary> /// Uses a custom server message handler /// </summary> [Obsolete("This method adds new handler, use AddServerMessageHandler instead")] public static HorseRiderBuilder UseServerMessageHandler(this HorseRiderBuilder builder, IServerMessageHandler messageHandler) { return AddServerMessageHandler(builder, messageHandler); } /// <summary> /// Uses a custom server message handler /// </summary> public static HorseRiderBuilder AddServerMessageHandler(this HorseRiderBuilder builder, IServerMessageHandler messageHandler) { builder.Rider.ServerMessageHandlers.Add(messageHandler); return builder; } #endregion } }
35.323404
133
0.63149
[ "Apache-2.0" ]
twino-framework/horse-mq
src/Horse.Messaging.Server/HorseRiderExtensions.cs
8,301
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GetDelegate")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Independentsoft")] [assembly: AssemblyProduct("GetDelegate")] [assembly: AssemblyCopyright("Copyright © Independentsoft 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("207cd634-beba-40f5-9ddd-ebba6aab6002")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.176471
84
0.756329
[ "MIT" ]
age-killer/Electronic-invoice-document-processing
MailSort_CSHARP/packages/Independentsoft.Exchange.3.0.400/Tutorial/GetDelegate/Properties/AssemblyInfo.cs
1,267
C#
using BattleTech; using Harmony; using Localize; using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace TisButAScratch.Patches { public class FloatyPatches { [HarmonyPatch(typeof(AbstractActor), "CheckPilotStatusFromAttack")] static class AbstractActor_CheckPilotStatusFromAttack { static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator ilGenerator) { List<CodeInstruction> codes = new List<CodeInstruction>(instructions); // Create a new label for our target point Label clearNeedsInjuryLabel = ilGenerator.DefineLabel(); MethodInfo clearNeedsInjuryMI = AccessTools.DeclaredMethod(typeof(Pilot), "ClearNeedsInjury"); int injuryStrIdx = 0, clearInjuryIdx = 0; for (int i = 0; i < codes.Count; i++) { CodeInstruction instruction = codes[i]; if (instruction.opcode == OpCodes.Ldstr && "{0}: PILOT INJURED".Equals((string)instruction.operand, StringComparison.InvariantCultureIgnoreCase)) { injuryStrIdx = i; ModInit.modLog.LogMessage($"Found PILOT INJURED instruction at idx: {i}"); } else if (instruction.opcode == OpCodes.Callvirt && (MethodInfo)instruction.operand == clearNeedsInjuryMI) { clearInjuryIdx = i; ModInit.modLog.LogMessage($"Found Pilot.ClearNeedsInjury instruction at idx: {i}"); } } CodeInstruction cnjInstruction = codes[clearInjuryIdx - 1]; cnjInstruction.labels.Add(clearNeedsInjuryLabel); codes.RemoveRange(injuryStrIdx, 15); codes.Insert(injuryStrIdx - 1, new CodeInstruction(OpCodes.Br_S, clearNeedsInjuryLabel)); return codes; } } [HarmonyPatch(typeof(Mech), "CompleteKnockdown")] static class Mech_CompleteKnockdown { static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> codes = new List<CodeInstruction>(instructions); int targetIdx = 0; for (int i = 0; i < codes.Count; i++) { CodeInstruction instruction = codes[i]; if (instruction.opcode == OpCodes.Ldstr && "KNOCKDOWN: PILOT INJURED".Equals((string)instruction.operand, StringComparison.InvariantCultureIgnoreCase)) { targetIdx = i; ModInit.modLog.LogMessage($"KNOCKDOWN: PILOT INJURED instruction at idx: {i}"); } } codes.RemoveRange(targetIdx - 4, 12); return codes; } } } }
40.342105
171
0.573712
[ "MIT" ]
ajkroeg/TisButAScratch
Patches/FloatyPatches.cs
3,068
C#
// ------------------------------------------------------------------------------------------------ // Copyright (c) 2021 Ruzsinszki Gábor // This is free software under the terms of the MIT License. https://opensource.org/licenses/MIT // ------------------------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.IO; using System.Text.Json; namespace TcPlayer.Engine.Settings { public sealed class SettingsFile: ISettingsFile { private readonly string _openFileName; private readonly Dictionary<Setting, string> _storage; public SettingsFile(string fileName) { _storage = new Dictionary<Setting, string>(); _openFileName = fileName; if (File.Exists(_openFileName)) { var temp = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, string>>>(File.ReadAllText(_openFileName)); if (temp == null) throw new InvalidOperationException(); foreach (var container in temp.Keys) { foreach (var setting in temp[container]) { _storage.Add(new Setting { Container = Guid.Parse(container), Key = setting.Key }, setting.Value); } } } Settings = new SettingsProvider(_storage); } public ISettingProvider Settings { get; } public void Save() { var toSerialize = new Dictionary<string, Dictionary<string, string>>(); foreach (var item in _storage) { var containerId = item.Key.Container.ToString(); if (toSerialize.ContainsKey(containerId)) { toSerialize[containerId].Add(item.Key.Key, item.Value); } else { toSerialize.Add(containerId, new Dictionary<string, string>()); toSerialize[containerId].Add(item.Key.Key, item.Value); } } var newContents = JsonSerializer.Serialize(toSerialize, new JsonSerializerOptions { WriteIndented = true, }); var oldfile = Path.ChangeExtension(_openFileName, ".old"); if (File.Exists(_openFileName)) File.Move(_openFileName, oldfile); using (var f = File.CreateText(_openFileName)) { f.Write(newContents); } File.Delete(oldfile); } } }
34.195122
135
0.481098
[ "MIT" ]
webmaster442/TcPlayer2
TcPlayer.Engine/Settings/SettingsFile.cs
2,807
C#
// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. using System; namespace Xtensive.Sql { /// <summary> /// Base class for SQL statements. /// </summary> [Serializable] public abstract class SqlStatement : SqlNode { protected SqlStatement(SqlNodeType nodeType) : base(nodeType) { } } }
19.2
65
0.679688
[ "MIT" ]
DataObjects-NET/dataobjects-net
Orm/Xtensive.Orm/Sql/SqlStatement.cs
384
C#
using System; using System.Collections.Generic; using Entitas; using UnityEngine; namespace Game.Logic { public class StoneFallSystem : ReactiveSystem<GameEntity> { Contexts contexts; public StoneFallSystem(Contexts contexts) : base(contexts.game) { this.contexts = contexts; } protected override ICollector<GameEntity> GetTrigger(IContext<GameEntity> context) { //return context.CreateCollector(GameMatcher.PositionInt.Added()); throw new NotImplementedException(); } protected override bool Filter(GameEntity entity) { //return entity.hasObjectType // && entity.objectType.value == ObjectType.Stone // && !contexts.HasObject(entity.positionInt.value + Vector2Int.up, ObjectType.Stone); throw new NotImplementedException(); } protected override void Execute(List<GameEntity> entities) { foreach (var gameEntity in entities) { //var pos = gameEntity.positionInt.value; //var to = pos + Vector2Int.down; //if (contexts.IsEmpty(pos + Vector2Int.left) && contexts.IsEmpty(to)) //{ // contexts.Move(pos, to); // continue; //} //to = pos + new Vector2Int(-1, -1); //if (contexts.IsEmpty(pos + Vector2Int.left) && contexts.IsEmpty(to)) //{ // contexts.Move(pos, to); // continue; //} //to = pos + new Vector2Int(1, -1); //if (contexts.IsEmpty(pos + Vector2Int.right) && contexts.IsEmpty(to)) //{ // contexts.Move(pos, to); // continue; //} throw new System.NotImplementedException(); } } } }
34.017241
101
0.519007
[ "MIT" ]
shsa/unity
Supaplex/Assets/Game/Scripts/Logic/Systems/StoneFallSystem.cs
1,975
C#
namespace Machete.X12Schema.V5010.Maps { using X12; using X12.Configuration; public class FGSMap : X12SegmentMap<FGS, X12Entity> { public FGSMap() { Id = "FGS"; Name = "Form Group"; Value(x => x.AssignedIdentifier, 1, x => x.MinLength(1).MaxLength(20)); Value(x => x.ReferenceIdentificationQualifier, 1, x => x.MinLength(2).MaxLength(3)); Value(x => x.ReferenceIdentification, 2, x => x.MinLength(1).MaxLength(50)); } } }
26.8
96
0.559701
[ "Apache-2.0" ]
ahives/Machete
src/Machete.X12Schema/V5010/Segments/Maps/FGSMap.cs
536
C#
//----------------------------------------------------------------------- // Copyright 2017 Roman Tumaykin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //----------------------------------------------------------------------- using System.Collections.Generic; using System.IO; namespace SsisBuild.Core.ProjectManagement { public interface IProjectFile { IReadOnlyDictionary<string, IParameter> Parameters { get; } ProtectionLevel ProtectionLevel { get; set; } void Initialize(string filePath, string password); void Initialize(Stream fileStream, string password); void Save(string filePath); void Save(Stream fileStream); void Save(string filePath, ProtectionLevel protectionLevel, string password); void Save(Stream fileStream, ProtectionLevel protectionLevel, string password); } }
41.058824
87
0.644699
[ "Apache-2.0" ]
ConstantineK/ssis-build
src/SsisBuild.Core/ProjectManagement/IProjectFile.cs
1,398
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Combo_Spear : MonoBehaviour { // Start is called before the first frame update private PlayerPhone player; private float attackSpecialCd = 10.02f; private float attackSpecialDuration; private bool spearAttacking = false; public Collider2D spearAttackTrigger; private Animator anim; private PlayerAttack playerAttackSpear; void Start() { player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerPhone>(); playerAttackSpear = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerAttack>(); anim = gameObject.GetComponent<Animator>(); spearAttackTrigger.enabled = false; } // Update is called once per frame void Update() { SpecialAttackSpear(); } public void SpecialAttackSpear() { if(player.myResistance == 5 && Input.GetKeyDown("o") && playerAttackSpear.weaponSelected == 2) { Debug.Log("pene"); spearAttacking = true; attackSpecialDuration = attackSpecialCd; spearAttackTrigger.enabled = true; player.speedX += player.speedX + 4.2f; if (spearAttackTrigger.IsTouchingLayers(LayerMask.GetMask("Enemy"))) { spearAttackTrigger.enabled = false; spearAttackTrigger.enabled = true; } } if (spearAttacking) { if(attackSpecialDuration > 0) { attackSpecialDuration -= Time.deltaTime; } else{ player.myResistance = 0; spearAttackTrigger.enabled = false; spearAttacking = false; player.speedX -= player.speedX - 4.2F; } } // anim.SetBool("walking_left", spearAttacking); } }
30.967742
102
0.60625
[ "MIT" ]
NikoSilveira/Civilization-Rush
Assets/Scripts/Player/Combos/Combo_Spear.cs
1,922
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(CanvasGroup))] public abstract class MenuBase : MonoBehaviour { [NonSerialized] public MenuManager MenuManager; protected CanvasGroup canvasGroup; protected virtual void Awake() { canvasGroup = GetComponent<CanvasGroup>(); } public virtual void Show() { gameObject.SetActive(true); canvasGroup.interactable = canvasGroup.blocksRaycasts = true; canvasGroup.alpha = 1.0f; OnEnter(); } public virtual void Hide() { canvasGroup.interactable = canvasGroup.blocksRaycasts = false; canvasGroup.alpha = 0.0f; OnExit(); gameObject.SetActive(false); } protected virtual void OnEnter() { } protected virtual void OnExit() { } }
23.333333
64
0.753247
[ "MIT" ]
Enter-your-name-studio/AB-Game-Jam
ABJam/Assets/Scripts/Menu/MenuBase.cs
772
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace CaveStory { public class PowerDoritoPickup : MapCollidable, IPickup { public enum SizeType { Small, Medium, Large } static GunExperienceUnit[] Values { get { return new GunExperienceUnit[] { 1, 5, 20 }; } } const string SpriteName = "Npc\\NpcSym"; static TileUnit SourceX { get { return 0; } } static TileUnit[] SourceYs { get { return new TileUnit[] { 1, 2, 3 }; } } static TileUnit SourceWidth = 1; static TileUnit SourceHeight = 1; const int Fps = 14; static FrameUnit NumFrames { get { return 6; } } static TimeSpan LifeTime { get { return TimeSpan.FromMilliseconds(8000); } } static TimeSpan FlashTime { get { return TimeSpan.FromMilliseconds(7000); } } static TimeSpan FlashPeriod { get { return TimeSpan.FromMilliseconds(50); } } static VelocityUnit BounceSpeed { get { return 0.225f; } } static FrictionAccelerator Friction { get { return new FrictionAccelerator(0.00002f); } } static SimpleCollisionRectangle[] CollisionRectangles { get { return new SimpleCollisionRectangle[] { new SimpleCollisionRectangle(new Rectangle(8, 8, 16, 16)), new SimpleCollisionRectangle(new Rectangle(4, 4, 24, 24)), new SimpleCollisionRectangle(new Rectangle(0, 0, 32, 32)) }; } } public Pickup.PickupType Type { get { return Pickup.PickupType.Experience; } } public int Value { get { return Values[(int)size]; } } public Rectangle CollisionRectangle { get { return new Rectangle((int)Math.Round(kinematicsX.position) + CollisionRectangles[(int)size].BoundingBox.Left, (int)Math.Round(kinematicsY.position) + CollisionRectangles[(int)size].BoundingBox.Top, CollisionRectangles[(int)size].BoundingBox.Width, CollisionRectangles[(int)size].BoundingBox.Height); } } Kinematics kinematicsX; Kinematics kinematicsY; AnimatedSprite sprite; SizeType size; Timer timer; public PowerDoritoPickup(ContentManager Content, GameUnit centerX, GameUnit centerY, SizeType size) : base(CollisionType.BouncingCollision) { kinematicsX = new Kinematics(centerX - Units.HalfTile, (Game1.Random.Next(0, 11) - 5) * 0.025f); kinematicsY = new Kinematics(centerY - Units.HalfTile, (Game1.Random.Next(0, 11) - 5) * 0.025f); sprite = new AnimatedSprite(Content, SpriteName, Units.TileToPixel(SourceX), Units.TileToPixel(SourceYs[(int)size]), Units.TileToPixel(SourceWidth), Units.TileToPixel(SourceHeight), Fps, NumFrames); this.size = size; timer = new Timer(LifeTime, true); } public bool Update(GameTime gameTime, Map map) { sprite.Update(); UpdateX(CollisionRectangles[(int)size], Friction, kinematicsX, kinematicsY, gameTime, map); UpdateY(CollisionRectangles[(int)size], ConstantAccelerator.Gravity, kinematicsX, kinematicsY, gameTime, map, null); return timer.Active; } protected override void OnCollision(TileInfo.SideType side, bool isDeltaDirection, BitArray tileType) { if (side == TileInfo.SideType.TopSide) { kinematicsY.velocity = 0; } else if (side == TileInfo.SideType.BottomSide) { kinematicsY.velocity = -BounceSpeed; } else { kinematicsX.velocity *= -1; } } protected override void OnDelta(TileInfo.SideType side) { } public void Draw(SpriteBatch spriteBatch) { if (timer.CurrentTime < FlashTime || timer.CurrentTime.Ticks / FlashPeriod.Ticks % 2 == 0) { sprite.Draw(spriteBatch, kinematicsX.position, kinematicsY.position); } } } }
35.882813
147
0.578271
[ "MIT" ]
golf1052/CaveStory
CaveStory/PowerDoritoPickup.cs
4,595
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ControlNumber")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ControlNumber")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a455ae17-95b7-43e6-823a-2bb46065f557")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.675676
84
0.748207
[ "MIT" ]
dragobaltov/Programming-Basics-And-Fundamentals
ControlNumber/ControlNumber/Properties/AssemblyInfo.cs
1,397
C#
using System; namespace _12._Number_Checker { class Program { static void Main(string[] args) { try { int number = int.Parse(Console.ReadLine()); Console.WriteLine("It is a number."); } catch (Exception) { Console.WriteLine("Invalid input!"); } } } }
19
59
0.390351
[ "MIT" ]
Svetloslav15/Softuni-Programming-Fundamentals
03.C# Conditional Statements and Loops - Lab/12. Number Checker/Program.cs
458
C#
//****************************************************************************************************** // ReadInputAdapter.cs // // Copyright © 2016, Duotong Yang All Rights Reserved. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 11/09/2016 - Duotong Yang // Generated original version of source code. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; using System.IO; using System.Collections; using VoltController.VcControlDevice; using VoltController.Adapters; using VoltController.VcSubRoutines; namespace VoltController.Adapters { public class ReadInputAdapter { #region [ Private Members ] private Dictionary<string, VcTransformer> m_controlTransformers; //VoltVarController vc; #endregion #region [ Private Methods ] #region [ Read the InputData ] private void ReadSubAlarm(VoltVarController vc, string SubAlarmPathName) { CsvAdapter csvRead = new CsvAdapter(); csvRead.ReadCSV(SubAlarmPathName); vc.SubstationAlarmDevice.Host = csvRead.Frame[1, 0]; vc.SubstationAlarmDevice.SwSchedId = csvRead.Frame[1, 1]; vc.SubstationAlarmDevice.SwSchedField = csvRead.Frame[1, 2]; vc.SubstationAlarmDevice.SwSchedClear = csvRead.Frame[1, 3]; vc.SubstationAlarmDevice.LtcDevice = csvRead.Frame[1, 4]; vc.SubstationAlarmDevice.ContFail = csvRead.Frame[1, 5]; vc.SubstationAlarmDevice.LtcLimit = csvRead.Frame[1, 6]; vc.SubstationAlarmDevice.OutService = csvRead.Frame[1, 7]; vc.SubstationAlarmDevice.VoltsOut = csvRead.Frame[1, 8]; vc.SubstationAlarmDevice.LtcProgram = csvRead.Frame[1, 9]; vc.SubstationAlarmDevice.ZNTX = Convert.ToInt32(csvRead.Frame[1, 10]); vc.SubstationAlarmDevice.ZNCP = Convert.ToInt32(csvRead.Frame[1, 11]); vc.SubstationAlarmDevice.ZVLO = Convert.ToDouble(csvRead.Frame[1, 12]); vc.SubstationAlarmDevice.VLLIM = Convert.ToDouble(csvRead.Frame[1, 13]); vc.SubstationAlarmDevice.VHLIM = Convert.ToDouble(csvRead.Frame[1, 14]); vc.SubstationAlarmDevice.ZVHI = Convert.ToDouble(csvRead.Frame[1, 15]); vc.SubstationAlarmDevice.ZHITAP = Convert.ToInt32(csvRead.Frame[1, 16]); vc.SubstationAlarmDevice.ZLOTAP = Convert.ToInt32(csvRead.Frame[1, 17]); vc.SubstationAlarmDevice.ZTCONS = Convert.ToInt32(csvRead.Frame[1, 18]); vc.SubstationAlarmDevice.ZBAL = Convert.ToDouble(csvRead.Frame[1, 19]); vc.SubstationAlarmDevice.ZLOWV = Convert.ToDouble(csvRead.Frame[1, 20]); vc.SubstationAlarmDevice.ZDIFTAP = Convert.ToDouble(csvRead.Frame[1, 21]); } private void ReadSubInformation(VoltVarController vc,string SubInformationPath, int rowNumber) { CsvAdapter csvRead = new CsvAdapter(); csvRead.ReadCSV(SubInformationPath); vc.SubstationInformation.SubDevId = csvRead.Frame[rowNumber, 0]; vc.SubstationInformation.TieId = csvRead.Frame[rowNumber, 1]; vc.SubstationInformation.TieV = Convert.ToInt32(csvRead.Frame[rowNumber, 2]); vc.SubstationInformation.CloverDev = csvRead.Frame[rowNumber, 3]; vc.SubstationInformation.G1MwId = csvRead.Frame[rowNumber, 4]; vc.SubstationInformation.G1MvrId = csvRead.Frame[rowNumber, 5]; vc.SubstationInformation.G2MwId = csvRead.Frame[rowNumber, 6]; vc.SubstationInformation.G2MvrId = csvRead.Frame[rowNumber, 7]; vc.SubstationInformation.G1Mw = Convert.ToDouble(csvRead.Frame[rowNumber, 8]); vc.SubstationInformation.G1Mvr = Convert.ToDouble(csvRead.Frame[rowNumber, 9]); vc.SubstationInformation.G2Mw = Convert.ToDouble(csvRead.Frame[rowNumber, 10]); vc.SubstationInformation.G2Mvr = Convert.ToDouble(csvRead.Frame[rowNumber, 11]); vc.SubstationInformation.ConsecTap = Convert.ToInt32(csvRead.Frame[rowNumber, 12]); vc.SubstationInformation.ConsecCap = Convert.ToInt32(csvRead.Frame[rowNumber, 13]); vc.SubstationInformation.Ncdel = Convert.ToInt32(csvRead.Frame[rowNumber, 14]); vc.SubstationInformation.Ntdel = Convert.ToInt32(csvRead.Frame[rowNumber, 15]); vc.SubstationInformation.OldDay = Convert.ToInt32(csvRead.Frame[rowNumber, 16]); vc.SubstationInformation.Zcdel = Convert.ToInt32(csvRead.Frame[rowNumber, 17]); vc.SubstationInformation.Zdel = Convert.ToInt32(csvRead.Frame[rowNumber, 18]); vc.SubstationInformation.Zmaxtrip = Convert.ToInt32(csvRead.Frame[rowNumber, 19]); vc.SubstationInformation.Zmaxclose = Convert.ToInt32(csvRead.Frame[rowNumber, 20]); vc.SubstationInformation.Zccons = Convert.ToInt32(csvRead.Frame[rowNumber, 21]); vc.SubstationInformation.Zclmvr = Convert.ToDouble (csvRead.Frame[rowNumber, 22]); vc.SubstationInformation.Ztrmvr = Convert.ToDouble(csvRead.Frame[rowNumber, 23]); vc.SubstationInformation.Alarm = csvRead.Frame[rowNumber, 24]; vc.SubstationInformation.Normal = csvRead.Frame[rowNumber, 25]; vc.SubstationInformation.Raise = csvRead.Frame[rowNumber, 26]; vc.SubstationInformation.Lower = csvRead.Frame[rowNumber, 27]; vc.SubstationInformation.ON = csvRead.Frame[rowNumber, 28]; vc.SubstationInformation.OFF = csvRead.Frame[rowNumber, 29]; vc.SubstationInformation.Close = csvRead.Frame[rowNumber, 30]; vc.SubstationInformation.Trip = csvRead.Frame[rowNumber, 31]; vc.SubstationInformation.Remote = csvRead.Frame[rowNumber, 32]; vc.SubstationInformation.Local = csvRead.Frame[rowNumber, 33]; vc.SubstationInformation.Auto = csvRead.Frame[rowNumber, 34]; vc.SubstationInformation.Manual = csvRead.Frame[rowNumber, 35]; vc.SubstationInformation.Dashes = csvRead.Frame[rowNumber, 36]; } private void ReadTransformer(VoltVarController vc, string datafolder, int rowNumber) { for (int i = 0; i < vc.SubstationAlarmDevice.ZNTX; i++) { int k = i + 1; CsvAdapter csvRead = new CsvAdapter(); csvRead.ReadCSV(string.Format(datafolder + "Transformer{0}.csv", k)); vc.ControlTransformers[i].DeviceId = csvRead.Frame[rowNumber, 0]; vc.ControlTransformers[i].LocRemId = csvRead.Frame[rowNumber, 1]; vc.ControlTransformers[i].LocRemV = csvRead.Frame[rowNumber, 2]; vc.ControlTransformers[i].ScadaSw = csvRead.Frame[rowNumber, 3]; vc.ControlTransformers[i].ScadaSwV = csvRead.Frame[rowNumber, 4]; vc.ControlTransformers[i].HighSideId = csvRead.Frame[rowNumber, 5]; vc.ControlTransformers[i].HighSideV = Convert.ToInt32(csvRead.Frame[rowNumber, 6]); vc.ControlTransformers[i].LowSideId = csvRead.Frame[rowNumber, 7]; vc.ControlTransformers[i].LowSideV = Convert.ToInt32(csvRead.Frame[rowNumber, 8]); vc.ControlTransformers[i].TapId = csvRead.Frame[rowNumber, 9]; vc.ControlTransformers[i].TapV = Convert.ToInt32(csvRead.Frame[rowNumber, 10]); vc.ControlTransformers[i].StTapV = Convert.ToInt32(csvRead.Frame[rowNumber, 11]); vc.ControlTransformers[i].MwId = csvRead.Frame[rowNumber, 12]; vc.ControlTransformers[i].MwV = Convert.ToDouble(csvRead.Frame[rowNumber, 13]); vc.ControlTransformers[i].MvrId = csvRead.Frame[rowNumber, 14]; vc.ControlTransformers[i].MvrV = Convert.ToDouble(csvRead.Frame[rowNumber, 15]); vc.ControlTransformers[i].StMvrV = Convert.ToInt32(csvRead.Frame[rowNumber, 16]); vc.ControlTransformers[i].VoltsId = csvRead.Frame[rowNumber, 17]; vc.ControlTransformers[i].VoltsV = Convert.ToDouble(csvRead.Frame[rowNumber, 18]); vc.ControlTransformers[i].VoltsTime = Convert.ToInt32(csvRead.Frame[rowNumber, 19]); vc.ControlTransformers[i].LtcCtlId = csvRead.Frame[rowNumber, 20]; vc.ControlTransformers[i].TapTime = Convert.ToInt32(csvRead.Frame[rowNumber, 21]); vc.ControlTransformers[i].CtlDone = Convert.ToInt32(csvRead.Frame[rowNumber, 22]); vc.ControlTransformers[i].InSvc = Convert.ToInt32(csvRead.Frame[rowNumber, 23]); vc.ControlTransformers[i].PrevCtl = csvRead.Frame[rowNumber, 24]; vc.ControlTransformers[i].MvrBal = Convert.ToInt32(csvRead.Frame[rowNumber, 25]); vc.ControlTransformers[i].IRange = csvRead.Frame[rowNumber, 26]; } } private void ReadCapBanks(VoltVarController vc, string datafolder, int rowNumber) { for (int i = 0; i < vc.SubstationAlarmDevice.ZNCP; i++) { int k = i + 1; CsvAdapter csvRead = new CsvAdapter(); csvRead.ReadCSV(string.Format(datafolder + "CapBank{0}.csv", k)); vc.ControlCapacitorBanks[i].OpCapDev = csvRead.Frame[rowNumber, 0]; vc.ControlCapacitorBanks[i].OpCapId = csvRead.Frame[rowNumber, 1]; vc.ControlCapacitorBanks[i].OpCapV = csvRead.Frame[rowNumber, 2]; vc.ControlCapacitorBanks[i].ScadaSwId = csvRead.Frame[rowNumber, 3]; vc.ControlCapacitorBanks[i].ScadaSwV = csvRead.Frame[rowNumber, 4]; vc.ControlCapacitorBanks[i].LocRemId = csvRead.Frame[rowNumber, 5]; vc.ControlCapacitorBanks[i].LocRemV = csvRead.Frame[rowNumber, 6]; vc.ControlCapacitorBanks[i].AutoManId = csvRead.Frame[rowNumber, 7]; vc.ControlCapacitorBanks[i].AutoManV = vc.SubstationInformation.Manual; vc.ControlCapacitorBanks[i].MiscId = csvRead.Frame[rowNumber, 9]; vc.ControlCapacitorBanks[i].MiscV = csvRead.Frame[rowNumber, 10]; vc.ControlCapacitorBanks[i].BusBkrId = csvRead.Frame[rowNumber, 11]; vc.ControlCapacitorBanks[i].BusBkrV = csvRead.Frame[rowNumber, 12]; vc.ControlCapacitorBanks[i].CapBkrId = csvRead.Frame[rowNumber, 13]; vc.ControlCapacitorBanks[i].CapBkrV = csvRead.Frame[rowNumber, 14]; vc.ControlCapacitorBanks[i].Clov = Convert.ToDouble(csvRead.Frame[rowNumber, 15]); vc.ControlCapacitorBanks[i].Chiv = Convert.ToDouble(csvRead.Frame[rowNumber, 16]); vc.ControlCapacitorBanks[i].Alovc = Convert.ToDouble(csvRead.Frame[rowNumber, 17]); vc.ControlCapacitorBanks[i].Ahivt = Convert.ToDouble(csvRead.Frame[rowNumber, 18]); vc.ControlCapacitorBanks[i].LockvDev = csvRead.Frame[rowNumber, 19]; vc.ControlCapacitorBanks[i].LockvId = csvRead.Frame[rowNumber, 20]; vc.ControlCapacitorBanks[i].LockvV = Convert.ToDouble(csvRead.Frame[rowNumber, 21]); vc.ControlCapacitorBanks[i].CapCtlDev = csvRead.Frame[rowNumber, 22]; vc.ControlCapacitorBanks[i].CapCtlId = csvRead.Frame[rowNumber, 23]; vc.ControlCapacitorBanks[i].Rtu = Convert.ToInt32(csvRead.Frame[rowNumber, 24]); vc.ControlCapacitorBanks[i].CtlDone = Convert.ToInt32(csvRead.Frame[rowNumber, 25]); vc.ControlCapacitorBanks[i].InSvc = Convert.ToInt32(csvRead.Frame[rowNumber, 26]); vc.ControlCapacitorBanks[i].PrevCtl = csvRead.Frame[rowNumber, 27]; vc.ControlCapacitorBanks[i].NcTrip = Convert.ToInt32(csvRead.Frame[rowNumber, 28]); vc.ControlCapacitorBanks[i].NcClose = Convert.ToInt32(csvRead.Frame[rowNumber, 29]); vc.ControlCapacitorBanks[i].TripEx = Convert.ToInt32(csvRead.Frame[rowNumber, 30]); vc.ControlCapacitorBanks[i].CloseEx = Convert.ToInt32(csvRead.Frame[rowNumber, 31]); } } private void ReadLtcStatus(VoltVarController vc, string LtcStatusPath) { CsvAdapter csvRead = new CsvAdapter(); csvRead.ReadCSV(LtcStatusPath); vc.LtcStatus.MinVar = Convert.ToDouble(csvRead.Frame[1, 0]); vc.LtcStatus.MaxVar = Convert.ToDouble(csvRead.Frame[1, 1]); vc.LtcStatus.MinTap = Convert.ToInt32(csvRead.Frame[1, 2]); vc.LtcStatus.MaxTap = Convert.ToInt32(csvRead.Frame[1, 3]); vc.LtcStatus.Nins = Convert.ToInt32(csvRead.Frame[1, 4]); vc.LtcStatus.Avv = Convert.ToInt32(csvRead.Frame[1, 5]); vc.LtcStatus.DifTap = Convert.ToInt32(csvRead.Frame[1, 6]); vc.LtcStatus.Cfail = Convert.ToInt32(csvRead.Frame[1, 7]); vc.LtcStatus.RTX = Convert.ToInt32(csvRead.Frame[1, 8]); vc.LtcStatus.LTX = Convert.ToInt32(csvRead.Frame[1, 9]); } private void CreateDictionary(VoltVarController vc) { vc.RawkeyValuePairs = new Dictionary<string, dynamic>(); // Add Transformers foreach (VcTransformer vcTransformer in vc.ControlTransformers) { vc.RawkeyValuePairs.Add(vcTransformer.HighSideId, vcTransformer.HighSideV); vc.RawkeyValuePairs.Add(vcTransformer.LowSideId, vcTransformer.LowSideV); vc.RawkeyValuePairs.Add(vcTransformer.LocRemId, vcTransformer.LocRemV); vc.RawkeyValuePairs.Add(vcTransformer.MvrId, vcTransformer.MvrV); vc.RawkeyValuePairs.Add(vcTransformer.MwId, vcTransformer.MwV); vc.RawkeyValuePairs.Add(vcTransformer.ScadaSw, vcTransformer.ScadaSwV); vc.RawkeyValuePairs.Add(vcTransformer.TapId, vcTransformer.TapV); vc.RawkeyValuePairs.Add(vcTransformer.VoltsId, vcTransformer.VoltsV); } foreach (VcCapacitorBank vcCapacitorbank in vc.ControlCapacitorBanks) { vc.RawkeyValuePairs.Add(vcCapacitorbank.OpCapId, vcCapacitorbank.OpCapV); vc.RawkeyValuePairs.Add(vcCapacitorbank.ScadaSwId, vcCapacitorbank.ScadaSwV); vc.RawkeyValuePairs.Add(vcCapacitorbank.MiscId, vcCapacitorbank.MiscV); vc.RawkeyValuePairs.Add(vcCapacitorbank.AutoManId, vcCapacitorbank.AutoManV); vc.RawkeyValuePairs.Add(vcCapacitorbank.BusBkrId, vcCapacitorbank.BusBkrV); vc.RawkeyValuePairs.Add(vcCapacitorbank.LockvId, vcCapacitorbank.LockvV); vc.RawkeyValuePairs.Add(vcCapacitorbank.CapBkrId, vcCapacitorbank.CapBkrV); } // Add Generators vc.RawkeyValuePairs.Add(vc.SubstationInformation.G1MwId, vc.SubstationInformation.G1Mw); vc.RawkeyValuePairs.Add(vc.SubstationInformation.G1MvrId, vc.SubstationInformation.G1Mvr); vc.RawkeyValuePairs.Add(vc.SubstationInformation.G2MwId, vc.SubstationInformation.G2Mw); vc.RawkeyValuePairs.Add(vc.SubstationInformation.G2MvrId, vc.SubstationInformation.G2Mvr); } #endregion #endregion #region [ Public Methods ] public VoltVarController ReadFrame(string inputdatafolder, string fileName, int rowNumber) { ReadInputAdapter ReadIn = new ReadInputAdapter(); VoltVarController vc = new VoltVarController(); string SubAlarmPath = "SubAlarm.csv"; string SubInformationPath = "SubInformation.csv"; string LtcStatusPath = "LtcStatus.csv"; ReadIn.ReadSubAlarm(vc, inputdatafolder + SubAlarmPath); ReadIn.ReadSubInformation(vc, inputdatafolder + SubInformationPath, rowNumber); ReadIn.ReadLtcStatus(vc, inputdatafolder + LtcStatusPath); vc.LinkNetworkComponents(vc.SubstationAlarmDevice.ZNTX, vc.SubstationAlarmDevice.ZNCP); ReadIn.ReadTransformer(vc, inputdatafolder, rowNumber); ReadIn.ReadCapBanks(vc, inputdatafolder, rowNumber); ReadIn.CreateDictionary(vc); //vc.SerializeToXml(fileName); return vc; } public OpOverRides ReadOpOverRides(string inputdatafolder, string fileName) { OpOverRides overRides = new OpOverRides(); CsvAdapter csvRead = new CsvAdapter(); csvRead.ReadCSV(inputdatafolder + fileName); overRides.StatV = csvRead.Frame[1, 0]; overRides.AnalV = csvRead.Frame[1, 1]; return overRides; } #endregion } }
57.861953
105
0.639162
[ "MIT" ]
GridProtectionAlliance/openECA
Source/Analytics/LocalizedVARController/Source/LocalVoltageController/C#code/VoltController4/Adapters/ReadInputAdapter.cs
17,188
C#
using RogueSharpSample2.Abilities; using RogueSharpSample2.Core; namespace RogueSharpSample2.Systems { public static class AbilityGenerator { public static Pool<Ability> _abilityPool; public static Ability CreateAbility() { if (_abilityPool == null) { _abilityPool = new Pool<Ability>(); _abilityPool.Add(new Heal(10), 10); _abilityPool.Add(new MagicMissile(2, 80), 10); _abilityPool.Add(new RevealMap(15), 10); _abilityPool.Add(new Whirlwind(), 10); _abilityPool.Add(new Fireball(4, 60, 2), 10); _abilityPool.Add(new LightningBolt(6, 40), 10); } return _abilityPool.Get(); } } }
29.185185
63
0.563452
[ "MIT", "Unlicense" ]
rsenna/RogueSharpSamples
SadConsole-8.99/RogueSharp-4.2/Systems/AbilityGenerator.cs
790
C#
using System; using NUnit.Framework; namespace Karzina.Common.FiniteStateMachineTests { [TestFixture] public class FiniteStateMachineEngineTest { [TestCase("Turnstile")] public void TestConstructorWithValidName(string Name) { FiniteStateMachineEngine engine = new FiniteStateMachineEngine(Name); Assert.That(engine.Name, Is.EqualTo(Name)); Assert.That(engine.ManagedStates.Count, Is.EqualTo(0)); Assert.That(engine.PendingEvents.Count, Is.EqualTo(0)); } [Test] public void TestAddState() { FiniteStateMachineEngine engine = new FiniteStateMachineEngine("Turnstile"); FiniteState movingToProcessed = new FiniteState("MovingToProcessed") { OnEnterAction = () => { } }; FiniteState addedState = engine.AddState(movingToProcessed); Assert.That(addedState, Is.EqualTo(movingToProcessed)); Assert.That(engine.ManagedStates.Count, Is.EqualTo(1)); Assert.That(engine.ManagedStates.ContainsKey(movingToProcessed.Name)); } [Test] public void TestAddDuplicateState() { FiniteStateMachineEngine engine = new FiniteStateMachineEngine("Turnstile"); FiniteState movingToProcessed = new FiniteState("MovingToProcessed") { OnEnterAction = () => { } }; Assert.That(() => { FiniteState addedState = engine.AddState(movingToProcessed); addedState = engine.AddState(movingToProcessed); }, Throws.InstanceOf<ArgumentException>().And.Message.EqualTo($"Attempt to add a duplicate state '{movingToProcessed.Name}'.")); } [Test] public void TestRaiseEvent() { FiniteStateMachineEngine engine = new FiniteStateMachineEngine("Turnstile"); FiniteStateEvent actionSucceeded = new FiniteStateEvent("ActionSucceeded"); engine.RaiseEvent(actionSucceeded); Assert.That(engine.PendingEvents.Count, Is.EqualTo(1)); Assert.That(engine.PendingEvents.Contains(actionSucceeded), Is.True); } [Test] public void TestNoTransitionForEvent() { FiniteStateMachineEngine engine = new FiniteStateMachineEngine("Turnstile"); FiniteState gettingWorkItem = new FiniteState("GettingWorkItem") { OnEnterAction = () => { } }; FiniteState movingToProcessed = new FiniteState("MovingToProcessed") { OnEnterAction = () => { } }; FiniteStateEvent actionSucceeded = new FiniteStateEvent("ActionSucceeded"); engine.AddState(gettingWorkItem); engine.AddState(movingToProcessed); engine.SetCurrentState(gettingWorkItem); engine.RaiseEvent(actionSucceeded); Assert.That(() => { engine.HandlePendingEvents(); }, Throws.InstanceOf<ArgumentException>().And.Message.EqualTo($"Failed to find a transition for event '{actionSucceeded.Name}' from state '{gettingWorkItem.Name}'.")); } [Test] public void TestSetCurrentState() { FiniteStateMachineEngine engine = new FiniteStateMachineEngine("Turnstile"); FiniteState gettingWorkItem = new FiniteState("GettingWorkItem") { OnEnterAction = () => { } }; FiniteState movingToProcessed = new FiniteState("MovingToProcessed") { OnEnterAction = () => { } }; engine.AddState(gettingWorkItem); engine.AddState(movingToProcessed); Assert.That(engine.ManagedStates.Count, Is.EqualTo(2)); Assert.That(engine.ManagedStates.ContainsKey(gettingWorkItem.Name)); Assert.That(engine.ManagedStates.ContainsKey(movingToProcessed.Name)); engine.SetCurrentState(gettingWorkItem); Assert.That(engine.CurrentState, Is.EqualTo(gettingWorkItem)); engine.SetCurrentState(movingToProcessed); Assert.That(engine.CurrentState, Is.EqualTo(movingToProcessed)); } [Test] public void TestSetCurrentStateToNonManagedState() { FiniteStateMachineEngine engine = new FiniteStateMachineEngine("Turnstile"); FiniteState gettingWorkItem = new FiniteState("GettingWorkItem") { OnEnterAction = () => { } }; FiniteState movingToProcessed = new FiniteState("MovingToProcessed") { OnEnterAction = () => { } }; engine.AddState(gettingWorkItem); // do not add the second one //engine.AddState(movingToProcessed); //engine.SetCurrentState(gettingWorkItem); //Assert.That(engine.CurrentState, Is.EqualTo(gettingWorkItem)); Assert.That(() => { engine.SetCurrentState(movingToProcessed); }, Throws.InstanceOf<ArgumentException>().And.Message.EqualTo($"Attempted to set current state to '{movingToProcessed.Name}' but no state of that name is managed by this state machine.")); } } }
38.070423
200
0.603959
[ "MIT" ]
bruceanwyl/FiniteStateMachine
FiniteStateMachineTests/FiniteStateMachineEngineTest.cs
5,408
C#
using System; using System.Buffers.Text; using System.Text; using MySqlConnector.Utilities; namespace MySqlConnector.Core { internal sealed class ServerVersion { public ServerVersion(ReadOnlySpan<byte> versionString) { OriginalString = Encoding.ASCII.GetString(versionString); if (!Utf8Parser.TryParse(versionString, out int major, out var bytesConsumed) || versionString[bytesConsumed] != 0x2E) throw new InvalidOperationException("Error parsing " + OriginalString); versionString = versionString.Slice(bytesConsumed + 1); if (!Utf8Parser.TryParse(versionString, out int minor, out bytesConsumed) || versionString[bytesConsumed] != 0x2E) throw new InvalidOperationException("Error parsing " + OriginalString); versionString = versionString.Slice(bytesConsumed + 1); if (!Utf8Parser.TryParse(versionString, out int build, out bytesConsumed)) throw new InvalidOperationException("Error parsing " + OriginalString); versionString = versionString.Slice(bytesConsumed); Version = new Version(major, minor, build); // check for MariaDB version appended to a fake MySQL version if (versionString.Length != 0 && versionString[0] == 0x2D) { versionString = versionString.Slice(1); var mariaDbIndex = versionString.IndexOf(MariaDb); if (mariaDbIndex != -1) { var totalBytesRead = 0; if (Utf8Parser.TryParse(versionString, out major, out bytesConsumed) && versionString[bytesConsumed] == 0x2E) { versionString = versionString.Slice(bytesConsumed + 1); totalBytesRead += bytesConsumed + 1; if (Utf8Parser.TryParse(versionString, out minor, out bytesConsumed) && versionString[bytesConsumed] == 0x2E) { versionString = versionString.Slice(bytesConsumed + 1); totalBytesRead += bytesConsumed + 1; if (Utf8Parser.TryParse(versionString, out build, out bytesConsumed) && versionString[bytesConsumed] == 0x2D) { totalBytesRead += bytesConsumed; if (totalBytesRead == mariaDbIndex) MariaDbVersion = new Version(major, minor, build); } } } } } } public string OriginalString { get; } public Version Version { get; } public Version? MariaDbVersion { get; } static ReadOnlySpan<byte> MariaDb => new byte[] { 0x2D, 0x4D, 0x61, 0x72, 0x69, 0x61, 0x44, 0x42 }; // -MariaDB } }
38.606557
121
0.709979
[ "MIT" ]
AndreiLuis/MySqlConnector
src/MySqlConnector/Core/ServerVersion.cs
2,355
C#
using System; using System.Runtime.CompilerServices; namespace Cake.MobileCenter { /// <summary> /// Settings for mobile-center apps list. /// Get list of configured applications. /// </summary> [CompilerGenerated] public sealed class MobileCenterAppsListSettings : AutoToolSettings { /// <summary> /// --disable-telemetry /// Do not send any CLI telemetry for this command, /// </summary> public bool? DisableTelemetry { get; set; } /// <summary> /// -v|--version /// Display command&#39;s version /// </summary> public bool? Version { get; set; } /// <summary> /// --quiet /// Auto-confirm any requests, do not prompt for /// </summary> public bool? Quiet { get; set; } /// <summary> /// -h|--help /// Display help for this command /// </summary> public bool? Help { get; set; } /// <summary> /// --env &lt;arg&gt; /// Environment to connect to when using api token /// </summary> public string Env { get; set; } /// <summary> /// --token &lt;arg&gt; /// API Token to use for this command /// </summary> public string Token { get; set; } /// <summary> /// --output &lt;arg&gt; /// Format of output for this command: json /// </summary> public string Output { get; set; } /// <summary> /// --debug /// Output additional debug information for this /// </summary> public bool? Debug { get; set; } } }
25.703704
68
0.615994
[ "MIT" ]
cake-contrib/Cake.MobileCenter
src/Cake.MobileCenter/Apps/List/MobileCenterAppsListSettings.cs
1,388
C#
using System; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Fabric; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.ServiceFabric.Actors.Runtime; namespace DCT.ILR.FundingCalcService.ALBActor { [EventSource(Name = "MyCompany-DCT.ILR.Processing.POC-DCT.ILR.FundingCalcService.ALBActor")] internal sealed class ActorEventSource : EventSource { public static readonly ActorEventSource Current = new ActorEventSource(); static ActorEventSource() { // A workaround for the problem where ETW activities do not get tracked until Tasks infrastructure is initialized. // This problem will be fixed in .NET Framework 4.6.2. Task.Run(() => { }); } // Instance constructor is private to enforce singleton semantics private ActorEventSource() : base() { } #region Keywords // Event keywords can be used to categorize events. // Each keyword is a bit flag. A single event can be associated with multiple keywords (via EventAttribute.Keywords property). // Keywords must be defined as a public class named 'Keywords' inside EventSource that uses them. public static class Keywords { public const EventKeywords HostInitialization = (EventKeywords)0x1L; } #endregion #region Events // Define an instance method for each event you want to record and apply an [Event] attribute to it. // The method name is the name of the event. // Pass any parameters you want to record with the event (only primitive integer types, DateTime, Guid & string are allowed). // Each event method implementation should check whether the event source is enabled, and if it is, call WriteEvent() method to raise the event. // The number and types of arguments passed to every event method must exactly match what is passed to WriteEvent(). // Put [NonEvent] attribute on all methods that do not define an event. // For more information see https://msdn.microsoft.com/en-us/library/system.diagnostics.tracing.eventsource.aspx [NonEvent] public void Message(string message, params object[] args) { if (this.IsEnabled()) { string finalMessage = string.Format(message, args); Message(finalMessage); } } private const int MessageEventId = 1; [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}")] public void Message(string message) { if (this.IsEnabled()) { WriteEvent(MessageEventId, message); } } [NonEvent] public void ActorMessage(Actor actor, string message, params object[] args) { if (this.IsEnabled() && actor.Id != null && actor.ActorService != null && actor.ActorService.Context != null && actor.ActorService.Context.CodePackageActivationContext != null) { string finalMessage = string.Format(message, args); ActorMessage( actor.GetType().ToString(), actor.Id.ToString(), actor.ActorService.Context.CodePackageActivationContext.ApplicationTypeName, actor.ActorService.Context.CodePackageActivationContext.ApplicationName, actor.ActorService.Context.ServiceTypeName, actor.ActorService.Context.ServiceName.ToString(), actor.ActorService.Context.PartitionId, actor.ActorService.Context.ReplicaId, actor.ActorService.Context.NodeContext.NodeName, finalMessage); } } // For very high-frequency events it might be advantageous to raise events using WriteEventCore API. // This results in more efficient parameter handling, but requires explicit allocation of EventData structure and unsafe code. // To enable this code path, define UNSAFE conditional compilation symbol and turn on unsafe code support in project properties. private const int ActorMessageEventId = 2; [Event(ActorMessageEventId, Level = EventLevel.Informational, Message = "{9}")] private #if UNSAFE unsafe #endif void ActorMessage( string actorType, string actorId, string applicationTypeName, string applicationName, string serviceTypeName, string serviceName, Guid partitionId, long replicaOrInstanceId, string nodeName, string message) { #if !UNSAFE WriteEvent( ActorMessageEventId, actorType, actorId, applicationTypeName, applicationName, serviceTypeName, serviceName, partitionId, replicaOrInstanceId, nodeName, message); #else const int numArgs = 10; fixed (char* pActorType = actorType, pActorId = actorId, pApplicationTypeName = applicationTypeName, pApplicationName = applicationName, pServiceTypeName = serviceTypeName, pServiceName = serviceName, pNodeName = nodeName, pMessage = message) { EventData* eventData = stackalloc EventData[numArgs]; eventData[0] = new EventData { DataPointer = (IntPtr) pActorType, Size = SizeInBytes(actorType) }; eventData[1] = new EventData { DataPointer = (IntPtr) pActorId, Size = SizeInBytes(actorId) }; eventData[2] = new EventData { DataPointer = (IntPtr) pApplicationTypeName, Size = SizeInBytes(applicationTypeName) }; eventData[3] = new EventData { DataPointer = (IntPtr) pApplicationName, Size = SizeInBytes(applicationName) }; eventData[4] = new EventData { DataPointer = (IntPtr) pServiceTypeName, Size = SizeInBytes(serviceTypeName) }; eventData[5] = new EventData { DataPointer = (IntPtr) pServiceName, Size = SizeInBytes(serviceName) }; eventData[6] = new EventData { DataPointer = (IntPtr) (&partitionId), Size = sizeof(Guid) }; eventData[7] = new EventData { DataPointer = (IntPtr) (&replicaOrInstanceId), Size = sizeof(long) }; eventData[8] = new EventData { DataPointer = (IntPtr) pNodeName, Size = SizeInBytes(nodeName) }; eventData[9] = new EventData { DataPointer = (IntPtr) pMessage, Size = SizeInBytes(message) }; WriteEventCore(ActorMessageEventId, numArgs, eventData); } #endif } private const int ActorHostInitializationFailedEventId = 3; [Event(ActorHostInitializationFailedEventId, Level = EventLevel.Error, Message = "Actor host initialization failed", Keywords = Keywords.HostInitialization)] public void ActorHostInitializationFailed(string exception) { WriteEvent(ActorHostInitializationFailedEventId, exception); } #endregion #region Private Methods #if UNSAFE private int SizeInBytes(string s) { if (s == null) { return 0; } else { return (s.Length + 1) * sizeof(char); } } #endif #endregion } }
45.852941
258
0.60526
[ "MIT" ]
SkillsFundingAgency/DC-Alpha-ILR-Processing-SF-POC
src/DCT.ILR.FundingCalcService.ALBActor/ActorEventSource.cs
7,797
C#
// Copyright 2016-2017 Confluent Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Refer to LICENSE for more information. using System; using System.Threading.Tasks; using System.Threading; using System.Linq; using System.Collections.Generic; namespace Confluent.Kafka.Benchmark { public static class BenchmarkProducer { private static long BenchmarkProducerImpl( string bootstrapServers, string topic, int nMessages, int nTests, int nHeaders, bool useDeliveryHandler) { // mirrors the librdkafka performance test example. var config = new ProducerConfig { BootstrapServers = bootstrapServers, QueueBufferingMaxMessages = 2000000, MessageSendMaxRetries = 3, RetryBackoffMs = 500 , LingerMs = 100, DeliveryReportFields = "none" }; DeliveryReport<byte[], byte[]> firstDeliveryReport = null; Headers headers = null; if (nHeaders > 0) { headers = new Headers(); for (int i=0; i<nHeaders; ++i) { headers.Add($"header-{i+1}", new byte[] { (byte)i, (byte)(i+1), (byte)(i+2), (byte)(i+3) }); } } using (var producer = new Producer<byte[], byte[]>(config)) { for (var j=0; j<nTests; j += 1) { Console.WriteLine($"{producer.Name} producing on {topic} " + (useDeliveryHandler ? "[Action<Message>]" : "[Task]")); byte cnt = 0; var val = new byte[100].Select(a => ++cnt).ToArray(); // this avoids including connection setup, topic creation time, etc.. in result. firstDeliveryReport = producer.ProduceAsync(topic, new Message<byte[], byte[]> { Value = val, Headers = headers }).Result; var startTime = DateTime.Now.Ticks; if (useDeliveryHandler) { var autoEvent = new AutoResetEvent(false); var msgCount = nMessages; Action<DeliveryReportResult<byte[], byte[]>> deliveryHandler = (DeliveryReportResult<byte[], byte[]> deliveryReport) => { if (--msgCount == 0) { autoEvent.Set(); } }; for (int i = 0; i < nMessages; i += 1) { producer.BeginProduce(topic, new Message<byte[], byte[]> { Value = val, Headers = headers }, deliveryHandler); } autoEvent.WaitOne(); } else { var tasks = new Task[nMessages]; for (int i = 0; i < nMessages; i += 1) { tasks[i] = producer.ProduceAsync(topic, new Message<byte[], byte[]> { Value = val, Headers = headers }); } Task.WaitAll(tasks); } var duration = DateTime.Now.Ticks - startTime; Console.WriteLine($"Produced {nMessages} messages in {duration/10000.0:F0}ms"); Console.WriteLine($"{nMessages / (duration/10000.0):F0}k msg/s"); } producer.Flush(TimeSpan.FromSeconds(10)); } return firstDeliveryReport.Offset; } /// <summary> /// Producer benchmark masquarading as an integration test. /// Uses Task based produce method. /// </summary> public static long TaskProduce(string bootstrapServers, string topic, int nMessages, int nHeaders, int nTests) => BenchmarkProducerImpl(bootstrapServers, topic, nMessages, nTests, nHeaders, false); /// <summary> /// Producer benchmark (with custom delivery handler) masquarading /// as an integration test. Uses Task based produce method. /// </summary> public static long DeliveryHandlerProduce(string bootstrapServers, string topic, int nMessages, int nHeaders, int nTests) => BenchmarkProducerImpl(bootstrapServers, topic, nMessages, nTests, nHeaders, true); } }
39.534884
144
0.523725
[ "Apache-2.0" ]
DHirani/confluent-kafka-dotnet
test/Confluent.Kafka.Benchmark/BenchmarkProducer.cs
5,100
C#
namespace TradingCompany.Repository { using System; using System.Collections.Generic; using System.Linq; using TradingCompany.Models; public class BankAccountRepository : IBankAccountRepository { private static readonly IList<BankAccount> bankAccounts = new List<BankAccount>() { new BankAccount(){ BankAccountId=1, CustomerName="Rangeela", AccountNumber="4544-4456-9911", RoutingNumber="333222", AccountBalance=100 } }; public void LinkMyBankAccount(BankAccount bankAccount) { bankAccounts.Add(bankAccount); } public BankAccount GetBankAccount(int bankAccountId) { return bankAccounts.FirstOrDefault(x => x.BankAccountId == bankAccountId); } public IList<BankAccount> GetAllBankAccounts() { return bankAccounts; } public void AddMoney(BankAccountRequest request) { BankAccount account = bankAccounts.FirstOrDefault(x => x.BankAccountId == request.BankAccountId); account.AccountBalance += request.Amount; } public void WithdrawMoeny(BankAccountRequest request) { BankAccount account = bankAccounts.FirstOrDefault(x => x.BankAccountId == request.BankAccountId); account.AccountBalance -= request.Amount; } } }
27.55814
141
0.759494
[ "Apache-2.0" ]
gaganpa2020/Trading-App-Backend
AccountService/TradingCompany.AccountService/TradingCompany.Repository/BankAccountRepository.cs
1,187
C#
/* * Created by SharpDevelop. * User: Admin * Date: 2018-03-29 * Time: 10:35 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using FastColoredTextBoxNS; using System.Text.RegularExpressions; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Microsan { /// <summary> /// Description of SourceCodeEditControl. /// </summary> public partial class SourceCodeEditControl : UserControl { public delegate void SaveCodeEventHandler(string script); public delegate void NonParameterEventHandler(); public event SaveCodeEventHandler Save = null; public event NonParameterEventHandler Execute = null; private bool TextChangedSinceSave = false; TextStyle BlueStyle = new TextStyle(Brushes.Blue, null, FontStyle.Regular); TextStyle BoldStyle = new TextStyle(null, null, FontStyle.Bold | FontStyle.Underline); TextStyle GrayStyle = new TextStyle(Brushes.Gray, null, FontStyle.Regular); TextStyle MagentaStyle = new TextStyle(Brushes.Magenta, null, FontStyle.Regular); TextStyle GreenStyle = new TextStyle(Brushes.Green, null, FontStyle.Italic); TextStyle BrownStyle = new TextStyle(Brushes.Brown, null, FontStyle.Italic); TextStyle MaroonStyle = new TextStyle(Brushes.Maroon, null, FontStyle.Regular); MarkerStyle SameWordsStyle = new MarkerStyle(new SolidBrush(Color.FromArgb(40, Color.Gray))); private DataTable dtLog; MenuItem menuItemPaste; public bool docked = false; private bool init = false; private List<SourceFile> sourceFilesRef; public SourceCodeEditControl() : this(Language.CSharp) { } public SourceCodeEditControl(Language language) { InitializeComponent(); fastColoredTextBox.Language = language; dtLog = new DataTable(); dtLog.Columns.Add("Filename", typeof(string)); dtLog.Columns.Add("Row", typeof(int)); dtLog.Columns.Add("Col", typeof(int)); dtLog.Columns.Add("Description", typeof(string)); dgv.DataSource = dtLog; fastColoredTextBox_setRightClickContextMenu(); tc.DragOver += tc_DragOver; tc.MouseDown += tc_MouseDown; tc.MouseMove += tc_MouseMove; tc.MouseUp += tc_MouseUp; tc.Selected += tc_Selected; tc.SelectedIndexChanged += tc_SelectedIndexChanged; dgv.CellClick += dgv_CellClick; } private ContextMenu GetTabPageCM(string title, int index) { ContextMenu cm = new ContextMenu(); // MenuItem mi = new MenuItem("close file", tcContextMenuCloseFile_Click); // mi.Tag = index; // cm.MenuItems.Add(mi); return cm; } private void tcContextMenuCloseFile_Click(object sender, EventArgs e) { int index = (int)((MenuItem)sender).Tag; tc.TabPages.RemoveAt(index); } public void Show(List<SourceFile> sourceFiles, string fileName_main) { sourceFilesRef = sourceFiles; tsBtnSave.Enabled = (Save != null); tsBtnExec.Enabled = (Execute != null) && (Save != null); init = true; tc.TabPages.Clear(); for (int i = 0; i < sourceFiles.Count; i++) { string fileNameTemp = sourceFiles[i].FileName; tc.TabPages.Add(fileNameTemp, fileNameTemp); } init = false; this.Show(); //SelectFile(fileName_main); SelectFileTab(fileName_main); } /* /// <summary> /// /// </summary> /// <param name="script"></param> /// <param name="linePos">the first line index is 1</param> /// <param name="colPos">the first column index is 1</param> public void Show(string fileName, int linePos, int colPos, string logMessage) { fileName = fileName.ToLower(); for (int i = 0; i < sourceFilesRef.Count; i++) { if (sourceFilesRef[i].FileName.ToLower() == fileName) { fastColoredTextBox.Text = sourceFilesRef[i].Contents; } } //fastColoredTextBox.Text = script; AddToLog(linePos, colPos, logMessage); SelectLogItem(0); if (!this.docked) this.Show(); } */ public void AddToDgvLog(string fileName, int linePos, int colPos, string logMessage) { dtLog.Rows.Add(fileName, linePos, colPos, logMessage); } public void ClearLog() { dtLog.Rows.Clear(); rtxtLog.Clear(); ResetSelections(); } public void SelectCharAtPos(int linePos, int colPos) { try { FastColoredTextBoxNS.Range range = fastColoredTextBox.GetLine(linePos); range.Start = new FastColoredTextBoxNS.Place(colPos - 1, linePos - 1); range.End = new FastColoredTextBoxNS.Place(colPos, linePos - 1); fastColoredTextBox.Selection = range; fastColoredTextBox.DoSelectionVisible(); // scroll to selection } catch (Exception ex) { rtxtLog.AppendText("exception @ SelectCharAtPos: line=" + linePos + ", col=" + colPos + "\r\n"); //rtxtLog.AppendText(ex.ToString() + "\r\n"); } } public void ResetSelections() { fastColoredTextBox.Selection = new Range(fastColoredTextBox, Place.Empty, Place.Empty); } public void AppendLineToLog(string logMessage) { rtxtLog.AppendText(logMessage + "\n"); } private void JavascriptEditForm_Shown(object sender, EventArgs e) { //btnSaveApply.Enabled = (SaveApply != null); } private void Set_TextChangedSinceSave(bool textEdited) { TextChangedSinceSave = textEdited; this.Text = "Source Code Edit Form"; if (textEdited) this.Text += " (text changed, you need to save before switch tabs)"; } private void _Save() { Set_TextChangedSinceSave(false); //if (Save == null) return; if (tc.SelectedTab == null) return; string fileName = tc.SelectedTab.Text.ToLower(); for (int i = 0; i < sourceFilesRef.Count; i++) { if (sourceFilesRef[i].FileName.ToLower() == fileName) { sourceFilesRef[i].Contents = fastColoredTextBox.Text; sourceFilesRef[i].SaveFile(); //tc.Enabled = true; break; } } //Save(); } private void tsBtnSave_Click(object sender, EventArgs e) { _Save(); } private void tsBtnExec_Click(object sender, EventArgs e) { _Save(); Execute(); } private void btnClose_Click(object sender, EventArgs e) { if (TextChangedSinceSave) { DialogResult dr = MessageBox.Show("Do you want to save the latest changes before close?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr == DialogResult.Yes) _Save(); } this.Visible = false; } private void this_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing) { e.Cancel = true; //if (!docked) // this.Visible = false; } } public void AppendText(string text) { fastColoredTextBox.SelectedText = text; } private void btnClearLog_Click(object sender, EventArgs e) { rtxtLog.Clear(); rtxtLog.ClearUndo(); } private void fastColoredTextBox_TextChanged(object sender, FastColoredTextBoxNS.TextChangedEventArgs e) { switch (fastColoredTextBox.Language) { case Language.CSharp: //For sample, we will highlight the syntax of C# manually, although could use built-in highlighter CSharpSyntaxHighlight(e);//custom highlighting break; case Language.JS: JavascriptSyntaxHighlight(e); break; default: break;//for highlighting of other languages, we using built-in FastColoredTextBox highlighter } } private void fastColoredTextBox_setRightClickContextMenu() { ContextMenu contextMenu = new System.Windows.Forms.ContextMenu(); MenuItem menuItem; menuItem = new MenuItem("Redo"); menuItem.Click += new EventHandler(RedoAction); contextMenu.MenuItems.Add(menuItem); menuItem = new MenuItem("Undo"); menuItem.Click += new EventHandler(UndoAction); contextMenu.MenuItems.Add(menuItem); contextMenu.MenuItems.Add(new MenuItem("-")); menuItem = new MenuItem("Increase Line Indent"); menuItem.Click += new EventHandler(IncreaseLineIndent_Action); contextMenu.MenuItems.Add(menuItem); menuItem = new MenuItem("Decrease Line Indent"); menuItem.Click += new EventHandler(DecreaseLineIndent_Action); contextMenu.MenuItems.Add(menuItem); contextMenu.MenuItems.Add(new MenuItem("-")); menuItem = new MenuItem("Cut"); menuItem.Click += new EventHandler(CutAction); contextMenu.MenuItems.Add(menuItem); menuItem = new MenuItem("Copy"); menuItem.Click += new EventHandler(CopyAction); contextMenu.MenuItems.Add(menuItem); menuItemPaste = new MenuItem("Paste"); menuItemPaste.Click += new EventHandler(PasteAction); contextMenu.MenuItems.Add(menuItemPaste); contextMenu.MenuItems.Add(new MenuItem("-")); menuItem = new MenuItem("Delete"); menuItem.Click += new EventHandler(DeleteAction); contextMenu.MenuItems.Add(menuItem); contextMenu.Popup += new EventHandler(ContextMenu_Popup_Action); fastColoredTextBox.ContextMenu = contextMenu; } void ContextMenu_Popup_Action(object s, EventArgs ea) { menuItemPaste.Enabled = Clipboard.ContainsText(); } void CutAction(object sender, EventArgs e) { fastColoredTextBox.Cut(); } void CopyAction(object sender, EventArgs e) { //Clipboard.SetData(DataFormats.Text, fastColoredTextBox.SelectedText); //Clipboard.Clear(); fastColoredTextBox.Copy(); } void IncreaseLineIndent_Action(object s, EventArgs ea) { fastColoredTextBox.IncreaseIndent(); } void DecreaseLineIndent_Action(object s, EventArgs ea) { fastColoredTextBox.DecreaseIndent(); } void PasteAction(object sender, EventArgs e) { fastColoredTextBox.Paste(); //fastColoredTextBox.SelectedText = Clipboard.GetText(); } void DeleteAction(object sender, EventArgs e) { fastColoredTextBox.SelectedText = ""; } void RedoAction(object sender, EventArgs e) { fastColoredTextBox.Redo(); } void UndoAction(object sender, EventArgs e) { fastColoredTextBox.Undo(); } private void JavascriptSyntaxHighlight(TextChangedEventArgs e) { // old edition //Range range = e.ChangedRange; //new edition Range range = fastColoredTextBox.VisibleRange;//or (sender as //FastColoredTextBox).Range //clear style of changed range range.ClearStyle(GreenStyle); //comment highlighting range.SetStyle(GreenStyle, @"//.*$", RegexOptions.Multiline); range.SetStyle(GreenStyle, @"(/\*.*?\*/)|(/\*.*)", RegexOptions.Singleline); range.SetStyle(GreenStyle, @"(/\*.*?\*/)|(.*\*/)", RegexOptions.Singleline | RegexOptions.RightToLeft); } private void CSharpSyntaxHighlight(TextChangedEventArgs e) { fastColoredTextBox.LeftBracket = '('; fastColoredTextBox.RightBracket = ')'; fastColoredTextBox.LeftBracket2 = '\x0'; fastColoredTextBox.RightBracket2 = '\x0'; //clear style of changed range e.ChangedRange.ClearStyle(BlueStyle, BoldStyle, GrayStyle, MagentaStyle, GreenStyle, BrownStyle); //string highlighting e.ChangedRange.SetStyle(BrownStyle, @"""""|@""""|''|@"".*?""|(?<!@)(?<range>"".*?[^\\]"")|'.*?[^\\]'"); //comment highlighting e.ChangedRange.SetStyle(GreenStyle, @"//.*$", RegexOptions.Multiline); e.ChangedRange.SetStyle(GreenStyle, @"(/\*.*?\*/)|(/\*.*)", RegexOptions.Singleline); e.ChangedRange.SetStyle(GreenStyle, @"(/\*.*?\*/)|(.*\*/)", RegexOptions.Singleline | RegexOptions.RightToLeft); //number highlighting e.ChangedRange.SetStyle(MagentaStyle, @"\b\d+[\.]?\d*([eE]\-?\d+)?[lLdDfF]?\b|\b0x[a-fA-F\d]+\b"); //attribute highlighting e.ChangedRange.SetStyle(GrayStyle, @"^\s*(?<range>\[.+?\])\s*$", RegexOptions.Multiline); //class name highlighting e.ChangedRange.SetStyle(BoldStyle, @"\b(class|struct|enum|interface)\s+(?<range>\w+?)\b"); //keyword highlighting e.ChangedRange.SetStyle(BlueStyle, @"\b(abstract|as|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|goto|if|implicit|in|int|interface|internal|is|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|virtual|void|volatile|while|add|alias|ascending|descending|dynamic|from|get|global|group|into|join|let|orderby|partial|remove|select|set|value|var|where|yield)\b|#region\b|#endregion\b"); //clear folding markers e.ChangedRange.ClearFoldingMarkers(); //set folding markers e.ChangedRange.SetFoldingMarkers("{", "}");//allow to collapse brackets block e.ChangedRange.SetFoldingMarkers(@"#region\b", @"#endregion\b");//allow to collapse #region blocks e.ChangedRange.SetFoldingMarkers(@"/\*", @"\*/");//allow to collapse comment block } private void fastColoredTextBox_SelectionChangedDelayed(object sender, EventArgs e) { fastColoredTextBox.VisibleRange.ClearStyle(SameWordsStyle); if (!fastColoredTextBox.Selection.IsEmpty) return;//user selected diapason //get fragment around caret var fragment = fastColoredTextBox.Selection.GetFragment(@"\w"); string text = fragment.Text; if (text.Length == 0) return; //highlight same words var ranges = fastColoredTextBox.VisibleRange.GetRanges("\\b" + text + "\\b").ToArray(); if (ranges.Length > 1) foreach (var r in ranges) r.SetStyle(SameWordsStyle); } private void dgv_CellClick(object sender, DataGridViewCellEventArgs e) { SelectLogItem(e.RowIndex); } public void SelectLogItem(int rowIndex) { string fileName = (string)dtLog.Rows[rowIndex]["Filename"]; int textRow = (int)dtLog.Rows[rowIndex]["Row"]; int textCol = (int)dtLog.Rows[rowIndex]["Col"]; rtxtLog.Text = (string)dtLog.Rows[rowIndex]["Description"]; if ((textRow < 1) || (textCol < 1)) return; //SelectFile(fileName); SelectFileTab(fileName); SelectCharAtPos(textRow, textCol); } private void SelectFileTab(string fileName) { fileName = fileName.ToLower(); for (int i = 0; i < tc.TabCount; i++) { if (tc.TabPages[i].Name.ToLower() == fileName) { tc.SelectedTab = tc.TabPages[i]; return; } } } private void tc_MouseDown(object sender, MouseEventArgs e) { // store clicked tab TabControl tc = (TabControl)sender; int hover_index = this.getHoverTabIndex(tc); if (hover_index >= 0) { tc.Tag = tc.TabPages[hover_index]; } tc.ContextMenu = GetTabPageCM(tc.TabPages[hover_index].Text, hover_index); } private void tc_MouseUp(object sender, MouseEventArgs e) { // clear stored tab TabControl tc = (TabControl)sender; tc.Tag = null; } private void tc_MouseMove(object sender, MouseEventArgs e) { // mouse button down? tab was clicked? TabControl tc = (TabControl)sender; if ((e.Button != MouseButtons.Left) || (tc.Tag == null)) return; TabPage clickedTab = (TabPage)tc.Tag; int clicked_index = tc.TabPages.IndexOf(clickedTab); // start drag n drop tc.DoDragDrop(clickedTab, DragDropEffects.All); } private void tc_DragOver(object sender, DragEventArgs e) { TabControl tc = (TabControl)sender; // a tab is draged? if (e.Data.GetData(typeof(TabPage)) == null) return; TabPage dragTab = (TabPage)e.Data.GetData(typeof(TabPage)); int dragTab_index = tc.TabPages.IndexOf(dragTab); // hover over a tab? int hoverTab_index = this.getHoverTabIndex(tc); if (hoverTab_index < 0) { e.Effect = DragDropEffects.None; return; } TabPage hoverTab = tc.TabPages[hoverTab_index]; e.Effect = DragDropEffects.Move; // start of drag? if (dragTab == hoverTab) return; // swap dragTab & hoverTab - avoids toggeling Rectangle dragTabRect = tc.GetTabRect(dragTab_index); Rectangle hoverTabRect = tc.GetTabRect(hoverTab_index); if (dragTabRect.Width < hoverTabRect.Width) { Point tcLocation = tc.PointToScreen(tc.Location); if (dragTab_index < hoverTab_index) { if ((e.X - tcLocation.X) > ((hoverTabRect.X + hoverTabRect.Width) - dragTabRect.Width)) this.swapTabPages(tc, dragTab, hoverTab); } else if (dragTab_index > hoverTab_index) { if ((e.X - tcLocation.X) < (hoverTabRect.X + dragTabRect.Width)) this.swapTabPages(tc, dragTab, hoverTab); } } else this.swapTabPages(tc, dragTab, hoverTab); // select new pos of dragTab tc.SelectedIndex = tc.TabPages.IndexOf(dragTab); } private int getHoverTabIndex(TabControl tc) { for (int i = 0; i < tc.TabPages.Count; i++) { if (tc.GetTabRect(i).Contains(tc.PointToClient(Cursor.Position))) return i; } return -1; } private void swapTabPages(TabControl tc, TabPage src, TabPage dst) { int index_src = tc.TabPages.IndexOf(src); int index_dst = tc.TabPages.IndexOf(dst); tc.TabPages[index_dst] = src; tc.TabPages[index_src] = dst; tc.Refresh(); } void tc_Selected(object sender, TabControlEventArgs e) { } private void tc_SelectedIndexChanged(object sender, EventArgs e) { if (tc.SelectedTab == null) return; if (init) return; SelectFile(tc.SelectedTab.Text); //tc.SelectedTab.Font = new Font(tc.SelectedTab.Font, FontStyle.Bold); } private void SelectFile(string fileName) { fileName = fileName.ToLower(); for (int i = 0; i < sourceFilesRef.Count; i++) { if (sourceFilesRef[i].FileName.ToLower() == fileName) { if (fastColoredTextBox.Tag != null) { SourceFile sf = (SourceFile)fastColoredTextBox.Tag; sf.Contents = fastColoredTextBox.Text; //sf.editorSelectionRange = fastColoredTextBox.Selection; sf.editorSelectionStart = fastColoredTextBox.SelectionStart; sf.editorSelectionLength = fastColoredTextBox.SelectionLength; sf.editorVerticalScrollValue = fastColoredTextBox.VerticalScroll.Value; sf.editorHorizontalScrollValue = fastColoredTextBox.HorizontalScroll.Value; } fastColoredTextBox.Text = sourceFilesRef[i].Contents; fastColoredTextBox.Tag = sourceFilesRef[i]; fastColoredTextBox.SelectionStart = sourceFilesRef[i].editorSelectionStart; fastColoredTextBox.SelectionLength = sourceFilesRef[i].editorSelectionLength; /* if (sourceFilesRef[i].editorSelectionRange != null) { fastColoredTextBox. fastColoredTextBox.Selection = sourceFilesRef[i].editorSelectionRange; fastColoredTextBox.Update(); //fastColoredTextBox.DoSelectionVisible(); } else rtxtLog.AppendText("ok @ sourceFilesRef[i].editorSelectionRange == null\r\n"); */ fastColoredTextBox.HorizontalScroll.Value = sourceFilesRef[i].editorHorizontalScrollValue; fastColoredTextBox.VerticalScroll.Value = sourceFilesRef[i].editorVerticalScrollValue; fastColoredTextBox.UpdateScrollbars(); //rtxtLog.AppendText("ok @ SelectFile: fileName=" + fileName + "\r\n"); return; } } rtxtLog.AppendText("error @ SelectFile: fileName=" + fileName + "\r\n"); } private void fastColoredTextBox_KeyPress(object sender, KeyPressEventArgs e) { //tc.Enabled = false; //tsslblMain.Text = "(text changed, you need to save before switch tabs)"; } private void tsbtnNewFile_Click(object sender, EventArgs e) { string filePath = ""; if (!QuickDialogs.FileSave(Application.StartupPath + "\\" + RuntimeProgramming.SOURCE_FILES_DIR_NAME, "Select the filename..", "C# files|*.cs", out filePath)) return; SourceFile sf = new SourceFile(filePath); sf.Contents = RuntimeProgramming.GetEmbeddedTemplateResource(RuntimeProgramming.RES_NAME_NEW_CLASS_TEMPLATE).Replace("NewClass", sf.FileNameWithoutExt); sf.SaveFile(); sourceFilesRef.Add(sf); tc.TabPages.Add(sf.FileName, sf.FileName); sf = null; } } }
38.038285
711
0.558316
[ "MIT" ]
manicken/MicrosanCalc
.localhistory/D/_Projects/_Software/_CommonSourceFiles/RuntimeProgramming/1538328447$SourceCodeEditControl.cs
24,841
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Menu : MonoBehaviour { public void OpenLevel(string name) { SceneManager.LoadScene(name); } }
17.538462
35
0.789474
[ "MIT" ]
JullyKE/ShootEmUp
Parcial1_MGII_3907/Assets/ShootEmUp/Scripts/Menu.cs
230
C#
namespace UCloudSDK.Models { /// <summary> /// 获取弹性IP详细信息 /// <para> /// http://docs.ucloud.cn/api/unet/describe_eip.html /// </para> /// </summary> public partial class DescribeEIPRequest { /// <summary> /// 默认Action名称 /// </summary> private string _action = "DescribeEIP"; /// <summary> /// API名称 /// <para> /// DescribeEIP /// </para> /// </summary> public string Action { get { return _action; } set { _action = value; } } /// <summary> /// 数据中心 /// <para> /// 参见 数据中心列表 /// </para> /// </summary> public string Region { get; set; } /// <summary> /// 弹性IP的资源ID如果为空 /// <para> /// 则返回当前Region中符合条件的的所有EIP /// </para> /// </summary> public NList EIPIds { get; set; } /// <summary> /// 数据偏移量 /// <para> /// 默认为0 /// </para> /// </summary> public int? Offset { get; set; } /// <summary> /// 数据分页值 /// <para> /// 默认为20 /// </para> /// </summary> public int? Limit { get; set; } /// <summary> /// 实例化 <see cref="DescribeEIPRequest"/> 类. /// </summary> /// <param name="region">数据中心</param> public DescribeEIPRequest(string region) { Region = region; } } }
24.671429
65
0.365373
[ "MIT" ]
icyflash/ucloud-csharp-sdk
UCloudSDK/Models/UNet/DescribeEIPRequest.cs
1,873
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FFBattleGenerator.BLL { public class FrameDef { /// <summary> /// Source position of frame /// </summary> public int X { get; set; } public int Y { get; set; } /// <summary> /// Source image /// </summary> public string Image { get; set; } /// <summary> /// Source width and height of frame /// </summary> public int Width { get; set; } public int Height { get; set; } /// <summary> /// How long the frame should be shown before the next frame is shown /// </summary> public int Delay { get; set; } /// <summary> /// The base coordinates where the sprite touches the ground. This is used to seamlessly switch from /// one animation to another using the same x & y coordinates without taking in account the difference in size /// of the sprite (as these properties will correct that). /// </summary> public int BaseX { get; set; } public int BaseY { get; set; } } }
29.731707
119
0.546349
[ "MIT" ]
drake7707/animation-builder
FFBattleGenerator/BLL/FrameDef.cs
1,221
C#
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0 { using System; using System.Runtime.CompilerServices; using static Root; partial struct minicore { /// <summary> /// Presents the bytespan head as a reference to an unsigned 32-bit integer /// </summary> /// <param name="src">The source span</param> /// <typeparam name="T">The cell type</typeparam> [MethodImpl(Inline), Op, Closures(Closure)] public static ref uint first32u<T>(Span<T> src) where T : unmanaged => ref first(recover<T,uint>(src)); /// <summary> /// Presents the span head as a readonly reference to an unsigned 32-bit integer /// </summary> /// <param name="src">The source span</param> /// <typeparam name="T">The cell type</typeparam> [MethodImpl(Inline), Op, Closures(Closure)] public static ref readonly uint first32u<T>(ReadOnlySpan<T> src) where T : unmanaged => ref first(recover<T,uint>(src)); } }
36.852941
88
0.505986
[ "BSD-3-Clause" ]
0xCM/z0
src/root/src/minicore/ops/first32u.cs
1,253
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = TrustPayments.Client.SwaggerDateConverter; namespace TrustPayments.Model { /// <summary> /// RefundComment /// </summary> [DataContract] public partial class RefundComment : IEquatable<RefundComment> { /// <summary> /// Initializes a new instance of the <see cref="RefundComment" /> class. /// </summary> [JsonConstructorAttribute] public RefundComment() { } /// <summary> /// Gets or Sets Content /// </summary> [DataMember(Name="content", EmitDefaultValue=false)] public string Content { get; private set; } /// <summary> /// Gets or Sets CreatedBy /// </summary> [DataMember(Name="createdBy", EmitDefaultValue=false)] public long? CreatedBy { get; private set; } /// <summary> /// The created on date indicates the date on which the entity was stored into the database. /// </summary> /// <value>The created on date indicates the date on which the entity was stored into the database.</value> [DataMember(Name="createdOn", EmitDefaultValue=false)] public DateTime? CreatedOn { get; private set; } /// <summary> /// Gets or Sets EditedBy /// </summary> [DataMember(Name="editedBy", EmitDefaultValue=false)] public long? EditedBy { get; private set; } /// <summary> /// The date on which the comment was last edited. /// </summary> /// <value>The date on which the comment was last edited.</value> [DataMember(Name="editedOn", EmitDefaultValue=false)] public DateTime? EditedOn { get; private set; } /// <summary> /// The ID is the primary key of the entity. The ID identifies the entity uniquely. /// </summary> /// <value>The ID is the primary key of the entity. The ID identifies the entity uniquely.</value> [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; private set; } /// <summary> /// The linked space id holds the ID of the space to which the entity belongs to. /// </summary> /// <value>The linked space id holds the ID of the space to which the entity belongs to.</value> [DataMember(Name="linkedSpaceId", EmitDefaultValue=false)] public long? LinkedSpaceId { get; private set; } /// <summary> /// Gets or Sets Pinned /// </summary> [DataMember(Name="pinned", EmitDefaultValue=false)] public bool? Pinned { get; private set; } /// <summary> /// Gets or Sets Refund /// </summary> [DataMember(Name="refund", EmitDefaultValue=false)] public long? Refund { get; private set; } /// <summary> /// The version number indicates the version of the entity. The version is incremented whenever the entity is changed. /// </summary> /// <value>The version number indicates the version of the entity. The version is incremented whenever the entity is changed.</value> [DataMember(Name="version", EmitDefaultValue=false)] public int? Version { get; private set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class RefundComment {\n"); sb.Append(" Content: ").Append(Content).Append("\n"); sb.Append(" CreatedBy: ").Append(CreatedBy).Append("\n"); sb.Append(" CreatedOn: ").Append(CreatedOn).Append("\n"); sb.Append(" EditedBy: ").Append(EditedBy).Append("\n"); sb.Append(" EditedOn: ").Append(EditedOn).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" LinkedSpaceId: ").Append(LinkedSpaceId).Append("\n"); sb.Append(" Pinned: ").Append(Pinned).Append("\n"); sb.Append(" Refund: ").Append(Refund).Append("\n"); sb.Append(" Version: ").Append(Version).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as RefundComment); } /// <summary> /// Returns true if RefundComment instances are equal /// </summary> /// <param name="input">Instance of RefundComment to be compared</param> /// <returns>Boolean</returns> public bool Equals(RefundComment input) { if (input == null) return false; return ( this.Content == input.Content || (this.Content != null && this.Content.Equals(input.Content)) ) && ( this.CreatedBy == input.CreatedBy || (this.CreatedBy != null && this.CreatedBy.Equals(input.CreatedBy)) ) && ( this.CreatedOn == input.CreatedOn || (this.CreatedOn != null && this.CreatedOn.Equals(input.CreatedOn)) ) && ( this.EditedBy == input.EditedBy || (this.EditedBy != null && this.EditedBy.Equals(input.EditedBy)) ) && ( this.EditedOn == input.EditedOn || (this.EditedOn != null && this.EditedOn.Equals(input.EditedOn)) ) && ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.LinkedSpaceId == input.LinkedSpaceId || (this.LinkedSpaceId != null && this.LinkedSpaceId.Equals(input.LinkedSpaceId)) ) && ( this.Pinned == input.Pinned || (this.Pinned != null && this.Pinned.Equals(input.Pinned)) ) && ( this.Refund == input.Refund || (this.Refund != null && this.Refund.Equals(input.Refund)) ) && ( this.Version == input.Version || (this.Version != null && this.Version.Equals(input.Version)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Content != null) hashCode = hashCode * 59 + this.Content.GetHashCode(); if (this.CreatedBy != null) hashCode = hashCode * 59 + this.CreatedBy.GetHashCode(); if (this.CreatedOn != null) hashCode = hashCode * 59 + this.CreatedOn.GetHashCode(); if (this.EditedBy != null) hashCode = hashCode * 59 + this.EditedBy.GetHashCode(); if (this.EditedOn != null) hashCode = hashCode * 59 + this.EditedOn.GetHashCode(); if (this.Id != null) hashCode = hashCode * 59 + this.Id.GetHashCode(); if (this.LinkedSpaceId != null) hashCode = hashCode * 59 + this.LinkedSpaceId.GetHashCode(); if (this.Pinned != null) hashCode = hashCode * 59 + this.Pinned.GetHashCode(); if (this.Refund != null) hashCode = hashCode * 59 + this.Refund.GetHashCode(); if (this.Version != null) hashCode = hashCode * 59 + this.Version.GetHashCode(); return hashCode; } } } }
39.088983
151
0.524336
[ "Apache-2.0" ]
TrustPayments/csharp-sdk
src/TrustPayments/Model/RefundComment.cs
9,225
C#
namespace MiniORM { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; internal class ChangeTracker<T> where T : class, new() { private readonly List<T> allEntities; private readonly List<T> addedEntities; private readonly List<T> removedEntities; public ChangeTracker(IEnumerable<T> entities) { this.addedEntities = new List<T>(); this.removedEntities = new List<T>(); this.allEntities = CloneEntities(entities); } public IReadOnlyCollection<T> AllEntities => this.allEntities.AsReadOnly(); public IReadOnlyCollection<T> AddedEntities => this.addedEntities.AsReadOnly(); public IReadOnlyCollection<T> RemovedEntities => this.removedEntities.AsReadOnly(); private static List<T> CloneEntities(IEnumerable<T> entities) { var clonedEntities = new List<T>(); var propertiesToClone = typeof(T).GetProperties() .Where(p => DbContext.AllowedSqlTypes.Contains(p.PropertyType)).ToArray(); foreach (var entity in entities) { var clonedEntity = Activator.CreateInstance<T>(); foreach (var propertyInfo in propertiesToClone) { var value = propertyInfo.GetValue(entity); propertyInfo.SetValue(clonedEntity, value); } clonedEntities.Add(clonedEntity); } return clonedEntities; } public void Add(T item) => this.addedEntities.Add(item); public void Remove(T item) => this.removedEntities.Add(item); public IEnumerable<T> GetModifiedEntities(DbSet<T> dbSet) { var modifiedEntities = new List<T>(); var primaryKeys = typeof(T).GetProperties().Where(p => p.HasAttribute<KeyAttribute>()).ToArray(); foreach (var proxyEntity in this.allEntities) { var primaryKeyValues = GetPrimaryKeyValues(primaryKeys, proxyEntity).ToArray(); var entity = dbSet.Entities.Single(e => GetPrimaryKeyValues(primaryKeys, e).SequenceEqual(primaryKeyValues)); var isModified = IsModified(proxyEntity, entity); if (isModified) { modifiedEntities.Add(entity); } } return modifiedEntities; } private static bool IsModified(T entity, T proxyEntity) { var monitoredProperties = typeof(T).GetProperties().Where(p => DbContext.AllowedSqlTypes.Contains(p.PropertyType)); var modifiedProperties = monitoredProperties .Where(p => !Equals(p.GetValue(entity), p.GetValue(proxyEntity))).ToArray(); return modifiedProperties.Any(); } private static IEnumerable<object> GetPrimaryKeyValues(IEnumerable<PropertyInfo> primaryKeys, T entity) { return primaryKeys.Select(pk => pk.GetValue(entity)); } } }
34.858696
111
0.597755
[ "MIT" ]
mayapeneva/DATABASE-Advanced-Entity-Framework
02.ORMFundamentals/MiniORM/ChangeTracker.cs
3,209
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Ckafka.V20190819.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class CreateAclRequest : AbstractModel { /// <summary> /// 实例id信息 /// </summary> [JsonProperty("InstanceId")] public string InstanceId{ get; set; } /// <summary> /// Acl资源类型,(0:UNKNOWN,1:ANY,2:TOPIC,3:GROUP,4:CLUSTER,5:TRANSACTIONAL_ID),当前只有TOPIC,其它字段用于后续兼容开源kafka的acl时使用 /// </summary> [JsonProperty("ResourceType")] public long? ResourceType{ get; set; } /// <summary> /// 资源名称,和resourceType相关,如当resourceType为TOPIC时,则该字段表示topic名称,当resourceType为GROUP时,该字段表示group名称 /// </summary> [JsonProperty("ResourceName")] public string ResourceName{ get; set; } /// <summary> /// Acl操作方式,(0:UNKNOWN,1:ANY,2:ALL,3:READ,4:WRITE,5:CREATE,6:DELETE,7:ALTER,8:DESCRIBE,9:CLUSTER_ACTION,10:DESCRIBE_CONFIGS,11:ALTER_CONFIGS) /// </summary> [JsonProperty("Operation")] public long? Operation{ get; set; } /// <summary> /// 权限类型,(0:UNKNOWN,1:ANY,2:DENY,3:ALLOW),当前ckakfa支持ALLOW(相当于白名单),其它用于后续兼容开源kafka的acl时使用 /// </summary> [JsonProperty("PermissionType")] public long? PermissionType{ get; set; } /// <summary> /// 默认为\*,表示任何host都可以访问,当前ckafka不支持host为\*,但是后面开源kafka的产品化会直接支持 /// </summary> [JsonProperty("Host")] public string Host{ get; set; } /// <summary> /// 用户列表,默认为*,表示任何user都可以访问,当前用户只能是用户列表中包含的用户 /// </summary> [JsonProperty("Principal")] public string Principal{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "InstanceId", this.InstanceId); this.SetParamSimple(map, prefix + "ResourceType", this.ResourceType); this.SetParamSimple(map, prefix + "ResourceName", this.ResourceName); this.SetParamSimple(map, prefix + "Operation", this.Operation); this.SetParamSimple(map, prefix + "PermissionType", this.PermissionType); this.SetParamSimple(map, prefix + "Host", this.Host); this.SetParamSimple(map, prefix + "Principal", this.Principal); } } }
36.395349
149
0.633546
[ "Apache-2.0" ]
ImEdisonJiang/tencentcloud-sdk-dotnet
TencentCloud/Ckafka/V20190819/Models/CreateAclRequest.cs
3,514
C#
using Orleans; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Swashbuckle.Orleans.SwaggerGen { public interface ISwaggerGenGrain:IGrainWithGuidKey { Task<string> Generator(); } }
18.642857
55
0.750958
[ "Apache-2.0" ]
aqa510415008/Swashbuckle.Orleans.SwaggerGen
src/Swashbuckle.Orleans.SwaggerGen/ISwaggerGenGrain.cs
263
C#
using System; using System.IO; using Core.Enums; using Core.Extensions.LocalizationRelated; using Core.Localization; using Core.Localization.Impl; namespace Core.Text.Formatter { public class TimeSpanFormatter : ITextFormatter<TimeSpan> { public TimeSpanFormatter( ITimeLocalization? localization = default, TimePart precision = TimePart.Second, bool compact = false, string separator = ", ") { Localization = localization ?? TimeLocalization.Create("en"); Precision = precision; Compact = compact; Separator = separator; } public void Write(TimeSpan value, TextWriter writer) { _outputStarted = false; if (value.Days != 0) { var days = value.Days; if (days > 7) { WriteValue(writer, TimePart.Week, value.Days / 7); if (Precision == TimePart.Week) return; days = value.Days % 7; } WriteValue(writer, TimePart.Day, days); if (Precision == TimePart.Day) return; } WriteValue(writer, TimePart.Hour, value.Hours); if (Precision == TimePart.Hour) return; WriteValue(writer, TimePart.Minute, value.Minutes); if (Precision == TimePart.Minute) return; WriteValue(writer, TimePart.Second, value.Seconds); if (Precision == TimePart.Second) return; WriteValue(writer, TimePart.Millisecond, value.Milliseconds); } private void WriteValue( TextWriter writer, TimePart part, int value) { var force = part == Precision; if (!_outputStarted && value == 0 && !force) return ; if (_outputStarted) writer.Write(Separator); _outputStarted = true; Localization .GetPartLocalization(part) .WriteValue(writer, value, Compact); } private bool _outputStarted; private TimePart Precision { get; set; } private ITimeLocalization Localization { get; set; } private bool Compact { get; set; } private string Separator { get; set; } } }
33.71831
73
0.541771
[ "MIT" ]
capjan/CoreLib
Core/Text/Formatter/TimeSpanFormatter.cs
2,396
C#
using NBitcoin.DataEncoders; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBitcoin.Protocol { public enum RejectCode : byte { MALFORMED = 0x01, INVALID = 0x10, OBSOLETE = 0x11, DUPLICATE = 0x12, NONSTANDARD = 0x40, DUST = 0x41, INSUFFICIENTFEE = 0x42, CHECKPOINT = 0x43 } public enum RejectCodeType { Common, Version, Transaction, Block } /// <summary> /// A transaction or block are rejected being transmitted through tx or block messages /// </summary> [Payload("reject")] public class RejectPayload : Payload { VarString _Message = new VarString(); /// <summary> /// "tx" or "block" /// </summary> public string Message { get { return Encoders.ASCII.EncodeData(_Message.GetString(true)); } set { _Message = new VarString(Encoders.ASCII.DecodeData(value)); } } byte _Code; public RejectCode Code { get { return (RejectCode)_Code; } set { _Code = (byte)value; } } public RejectCodeType CodeType { get { switch (Code) { case RejectCode.MALFORMED: return RejectCodeType.Common; case RejectCode.OBSOLETE: if (Message == "block") return RejectCodeType.Block; else return RejectCodeType.Version; case RejectCode.DUPLICATE: if (Message == "tx") return RejectCodeType.Transaction; else return RejectCodeType.Version; case RejectCode.NONSTANDARD: case RejectCode.DUST: case RejectCode.INSUFFICIENTFEE: return RejectCodeType.Transaction; case RejectCode.CHECKPOINT: return RejectCodeType.Block; case RejectCode.INVALID: if (Message == "tx") return RejectCodeType.Transaction; else return RejectCodeType.Block; default: return RejectCodeType.Common; } } } VarString _Reason = new VarString(); /// <summary> /// Details of the error /// </summary> public string Reason { get { return Encoders.ASCII.EncodeData(_Reason.GetString(true)); } set { _Reason = new VarString(Encoders.ASCII.DecodeData(value)); } } uint256 _Hash; /// <summary> /// The hash being rejected /// </summary> public uint256 Hash { get { return _Hash; } set { _Hash = value; } } public override void ReadWriteCore(BitcoinStream stream) { stream.ReadWrite(ref _Message); stream.ReadWrite(ref _Code); stream.ReadWrite(ref _Reason); if (Message == "tx" || Message == "block") stream.ReadWrite(ref _Hash); } } }
19.737589
88
0.608696
[ "MIT" ]
3DA4C300/NBitcoin
NBitcoin/Protocol/Payloads/RejectPayload.cs
2,785
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Internal; using System.Reflection.Metadata; using System.Reflection.Metadata.Tests; using Xunit; namespace System.Reflection.PortableExecutable.Tests { public class DebugDirectoryTests { [Fact] public void NoDebugDirectory() { var peStream = new MemoryStream(Misc.Members); using (var reader = new PEReader(peStream)) { var entries = reader.ReadDebugDirectory(); Assert.Empty(entries); } } [Fact] public void CodeView() { var peStream = new MemoryStream(Misc.Debug); using (var reader = new PEReader(peStream)) { ValidateCodeView(reader); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void CodeView_Loaded() { LoaderUtilities.LoadPEAndValidate(Misc.Debug, ValidateCodeView); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void CodeView_Loaded_FromStream() { LoaderUtilities.LoadPEAndValidate(Misc.Debug, ValidateCodeView, useStream: true); } private void ValidateCodeView(PEReader reader) { // dumpbin: // // Debug Directories // // Time Type Size RVA Pointer // -------------- - ------------------------ // 5670C4E6 cv 11C 0000230C 50C Format: RSDS, { 0C426227-31E6-4EC2-BD5F-712C4D96C0AB}, 1, C:\Temp\Debug.pdb var cvEntry = reader.ReadDebugDirectory().Single(); Assert.Equal(DebugDirectoryEntryType.CodeView, cvEntry.Type); Assert.False(cvEntry.IsPortableCodeView); Assert.Equal(0x050c, cvEntry.DataPointer); Assert.Equal(0x230c, cvEntry.DataRelativeVirtualAddress); Assert.Equal(0x011c, cvEntry.DataSize); // includes NUL padding Assert.Equal(0, cvEntry.MajorVersion); Assert.Equal(0, cvEntry.MinorVersion); Assert.Equal(0x5670c4e6u, cvEntry.Stamp); var cv = reader.ReadCodeViewDebugDirectoryData(cvEntry); Assert.Equal(1, cv.Age); Assert.Equal(new Guid("0C426227-31E6-4EC2-BD5F-712C4D96C0AB"), cv.Guid); Assert.Equal(@"C:\Temp\Debug.pdb", cv.Path); } [Fact] public void Deterministic() { var peStream = new MemoryStream(Misc.Deterministic); using (var reader = new PEReader(peStream)) { ValidateDeterministic(reader); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void Deterministic_Loaded() { LoaderUtilities.LoadPEAndValidate(Misc.Deterministic, ValidateDeterministic); } private void ValidateDeterministic(PEReader reader) { // dumpbin: // // Debug Directories // // Time Type Size RVA Pointer // -------- ------- -------- -------- -------- // D2FC74D3 cv 32 00002338 538 Format: RSDS, {814C578F-7676-0263-4F8A-2D3E8528EAF1}, 1, C:\Temp\Deterministic.pdb // 00000000 repro 0 00000000 0 var entries = reader.ReadDebugDirectory(); var cvEntry = entries[0]; Assert.Equal(DebugDirectoryEntryType.CodeView, cvEntry.Type); Assert.False(cvEntry.IsPortableCodeView); Assert.Equal(0x0538, cvEntry.DataPointer); Assert.Equal(0x2338, cvEntry.DataRelativeVirtualAddress); Assert.Equal(0x0032, cvEntry.DataSize); // no NUL padding Assert.Equal(0, cvEntry.MajorVersion); Assert.Equal(0, cvEntry.MinorVersion); Assert.Equal(0xD2FC74D3u, cvEntry.Stamp); var cv = reader.ReadCodeViewDebugDirectoryData(cvEntry); Assert.Equal(1, cv.Age); Assert.Equal(new Guid("814C578F-7676-0263-4F8A-2D3E8528EAF1"), cv.Guid); Assert.Equal(@"C:\Temp\Deterministic.pdb", cv.Path); var detEntry = entries[1]; Assert.Equal(DebugDirectoryEntryType.Reproducible, detEntry.Type); Assert.False(detEntry.IsPortableCodeView); Assert.Equal(0, detEntry.DataPointer); Assert.Equal(0, detEntry.DataRelativeVirtualAddress); Assert.Equal(0, detEntry.DataSize); Assert.Equal(0, detEntry.MajorVersion); Assert.Equal(0, detEntry.MinorVersion); Assert.Equal(0u, detEntry.Stamp); Assert.Equal(2, entries.Length); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void EmbeddedPortablePdb_Loaded() { LoaderUtilities.LoadPEAndValidate( PortablePdbs.DocumentsEmbeddedDll, ValidateEmbeddedPortablePdb ); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void EmbeddedPortablePdb_Loaded_FromStream() { LoaderUtilities.LoadPEAndValidate( PortablePdbs.DocumentsEmbeddedDll, ValidateEmbeddedPortablePdb, useStream: true ); } private void ValidateEmbeddedPortablePdb(PEReader reader) { var entries = reader.ReadDebugDirectory(); Assert.Equal(DebugDirectoryEntryType.CodeView, entries[0].Type); Assert.Equal(DebugDirectoryEntryType.Reproducible, entries[1].Type); Assert.Equal(DebugDirectoryEntryType.EmbeddedPortablePdb, entries[2].Type); using ( MetadataReaderProvider provider = reader.ReadEmbeddedPortablePdbDebugDirectoryData( entries[2] ) ) { var pdbReader = provider.GetMetadataReader(); var document = pdbReader.GetDocument(pdbReader.Documents.First()); Assert.Equal(@"C:\Documents.cs", pdbReader.GetString(document.Name)); } } [Fact] public void DebugDirectoryData_Errors() { var reader = new PEReader(new MemoryStream(Misc.Members)); AssertExtensions.Throws<ArgumentException>( "entry", () => reader.ReadCodeViewDebugDirectoryData( new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.Coff, 0, 0, 0) ) ); Assert.Throws<BadImageFormatException>( () => reader.ReadCodeViewDebugDirectoryData( new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.CodeView, 0, 0, 0) ) ); AssertExtensions.Throws<ArgumentException>( "entry", () => reader.ReadEmbeddedPortablePdbDebugDirectoryData( new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.Coff, 0, 0, 0) ) ); Assert.Throws<BadImageFormatException>( () => reader.ReadEmbeddedPortablePdbDebugDirectoryData( new DebugDirectoryEntry( 0, 0, 0, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0 ) ) ); } [Fact] public void ValidateEmbeddedPortablePdbVersion() { // major version (Portable PDB format): PEReader.ValidateEmbeddedPortablePdbVersion( new DebugDirectoryEntry( 0, 0x0100, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0 ) ); PEReader.ValidateEmbeddedPortablePdbVersion( new DebugDirectoryEntry( 0, 0x0101, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0 ) ); PEReader.ValidateEmbeddedPortablePdbVersion( new DebugDirectoryEntry( 0, 0xffff, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0 ) ); Assert.Throws<BadImageFormatException>( () => PEReader.ValidateEmbeddedPortablePdbVersion( new DebugDirectoryEntry( 0, 0x0000, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0 ) ) ); Assert.Throws<BadImageFormatException>( () => PEReader.ValidateEmbeddedPortablePdbVersion( new DebugDirectoryEntry( 0, 0x00ff, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0 ) ) ); // minor version (Embedded blob format): Assert.Throws<BadImageFormatException>( () => PEReader.ValidateEmbeddedPortablePdbVersion( new DebugDirectoryEntry( 0, 0x0100, 0x0101, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0 ) ) ); Assert.Throws<BadImageFormatException>( () => PEReader.ValidateEmbeddedPortablePdbVersion( new DebugDirectoryEntry( 0, 0x0100, 0x0000, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0 ) ) ); Assert.Throws<BadImageFormatException>( () => PEReader.ValidateEmbeddedPortablePdbVersion( new DebugDirectoryEntry( 0, 0x0100, 0x00ff, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0 ) ) ); Assert.Throws<BadImageFormatException>( () => PEReader.ValidateEmbeddedPortablePdbVersion( new DebugDirectoryEntry( 0, 0x0100, 0x0200, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0 ) ) ); } [Fact] public void CodeView_PathPadding() { var bytes = ImmutableArray.Create( new byte[] { (byte)'R', (byte)'S', (byte)'D', (byte)'S', // signature 0x6E, 0xE6, 0x88, 0x3C, 0xB9, 0xE0, 0x08, 0x45, 0x92, 0x90, 0x11, 0xE0, 0xDB, 0x51, 0xA1, 0xC5, // GUID 0x01, 0x00, 0x00, 0x00, // age (byte)'x', 0x00, 0x20, 0xff, // path } ); using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length)) { Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } using ( var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 1) ) { Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } using ( var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 2) ) { Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } using ( var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 3) ) { Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } using ( var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 4) ) { Assert.Equal("", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } } [Fact] public void CodeView_Errors() { var bytes = ImmutableArray.Create( new byte[] { (byte)'R', (byte)'S', (byte)'D', (byte)'S', // signature 0x6E, 0xE6, 0x88, 0x3C, 0xB9, 0xE0, 0x08, 0x45, 0x92, 0x90, 0x11, 0xE0, 0xDB, 0x51, 0xA1, 0xC5, // GUID 0x01, 0x00, 0x00, 0x00, // age (byte)'x', 0x00, // path } ); using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, 1)) { Assert.Throws<BadImageFormatException>( () => PEReader.DecodeCodeViewDebugDirectoryData(block) ); } using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, 4)) { Assert.Throws<BadImageFormatException>( () => PEReader.DecodeCodeViewDebugDirectoryData(block) ); } using ( var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 3) ) { Assert.Throws<BadImageFormatException>( () => PEReader.DecodeCodeViewDebugDirectoryData(block) ); } } [Fact] public void EmbeddedPortablePdb_Errors() { var bytes1 = ImmutableArray.Create( new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0xFF, 0xFF, 0xFF, 0xFF, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data } ); using (var block = new ByteArrayMemoryProvider(bytes1).GetMemoryBlock(0, bytes1.Length)) { Assert.Throws<BadImageFormatException>( () => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block) ); } var bytes2 = ImmutableArray.Create( new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0x09, 0x00, 0x00, 0x00, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data } ); using (var block = new ByteArrayMemoryProvider(bytes2).GetMemoryBlock(0, bytes2.Length)) { Assert.Throws<BadImageFormatException>( () => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block) ); } var bytes3 = ImmutableArray.Create( new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0x00, 0x00, 0x00, 0x00, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data } ); using (var block = new ByteArrayMemoryProvider(bytes3).GetMemoryBlock(0, bytes3.Length)) { Assert.Throws<BadImageFormatException>( () => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block) ); } var bytes4 = ImmutableArray.Create( new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0xff, 0xff, 0xff, 0x7f, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data } ); using (var block = new ByteArrayMemoryProvider(bytes4).GetMemoryBlock(0, bytes4.Length)) { Assert.Throws<BadImageFormatException>( () => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block) ); } var bytes5 = ImmutableArray.Create( new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0x08, 0x00, 0x00, 0x00, // uncompressed size 0xEF, 0xFF, 0x4F, 0xFF, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data } ); using (var block = new ByteArrayMemoryProvider(bytes4).GetMemoryBlock(0, bytes4.Length)) { Assert.Throws<BadImageFormatException>( () => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block) ); } var bytes6 = ImmutableArray.Create( new byte[] { 0x4D, 0x50, 0x44, 0x43, // signature 0x08, 0x00, 0x00, 0x00, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data } ); using (var block = new ByteArrayMemoryProvider(bytes6).GetMemoryBlock(0, bytes6.Length)) { Assert.Throws<BadImageFormatException>( () => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block) ); } var bytes7 = ImmutableArray.Create( new byte[] { 0x4D, 0x50, 0x44, 0x43, // signature 0x08, 0x00, 0x00, } ); using (var block = new ByteArrayMemoryProvider(bytes7).GetMemoryBlock(0, bytes7.Length)) { Assert.Throws<BadImageFormatException>( () => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block) ); } var bytes8 = ImmutableArray.Create( new byte[] { 0x4D, 0x50, 0x44, 0x43, // signature 0x08, 0x00, 0x00, } ); using (var block = new ByteArrayMemoryProvider(bytes8).GetMemoryBlock(0, bytes8.Length)) { Assert.Throws<BadImageFormatException>( () => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block) ); } var bytes9 = ImmutableArray.Create( new byte[] { 0x4D, 0x50, 0x44, 0x43, // signature 0x08, 0x00, 0x00, 0x00 } ); using (var block = new ByteArrayMemoryProvider(bytes9).GetMemoryBlock(0, 1)) { Assert.Throws<BadImageFormatException>( () => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block) ); } } [Fact] public void PdbChecksum() { var bytes = ImmutableArray.Create( new byte[] { (byte)'A', (byte)'L', (byte)'G', 0, // AlgorithmName 0x01, 0x02, 0x03, 0x04, 0x05 // checksum } ); using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length)) { var data = PEReader.DecodePdbChecksumDebugDirectoryData(block); Assert.Equal("ALG", data.AlgorithmName); AssertEx.Equal(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 }, data.Checksum); } } [Theory] [InlineData( new byte[] { 0, // AlgorithmName 0x01, 0x02, 0x03, 0x04, 0x05 // checksum } )] [InlineData(new byte[] { 0x01, 0x01, 0x02, 0x03, 0x04, 0x05 })] [InlineData(new byte[] { 0x01, 0x00 })] [InlineData(new byte[] { 0x00 })] [InlineData(new byte[] { 0x01 })] [InlineData(new byte[0])] public void PdbChecksum_Errors(byte[] blob) { var bytes = ImmutableArray.Create(blob); using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length)) { Assert.Throws<BadImageFormatException>( () => PEReader.DecodePdbChecksumDebugDirectoryData(block) ); } } } }
33.112821
146
0.41726
[ "MIT" ]
belav/runtime
src/libraries/System.Reflection.Metadata/tests/PortableExecutable/DebugDirectoryTests.cs
25,828
C#
using System.Linq; using System.Net.Http.Formatting; using System.Web.Http; using Newtonsoft.Json.Serialization; namespace OAuthExample { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 配置和服务 // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First(); jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } } }
28.142857
109
0.623096
[ "MIT" ]
buyixiaohan/OAuthExample
OAuthExample/App_Start/WebApiConfig.cs
804
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Kusto.V20190515 { /// <summary> /// Class representing a Kusto cluster. /// </summary> [AzureNextGenResourceType("azure-nextgen:kusto/v20190515:Cluster")] public partial class Cluster : Pulumi.CustomResource { /// <summary> /// The cluster data ingestion URI. /// </summary> [Output("dataIngestionUri")] public Output<string> DataIngestionUri { get; private set; } = null!; /// <summary> /// A boolean value that indicates if the cluster's disks are encrypted. /// </summary> [Output("enableDiskEncryption")] public Output<bool?> EnableDiskEncryption { get; private set; } = null!; /// <summary> /// A boolean value that indicates if the streaming ingest is enabled. /// </summary> [Output("enableStreamingIngest")] public Output<bool?> EnableStreamingIngest { get; private set; } = null!; /// <summary> /// The geo-location where the resource lives /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// The name of the resource /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Optimized auto scale definition. /// </summary> [Output("optimizedAutoscale")] public Output<Outputs.OptimizedAutoscaleResponse?> OptimizedAutoscale { get; private set; } = null!; /// <summary> /// The provisioned state of the resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The SKU of the cluster. /// </summary> [Output("sku")] public Output<Outputs.AzureSkuResponse> Sku { get; private set; } = null!; /// <summary> /// The state of the resource. /// </summary> [Output("state")] public Output<string> State { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// The cluster's external tenants. /// </summary> [Output("trustedExternalTenants")] public Output<ImmutableArray<Outputs.TrustedExternalTenantResponse>> TrustedExternalTenants { get; private set; } = null!; /// <summary> /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// The cluster URI. /// </summary> [Output("uri")] public Output<string> Uri { get; private set; } = null!; /// <summary> /// Virtual network definition. /// </summary> [Output("virtualNetworkConfiguration")] public Output<Outputs.VirtualNetworkConfigurationResponse?> VirtualNetworkConfiguration { get; private set; } = null!; /// <summary> /// The availability zones of the cluster. /// </summary> [Output("zones")] public Output<ImmutableArray<string>> Zones { get; private set; } = null!; /// <summary> /// Create a Cluster resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Cluster(string name, ClusterArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:kusto/v20190515:Cluster", name, args ?? new ClusterArgs(), MakeResourceOptions(options, "")) { } private Cluster(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:kusto/v20190515:Cluster", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:kusto:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/latest:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20170907privatepreview:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20180907preview:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20190121:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20190907:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20191109:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20200215:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20200614:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20200918:Cluster"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing Cluster resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Cluster Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new Cluster(name, id, options); } } public sealed class ClusterArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the Kusto cluster. /// </summary> [Input("clusterName")] public Input<string>? ClusterName { get; set; } /// <summary> /// A boolean value that indicates if the cluster's disks are encrypted. /// </summary> [Input("enableDiskEncryption")] public Input<bool>? EnableDiskEncryption { get; set; } /// <summary> /// A boolean value that indicates if the streaming ingest is enabled. /// </summary> [Input("enableStreamingIngest")] public Input<bool>? EnableStreamingIngest { get; set; } /// <summary> /// The geo-location where the resource lives /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// Optimized auto scale definition. /// </summary> [Input("optimizedAutoscale")] public Input<Inputs.OptimizedAutoscaleArgs>? OptimizedAutoscale { get; set; } /// <summary> /// The name of the resource group containing the Kusto cluster. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The SKU of the cluster. /// </summary> [Input("sku", required: true)] public Input<Inputs.AzureSkuArgs> Sku { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } [Input("trustedExternalTenants")] private InputList<Inputs.TrustedExternalTenantArgs>? _trustedExternalTenants; /// <summary> /// The cluster's external tenants. /// </summary> public InputList<Inputs.TrustedExternalTenantArgs> TrustedExternalTenants { get => _trustedExternalTenants ?? (_trustedExternalTenants = new InputList<Inputs.TrustedExternalTenantArgs>()); set => _trustedExternalTenants = value; } /// <summary> /// Virtual network definition. /// </summary> [Input("virtualNetworkConfiguration")] public Input<Inputs.VirtualNetworkConfigurationArgs>? VirtualNetworkConfiguration { get; set; } [Input("zones")] private InputList<string>? _zones; /// <summary> /// The availability zones of the cluster. /// </summary> public InputList<string> Zones { get => _zones ?? (_zones = new InputList<string>()); set => _zones = value; } public ClusterArgs() { EnableStreamingIngest = false; } } }
38.171875
130
0.581867
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Kusto/V20190515/Cluster.cs
9,772
C#
// This file was auto-generated based on version 1.1.0 of the canonical data. using Xunit; namespace HelloWorld; public class HelloWorldTests { [Fact] public void Say_hi_() { Assert.Equal("Hello, World!", HelloWorld.Hello()); } }
17.133333
77
0.66537
[ "MIT" ]
dalprahcd/exercism-solutions
csharp/hello-world/HelloWorldTests.cs
257
C#
using System.Windows.Automation; using TestStack.White.AutomationElementSearch; using TestStack.White.Configuration; using TestStack.White.Factory; using TestStack.White.UIItems.Actions; using TestStack.White.UIItems.Finders; using TestStack.White.UIItems.Scrolling; namespace TestStack.White.UIItems.TableItems { public class Table : UIItem, IVerticalSpanProvider, ITableVerticalScrollOffset { private TableRows rows; private TableHeader header; private readonly AutomationElementFinder finder; private readonly TableRowFactory tableRowFactory; protected Table() {} public Table(AutomationElement automationElement, IActionListener actionListener) : base(automationElement, actionListener) { finder = new AutomationElementFinder(automationElement); tableRowFactory = new TableRowFactory(finder); } public virtual TableRows Rows { get { return rows ?? (rows = tableRowFactory.CreateRows(this, Header ?? new NullTableHeader())); } } public virtual TableHeader Header { get { if (header == null) { AutomationElement headerElement = finder.Descendant(SearchCriteria.ByText(UIItemIdAppXmlConfiguration.Instance.TableHeader).AutomationCondition); if (headerElement == null) return null; header = (TableHeader) new TableHeaderFactory().Create(headerElement, actionListener); } return header; } } public virtual TableRow Row(string column, string value) { return Rows.Get(column, value); } public virtual TableRows FindAll(string column, string value) { return Rows.GetMultipleRows(column, value); } public virtual void Refresh() { rows = null; } public override void ActionPerforming(UIItem uiItem) { if (uiItem is Table) return; new ScreenItem(uiItem, ScrollBars).MakeVisible(this); } public override IScrollBars ScrollBars { get { return scrollBars ?? (scrollBars = new TableScrollBars(finder, ActionListener, this)); } } public override void RightClick() { new TooltipSafeMouse(mouse).RightClickOutsideToolTip(this, actionListener); } public virtual VerticalSpan VerticalSpan { get { return new VerticalSpan(Bounds); } } bool ITableVerticalScrollOffset.IsOnTop { get { if (Rows.Count == 0) return true; return !Rows[0].IsOffScreen; } } } }
32.719101
166
0.590316
[ "Apache-2.0", "MIT" ]
DaveWeath/White
src/TestStack.White/UIItems/TableItems/Table.cs
2,824
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // The test originally exposed the issue with predecessors lists: // 1. fgReplacePred did not keep the sorted order (GitHub_13295); // 2. fgAddRefPred did not find the existing occurrence if the order was not sorted; // 3. fgReplacePred had several occurrences of the same block and when it became dead it updated only the first link; // 4. The link to the dead block exposed noway_assert in flowgraph. // The repro required JitStress=2 or complus_jitstressmodenames=STRESS_BB_PROFILE; // STRESS_BB_PROFILE uses file name hash to set weights, so this file can't be renamed. #pragma warning disable using System; class testout1 { static bool static_field_bool; static bool sfb_false; static bool sfb_true; bool mfb; bool mfb_false; bool mfb_true; static bool simple_func_bool() { return true; } static bool func_sb_true() { return true; } static bool func_sb_false() { return false; } static int Sub_Funclet_411() { int True_Sum = 0; int False_Sum = 0; int index = 1; bool local_bool = true; testout1 t1_i = new testout1(); bool[] ab_false = new bool[3]; bool[] ab_true = new bool[3]; ab_true[0] = true; ab_true[1] = true; ab_true[2] = true; static_field_bool = true; sfb_false = false; sfb_true = true; t1_i.mfb = true; t1_i.mfb_false = false; t1_i.mfb_true = true; if (ab_true[index] && func_sb_true() ? static_field_bool : t1_i.mfb) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? static_field_bool : simple_func_bool()) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? static_field_bool : ab_true[index]) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? static_field_bool : ab_false[index]) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? t1_i.mfb : true) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? t1_i.mfb : false) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? t1_i.mfb : local_bool) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? t1_i.mfb : static_field_bool) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? t1_i.mfb : t1_i.mfb) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? t1_i.mfb : simple_func_bool()) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? t1_i.mfb : ab_true[index]) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? t1_i.mfb : ab_false[index]) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? simple_func_bool() : true) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? simple_func_bool() : false) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? simple_func_bool() : local_bool) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? simple_func_bool() : static_field_bool) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? simple_func_bool() : t1_i.mfb) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? simple_func_bool() : simple_func_bool()) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? simple_func_bool() : ab_true[index]) True_Sum++; else False_Sum++; if (ab_true[index] && func_sb_true() ? simple_func_bool() : ab_false[index]) True_Sum++; else False_Sum++; return (True_Sum * 2) - False_Sum; } public static int Main() { int Sum = 0; Sum += Sub_Funclet_411(); if (Sum == 40) { Console.WriteLine("PASSED"); return 100; } else { Console.WriteLine("FAILED"); return -1; } } }
41.979798
117
0.62873
[ "MIT" ]
2m0nd/runtime
src/tests/JIT/Regression/JitBlue/GitHub_18056/Bool_And_Op.cs
4,156
C#
using LoESoft.MapEditor.Core.GUI.HUD; namespace LoESoft.MapEditor.Core.GUI { partial class MapEditorForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MapEditorForm)); this.hud1 = new LoESoft.MapEditor.Core.GUI.HUD.HUD(); this.monoGameWindow1 = new LoESoft.MapEditor.Core.GUI.HUD.MEGameControl(); this.SuspendLayout(); // // hud1 // this.hud1.Location = new System.Drawing.Point(609, 0); this.hud1.Name = "hud1"; this.hud1.Size = new System.Drawing.Size(200, 608); this.hud1.TabIndex = 1; // // monoGameWindow1 // this.monoGameWindow1.Location = new System.Drawing.Point(0, 0); this.monoGameWindow1.Name = "monoGameWindow1"; this.monoGameWindow1.Size = new System.Drawing.Size(609, 608); this.monoGameWindow1.TabIndex = 0; this.monoGameWindow1.Text = "monoGameWindow1"; // // MapEditorForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(809, 608); this.Controls.Add(this.hud1); this.Controls.Add(this.monoGameWindow1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "MapEditorForm"; this.Text = "LoESoft Games - BRME Map Editor"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MapEditorForm_FormClosing); this.ResumeLayout(false); } #endregion private MEGameControl monoGameWindow1; private HUD.HUD hud1; } }
38.573333
145
0.588317
[ "MIT" ]
Devwarlt/loe-core
mapeditor/Core/GUI/MapEditorForm.Designer.cs
2,895
C#
#region Copyright // <<<<<<< HEAD <<<<<<< HEAD ======= ======= >>>>>>> update form orginal repo // DotNetNuke® - https://www.dnnsoftware.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion <<<<<<< HEAD >>>>>>> Merges latest changes from release/9.4.x into development (#3178) ======= >>>>>>> update form orginal repo #region Usings using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Threading; using DotNetNuke.Common.Utilities; using DotNetNuke.Data; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Log.EventLog; #endregion namespace DotNetNuke.Common.Lists { public class ListController { public readonly string[] NonLocalizedLists = { "ContentTypes", "Processor", "DataType", "ProfanityFilter", "BannedPasswords" }; #region Private Methods private void ClearListCache(int portalId) { DataCache.ClearListsCache(portalId); } private void ClearEntriesCache(string listName, int portalId) { string cacheKey = string.Format(DataCache.ListEntriesCacheKey, portalId, listName); DataCache.RemoveCache(cacheKey); } private ListInfo FillListInfo(IDataReader dr, bool CheckForOpenDataReader) { ListInfo list = null; // read datareader bool canContinue = true; if (CheckForOpenDataReader) { canContinue = false; if (dr.Read()) { canContinue = true; } } if (canContinue) { list = new ListInfo(Convert.ToString(dr["ListName"])); { list.Level = Convert.ToInt32(dr["Level"]); list.PortalID = Convert.ToInt32(dr["PortalID"]); list.DefinitionID = Convert.ToInt32(dr["DefinitionID"]); list.EntryCount = Convert.ToInt32(dr["EntryCount"]); list.ParentID = Convert.ToInt32(dr["ParentID"]); list.ParentKey = Convert.ToString(dr["ParentKey"]); list.Parent = Convert.ToString(dr["Parent"]); list.ParentList = Convert.ToString(dr["ParentList"]); list.EnableSortOrder = (Convert.ToInt32(dr["MaxSortOrder"]) > 0); list.SystemList = Convert.ToInt32(dr["SystemList"]) > 0; } } return list; } private Dictionary<string, ListInfo> FillListInfoDictionary(IDataReader dr) { var dic = new Dictionary<string, ListInfo>(); try { while (dr.Read()) { // fill business object ListInfo list = FillListInfo(dr, false); if (!dic.ContainsKey(list.Key)) { dic.Add(list.Key, list); } } } catch (Exception exc) { Exceptions.LogException(exc); } finally { // close datareader CBO.CloseDataReader(dr, true); } return dic; } private Dictionary<string, ListInfo> GetListInfoDictionary(int portalId) { string cacheKey = string.Format(DataCache.ListsCacheKey, portalId); return CBO.GetCachedObject<Dictionary<string, ListInfo>>(new CacheItemArgs(cacheKey, DataCache.ListsCacheTimeOut, DataCache.ListsCachePriority), c => FillListInfoDictionary(DataProvider.Instance().GetLists(portalId))); } private IEnumerable<ListEntryInfo> GetListEntries(string listName, int portalId) { string cacheKey = string.Format(DataCache.ListEntriesCacheKey, portalId, listName); return CBO.GetCachedObject<IEnumerable<ListEntryInfo>>(new CacheItemArgs(cacheKey, DataCache.ListsCacheTimeOut, DataCache.ListsCachePriority), c => CBO.FillCollection<ListEntryInfo>(DataProvider.Instance().GetListEntriesByListName(listName, String.Empty, portalId))); } #endregion /// <summary> /// Adds a new list entry to the database. If the current thread locale is not "en-US" then the text value will also be /// persisted to a resource file under App_GlobalResources using the list's name and the value as key. /// </summary> /// <param name="listEntry">The list entry.</param> /// <returns></returns> public int AddListEntry(ListEntryInfo listEntry) { bool enableSortOrder = listEntry.SortOrder > 0; ClearListCache(listEntry.PortalID); int entryId = DataProvider.Instance().AddListEntry(listEntry.ListName, listEntry.Value, listEntry.TextNonLocalized, listEntry.ParentID, listEntry.Level, enableSortOrder, listEntry.DefinitionID, listEntry.Description, listEntry.PortalID, listEntry.SystemList, UserController.Instance.GetCurrentUserInfo().UserID); if (entryId != Null.NullInteger) { EventLogController.Instance.AddLog(listEntry, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.LISTENTRY_CREATED); } if (Thread.CurrentThread.CurrentCulture.Name != Localization.SystemLocale && !NonLocalizedLists.Contains(listEntry.ListName)) { if (string.IsNullOrEmpty(listEntry.ParentKey)) { LocalizationProvider.Instance.SaveString(listEntry.Value + ".Text", listEntry.TextNonLocalized, listEntry.ResourceFileRoot, Thread.CurrentThread.CurrentCulture.Name, PortalController.Instance.GetCurrentPortalSettings(), LocalizationProvider.CustomizedLocale.None, true, true); } else { LocalizationProvider.Instance.SaveString(listEntry.ParentKey + "." + listEntry.Value + ".Text", listEntry.TextNonLocalized, listEntry.ResourceFileRoot, Thread.CurrentThread.CurrentCulture.Name, PortalController.Instance.GetCurrentPortalSettings(), LocalizationProvider.CustomizedLocale.None, true, true); } } ClearEntriesCache(listEntry.ListName, listEntry.PortalID); return entryId; } public void DeleteList(string listName, string parentKey) { DeleteList(listName, parentKey, Null.NullInteger); } public void DeleteList(string listName, string parentKey, int portalId) { ListInfo list = GetListInfo(listName, parentKey, portalId); EventLogController.Instance.AddLog("ListName", listName, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.LISTENTRY_DELETED); DataProvider.Instance().DeleteList(listName, parentKey); if (list != null) { ClearListCache(list.PortalID); ClearEntriesCache(list.Name, list.PortalID); } } public void DeleteList(ListInfo list, bool includeChildren) { if (list == null) { return; } var lists = new SortedList<string, ListInfo>(); lists.Add(list.Key, list); //add Children if (includeChildren) { foreach (KeyValuePair<string, ListInfo> listPair in GetListInfoDictionary(list.PortalID)) { if ((listPair.Value.ParentList.StartsWith(list.Key))) { lists.Add(listPair.Value.Key.Replace(":", "."), listPair.Value); } } } //Delete items in reverse order so deeper descendants are removed before their parents for (int i = lists.Count - 1; i >= 0; i += -1) { DeleteList(lists.Values[i].Name, lists.Values[i].ParentKey, lists.Values[i].PortalID); } } public void DeleteListEntryByID(int entryId, bool deleteChild) { ListEntryInfo entry = GetListEntryInfo(entryId); DataProvider.Instance().DeleteListEntryByID(entryId, deleteChild); ClearListCache(entry.PortalID); ClearEntriesCache(entry.ListName, entry.PortalID); } public void DeleteListEntryByListName(string listName, string listValue, bool deleteChild) { ListEntryInfo entry = GetListEntryInfo(listName, listValue); DataProvider.Instance().DeleteListEntryByListName(listName, listValue, deleteChild); ClearListCache(entry.PortalID); ClearEntriesCache(listName, entry.PortalID); } public ListEntryInfo GetListEntryInfo(int entryId) { return CBO.FillObject<ListEntryInfo>(DataProvider.Instance().GetListEntry(entryId)); } public ListEntryInfo GetListEntryInfo(string listName, int entryId) { return GetListEntries(listName, Null.NullInteger).SingleOrDefault(l => l.EntryID == entryId); } public ListEntryInfo GetListEntryInfo(string listName, string listValue) { return GetListEntries(listName, Null.NullInteger).SingleOrDefault(l => l.Value == listValue); } public IEnumerable<ListEntryInfo> GetListEntryInfoItems(string listName) { return GetListEntries(listName, Null.NullInteger); } public IEnumerable<ListEntryInfo> GetListEntryInfoItems(string listName, string parentKey) { return GetListEntries(listName, Null.NullInteger).Where(l => l.ParentKey == parentKey); } public IEnumerable<ListEntryInfo> GetListEntryInfoItems(string listName, string parentKey, int portalId) { return GetListEntries(listName, portalId).Where(l => l.ParentKey == parentKey); } public Dictionary<string, ListEntryInfo> GetListEntryInfoDictionary(string listName) { return GetListEntryInfoDictionary(listName, "", Null.NullInteger); } public Dictionary<string, ListEntryInfo> GetListEntryInfoDictionary(string listName, string parentKey) { return GetListEntryInfoDictionary(listName, parentKey, Null.NullInteger); } public Dictionary<string, ListEntryInfo> GetListEntryInfoDictionary(string listName, string parentKey, int portalId) { return ListEntryInfoItemsToDictionary(GetListEntryInfoItems(listName, parentKey, portalId)); } private static Dictionary<string, ListEntryInfo> ListEntryInfoItemsToDictionary(IEnumerable<ListEntryInfo> items) { var dict = new Dictionary<string, ListEntryInfo>(); items.ToList().ForEach(x => dict.Add(x.Key, x)); return dict; } public ListInfo GetListInfo(string listName) { return GetListInfo(listName, ""); } public ListInfo GetListInfo(string listName, string parentKey) { return GetListInfo(listName, parentKey, -1); } public ListInfo GetListInfo(string listName, string parentKey, int portalId) { ListInfo list = null; string key = Null.NullString; if (!string.IsNullOrEmpty(parentKey)) { key = parentKey + ":"; } key += listName; Dictionary<string, ListInfo> dicLists = GetListInfoDictionary(portalId); if (!dicLists.TryGetValue(key, out list)) { IDataReader dr = DataProvider.Instance().GetList(listName, parentKey, portalId); try { list = FillListInfo(dr, true); } finally { CBO.CloseDataReader(dr, true); } } return list; } public ListInfoCollection GetListInfoCollection() { return GetListInfoCollection(""); } public ListInfoCollection GetListInfoCollection(string listName) { return GetListInfoCollection(listName, ""); } public ListInfoCollection GetListInfoCollection(string listName, string parentKey) { return GetListInfoCollection(listName, parentKey, -1); } public ListInfoCollection GetListInfoCollection(string listName, string parentKey, int portalId) { IList lists = new ListInfoCollection(); foreach (KeyValuePair<string, ListInfo> listPair in GetListInfoDictionary(portalId).OrderBy(l => l.Value.DisplayName)) { ListInfo list = listPair.Value; if ((list.Name == listName || string.IsNullOrEmpty(listName)) && (list.ParentKey == parentKey || string.IsNullOrEmpty(parentKey)) && (list.PortalID == portalId || portalId == Null.NullInteger)) { lists.Add(list); } } return (ListInfoCollection)lists; } /// <summary> /// Updates the list entry in the database using the values set on the listEntry. Note that if the current thread locale is not "en-US" then the /// text value will be persisted to a resource file under App_GlobalResources using the list's name and the value as key. Also the supplied text value /// will *not* be written to the database in this case (i.e. we expect the text value in the database to be the en-US text value). /// </summary> /// <param name="listEntry">The list entry info item to update.</param> public void UpdateListEntry(ListEntryInfo listEntry) { if (Thread.CurrentThread.CurrentCulture.Name == Localization.SystemLocale || NonLocalizedLists.Contains(listEntry.ListName)) { DataProvider.Instance().UpdateListEntry(listEntry.EntryID, listEntry.Value, listEntry.TextNonLocalized, listEntry.Description, UserController.Instance.GetCurrentUserInfo().UserID); } else { var oldItem = GetListEntryInfo(listEntry.EntryID); // look up existing db record to be able to just update the value or description and not touch the en-US text value DataProvider.Instance().UpdateListEntry(listEntry.EntryID, listEntry.Value, oldItem.TextNonLocalized, listEntry.Description, UserController.Instance.GetCurrentUserInfo().UserID); var key = string.IsNullOrEmpty(listEntry.ParentKey) ? listEntry.Value + ".Text" : listEntry.ParentKey + "." + listEntry.Value + ".Text"; LocalizationProvider.Instance.SaveString(key, listEntry.TextNonLocalized, listEntry.ResourceFileRoot, Thread.CurrentThread.CurrentCulture.Name, PortalController.Instance.GetCurrentPortalSettings(), LocalizationProvider.CustomizedLocale.None, true, true); } EventLogController.Instance.AddLog(listEntry, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.LISTENTRY_UPDATED); ClearListCache(listEntry.PortalID); ClearEntriesCache(listEntry.ListName, listEntry.PortalID); } public void UpdateListSortOrder(int EntryID, bool MoveUp) { DataProvider.Instance().UpdateListSortOrder(EntryID, MoveUp); ListEntryInfo entry = GetListEntryInfo(EntryID); ClearListCache(entry.PortalID); ClearEntriesCache(entry.ListName, entry.PortalID); } } }
44.718519
309
0.599194
[ "MIT" ]
DnnSoftwarePersian/Dnn.Platform
DNN Platform/Library/Common/Lists/ListController.cs
18,112
C#
namespace Aurora.Profiles.ResidentEvil2.GSI.Nodes { /// <summary> /// Class representing player information /// </summary> public class Player_ResidentEvil2 : Node<Player_ResidentEvil2> { public enum PlayerStatus { /// <summary> /// Not in-game /// </summary> OffGame = -1, /// <summary> /// Dead /// </summary> Dead = 0, /// <summary> /// Danger /// </summary> Danger = 1, /// <summary> /// Caution /// </summary> Caution = 2, /// <summary> /// Lite Fine /// </summary> LiteFine = 3, /// <summary> /// Fine /// </summary> Fine = 4 } /// <summary> /// Player's maximum health, currently 1200 in all modes. /// </summary> public int MaximumHealth = 0; // max health 0 means not in-game /// <summary> /// Player's health amount [0, 1200]. /// </summary> public int CurrentHealth = 0; /// <summary> /// Player's status (e.g., Fine, Caution, Danger, etc.). OffGame means player is not in-game. /// </summary> public PlayerStatus Status = PlayerStatus.OffGame; /// <summary> /// Player's poison status. Poison status is separate from health status. /// </summary> public bool Poison = false; /// <summary> /// The dynamic difficulty of the game. Changes as player kills enemies or gets hurt. /// </summary> public int Rank = 0; internal Player_ResidentEvil2(string json_data) : base(json_data) { } } }
26.583333
102
0.449843
[ "MIT" ]
CalcProgrammer1/Aurora
Project-Aurora/Project-Aurora/Profiles/Resident Evil 2/GSI/Nodes/Player.cs
1,845
C#
using System.Collections.Generic; using System.Globalization; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Core.IO; using Cake.Core.Tooling; public class GitTool : Tool<GitToolSettings> { readonly ICakeLog logger; public GitTool(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools, ICakeLog logger) : base(fileSystem, environment, processRunner, tools) { this.logger = logger; } public GitTool(ICakeContext context) : this(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools, context.Log) { } public int LastExitCode { get; set; } public bool AllowExitCodeForStatus { get; set; } public void RunGit(GitToolSettings settings, ProcessArgumentBuilder args) { Run(settings, args); if (LastExitCode != 0) { const string message = "{0}: Process returned an error (exit code {1})."; throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, GetToolName(), LastExitCode)); } } public int RunGitCheck(GitToolSettings settings, ProcessArgumentBuilder args) { LastExitCode = 0; Run(settings, args); return LastExitCode; } /// <summary> /// Called by Tool base class /// </summary> /// <returns></returns> protected override string GetToolName() => "Git"; /// <summary> /// Called by Tool base class to retrieve the executables that should be invoked with the given arguments /// when calling <see cref="Run"/>. /// </summary> /// <returns></returns> protected override IEnumerable<string> GetToolExecutableNames() => new List<string> {"Git.exe", "git.exe"}; /// <summary> /// Called by Tool base class the inject the exit code of the executable retrieved via <see cref="GetToolExecutableNames"/>. /// </summary> /// <param name="exitCode"></param> protected override void ProcessExitCode(int exitCode) => LastExitCode = exitCode; }
31.056338
128
0.630839
[ "MIT" ]
moerwald/AutoCake
src/AutoCake.Release/GitTool.cs
2,205
C#
// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Steeltoe.Common.HealthChecks; using Steeltoe.Management.Endpoint; using Steeltoe.Management.Endpoint.Handler; using Steeltoe.Management.Endpoint.Health.Contributor; using System.Collections.Generic; namespace Steeltoe.Management.EndpointWeb.Test { public class ManagementConfig { public static IList<IActuatorHandler> ConfigureManagementActuators(LoggerFactory loggerFactory = null, Dictionary<string, string> settings = null) { var configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); ActuatorConfigurator.ConfiguredHandlers.Clear(); // Clear setup between tests ActuatorConfigurator.ClearManagementOptions(); ActuatorConfigurator.UseAllActuators(configuration, null, GetHealthContributors(configuration), null, loggerFactory); return ActuatorConfigurator.ConfiguredHandlers; } private static IEnumerable<IHealthContributor> GetHealthContributors(IConfiguration configuration) { var healthContributors = new List<IHealthContributor> { new DiskSpaceContributor(), }; return healthContributors; } } }
40.652174
154
0.750802
[ "ECL-2.0", "Apache-2.0" ]
spring-operator/Management
test/Steeltoe.Management.EndpointWeb.Test/ManagementConfig.cs
1,872
C#
namespace API.Helpers; public class LikesParams : PaginationParams { public int UserId { get; set; } public string Predicate { get; set; } }
18.75
43
0.7
[ "MIT" ]
FernandoDevBh/DattingApp
API/Helpers/LikesParams.cs
150
C#
namespace Hexalith.OpenIdDict.Settings { using System.Collections.Generic; public class OpenIdSettings { public IEnumerable<string>? AuthorizedUrls { get; init; } public IEnumerable<string>? CertificatePaths { get; init; } public string? EncryptionCertificateFile { get; init; } public string? EncryptionCertificateThumbprint { get; init; } public string? EncryptionCertificateFilePassword { get; init; } public string? SigningCertificateFile { get; init; } public string? SigningCertificateFilePassword { get; init; } public string? SigningCertificateThumbprint { get; init; } public string? SigningCertificateThumbprintPassword { get; init; } public bool AllowGoogleAuthentication { get; init; } public bool AllowFacebookAuthentication { get; init; } public bool AllowMicrosoftAuthentication { get; init; } } }
46.3
74
0.699784
[ "MIT" ]
Hexalith/Hexalith
src/Modules/Server/Hexalith.OpenIdDict.Server/Settings/OpenIdSettings.cs
928
C#
namespace Todos { public class Todo { public int Id { get; set; } public string Name { get; set; } public bool IsComplete { get; set; } } }
17.7
44
0.531073
[ "MIT" ]
SteveSandersonMS/featherhttp.framework
samples/todo/TodoBasicWithAuth/Todo.cs
179
C#
using Notus.Data.Infrastructure; using Notus.Model.Models; namespace Notus.Data.Repository { public class SecurityTokenRepository : RepositoryBase<SecurityToken>, ISecurityTokenRepository { public SecurityTokenRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } } public interface ISecurityTokenRepository : IRepository<SecurityToken> { } }
24.941176
98
0.716981
[ "Apache-2.0" ]
gamunu/notus
Notus.Data/Repository/SecurityTokenRepository.cs
426
C#
using BentoEx.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace BentoEx.View { public class OrderStatusToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { try { if (Enum.Equals(value, Bento.OrderStatus.ordered)) return "注文済み"; else if (Enum.Equals(value, Bento.OrderStatus.expired)) return "受付終了"; else return string.Empty; } catch { return string.Empty; } } // No need to implement converting back on a one-way binding public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } // https://stackoverflow.com/questions/34337755/convert-enum-to-string-inside-textblock-text public class EnumToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string EnumString; try { EnumString = Enum.GetName((value.GetType()), value); return EnumString; } catch { return string.Empty; } } // No need to implement converting back on a one-way binding public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } public class BoolToValueConverter<T> : IValueConverter { public T FalseValue { get; set; } public T TrueValue { get; set; } public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) return FalseValue; else return (bool)value ? TrueValue : FalseValue; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value != null ? value.Equals(TrueValue) : false; } } public class BoolToStringConverter : BoolToValueConverter<String> { } }
33.9375
125
0.58011
[ "MIT" ]
kmaki565/BentoEx
BentoEx/View/Converter.cs
2,733
C#
// ******************************************************************************************************** // <copyright file="MWLite.Symbology.cs" company="MapWindow.org"> // Copyright (c) MapWindow.org. All rights reserved. // </copyright> // The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http:// Www.mozilla.org/MPL/ // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either express or implied. See the License for the specificlanguage governing rights and // limitations under the License. // // The Initial Developer of this version of the Original Code is Sergei Leschinski // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Change Log: // Date Changed By Notes // ******************************************************************************************************** using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using MWLite.Symbology.Classes; using MWLite.Symbology.Controls; using MapWinGIS; using MWLite.Symbology.LegendControl; using MWLite.Symbology.Classes; namespace MWLite.Symbology.Forms.Symbology { public partial class LinesForm : Form { #region Member variables // reference to the legend internal LegendControl.Legend m_legend = null; // layer being edited internal Layer m_layer = null; // the options to edit ShapeDrawingOptions _options = null; // prevents the unwanted events private bool _noEvents = false; // the serialized version of the initial state private string _initState = ""; // tab index to open on the next loading internal static int _tabIndex = 0; // column indices for the grid private const int CMN_PICTURE = 0; private const int CMN_TYPE = 1; #endregion #region Initialization /// <summary> /// Creates a new instance of PolygonsForm class /// </summary> public LinesForm(LegendControl.Legend legend, Layer layer, ShapeDrawingOptions options, bool applyDisabled) { InitializeComponent(); if (options == null || layer == null) { throw new Exception("PolygonsForm: unexpected null parameter"); } else { _options = options; m_layer = layer; } m_legend = legend; btnApply.Visible = !applyDisabled; _initState = options.Serialize(); icbLineType.ComboStyle = ImageComboStyle.LineStyle; icbLineWidth.ComboStyle = ImageComboStyle.LineWidth; groupMarker.Parent = tabLine; groupMarker.Top = groupLine.Top; groupMarker.Left = groupLine.Left; cboVerticesType.Items.Clear(); cboVerticesType.Items.Add("Square"); cboVerticesType.Items.Add("Circle"); cboOrientation.Items.Clear(); cboOrientation.Items.Add("Horizontal"); cboOrientation.Items.Add("Parallel"); cboOrientation.Items.Add("Perpendicular"); cboLineType.Items.Clear(); cboLineType.Items.Add("Line"); cboLineType.Items.Add("Marker"); cboLineType.SelectedIndexChanged += new EventHandler(cboLineType_SelectedIndexChanged); cboLineType.SelectedIndex = 0; // vertices chkVerticesVisible.CheckedChanged += new EventHandler(GUI2Options); cboVerticesType.SelectedIndexChanged += new EventHandler(GUI2Options); clpVerticesColor.SelectedColorChanged += new EventHandler(GUI2Options); chkVerticesFillVisible.CheckedChanged += new EventHandler(GUI2Options); udVerticesSize.ValueChanged += new EventHandler(GUI2Options); InitLinePattern(); Options2Grid(); Options2GUI(); linePatternControl1.LoadFromXML(); _noEvents = true; tabControl1.SelectedIndex = _tabIndex; _noEvents = false; } /// <summary> /// Take cate that a line pattern actually exists /// </summary> void InitLinePattern() { if (_options.LinePattern == null) { _options.LinePattern = new LinePattern(); } if (_options.LinePattern.Count == 0) { _options.LinePattern.AddLine(_options.LineColor, _options.LineWidth, _options.LineStipple); } } /// <summary> /// Updates the enabled state of the controls /// </summary> void RefreshControlState() { bool exists = (dgv.SelectedRows.Count > 0) && (dgv.Rows.Count > 1); btnRemove.Enabled = exists; if (exists) { int index = dgv.SelectedRows[0].Index; btnMoveUp.Enabled = index > 0; btnMoveDown.Enabled = index < dgv.Rows.Count - 1; } else { btnMoveDown.Enabled = false; btnMoveUp.Enabled = false; } } #endregion #region PropertyExchange /// <summary> /// Sets the values entered by user to the class /// </summary> private void GUI2Options(object sender, EventArgs e) { if (_noEvents) return; // vertices _options.VerticesVisible = chkVerticesVisible.Checked; _options.VerticesFillVisible = chkVerticesFillVisible.Checked; _options.VerticesSize = (int)udVerticesSize.Value; _options.VerticesColor = Colors.ColorToUInteger(clpVerticesColor.Color); _options.VerticesType = (tkVertexType)cboVerticesType.SelectedIndex; // transparency _options.LineTransparency = transparencyControl1.Value; if (_options.LinePattern != null) { _options.LinePattern.Transparency = (byte)_options.LineTransparency; } if (dgv.SelectedRows.Count > 0) { int index = dgv.SelectedRows[0].Index; MapWinGIS.LineSegment line = _options.LinePattern.get_Line(index); if (line != null) { line.LineType = cboLineType.SelectedIndex == 0 ? tkLineType.lltSimple : tkLineType.lltMarker; // showing the options if (cboLineType.SelectedIndex == 0) { line.LineStyle = (tkDashStyle)icbLineType.SelectedIndex; line.LineWidth = icbLineWidth.SelectedIndex + 1; line.Color = Colors.ColorToUInteger(clpOutline.Color); } else { line.Marker = (tkDefaultPointSymbol)pointSymbolControl1.SelectedIndex; line.MarkerInterval = (float)udMarkerInterval.Value; line.MarkerSize = (float)udMarkerSize.Value; line.Color = Colors.ColorToUInteger(clpMarkerFill.Color); line.MarkerOutlineColor = Colors.ColorToUInteger(clpMarkerOutline.Color); line.MarkerOrientation = (tkLineLabelOrientation)cboOrientation.SelectedIndex; line.MarkerOffset = (float)udMarkerOffset.Value; if (pointSymbolControl1.ForeColor != clpMarkerFill.Color) { pointSymbolControl1.ForeColor = clpMarkerFill.Color; } } dgv.Invalidate(); } } btnApply.Enabled = true; DrawPreview(); } /// <summary> /// Loads the values of the class instance to the controls /// </summary> private void Options2GUI() { _noEvents = true; // vertices chkVerticesVisible.Checked = _options.VerticesVisible; chkVerticesFillVisible.Checked = _options.VerticesFillVisible; udVerticesSize.SetValue(_options.VerticesSize); clpVerticesColor.Color = Colors.UintToColor(_options.VerticesColor); cboVerticesType.SelectedIndex = (int)_options.VerticesType; // transparency if (_options.LinePattern != null) { transparencyControl1.Value = _options.LinePattern.Transparency; } if (dgv.SelectedRows.Count > 0) { int index = dgv.SelectedRows[0].Index; MapWinGIS.LineSegment line = _options.LinePattern.get_Line(index); if (line != null) { cboLineType.SelectedIndex = (int)line.LineType; groupLine.Visible = false; groupMarker.Visible = false; if (cboLineType.SelectedIndex == 0) { groupLine.Visible = true; } else { groupMarker.Visible = true; } // showing the options if (line.LineType == tkLineType.lltSimple) { _noEvents = true; icbLineType.SelectedIndex = (int)line.LineStyle; icbLineWidth.SelectedIndex = (int)line.LineWidth - 1; clpOutline.Color = Colors.UintToColor(line.Color); _noEvents = false; } else { _noEvents = true; pointSymbolControl1.SelectedIndex = (int)line.Marker; udMarkerInterval.SetValue(line.MarkerInterval); udMarkerSize.SetValue(line.MarkerSize); clpMarkerFill.Color = Colors.UintToColor(line.Color); clpMarkerOutline.Color = Colors.UintToColor(line.MarkerOutlineColor); udMarkerOffset.SetValue(line.MarkerOffset); cboOrientation.SelectedIndex = (int)line.MarkerOrientation; if (pointSymbolControl1.ForeColor != clpMarkerFill.Color) { pointSymbolControl1.ForeColor = clpMarkerFill.Color; } _noEvents = false; } DrawPreview(); } } _noEvents = false; } #endregion #region Drawing /// <summary> /// Draws preview based on the chosen options /// </summary> private void DrawPreview() { if (_noEvents) return; if (pctPreview.Image != null) { pctPreview.Image.Dispose(); } Rectangle rect = pctPreview.ClientRectangle; Bitmap bmp = new Bitmap(rect.Width, rect.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(bmp); IntPtr ptr = g.GetHdc(); uint backColor = Colors.ColorToUInteger(this.BackColor); _options.LinePattern.Draw(ptr, 20, 0, rect.Width - 40, rect.Height, backColor); g.ReleaseHdc(); //bmp.MakeTransparent(Color.White); pctPreview.Image = bmp; } #endregion #region User input // Toggle between simaple and marker line void cboLineType_SelectedIndexChanged(object sender, EventArgs e) { if (_noEvents) return; if (dgv.SelectedRows.Count > 0) { int index = dgv.SelectedRows[0].Index; MapWinGIS.LineSegment line = _options.LinePattern.get_Line(index); line.LineType = (tkLineType)cboLineType.SelectedIndex; dgv[CMN_TYPE, index].Value = line.LineType == tkLineType.lltSimple ? "line" : "marker"; Options2GUI(); dgv.Invalidate(); btnApply.Enabled = true; } } #endregion #region Grid /// <summary> /// Drawing of images in the style column /// </summary> private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (_options.LinePattern == null) { return; } if (e.RowIndex >= 0 && e.RowIndex < _options.LinePattern.Count) { if (e.ColumnIndex == CMN_PICTURE) { System.Drawing.Image img = e.Value as System.Drawing.Image; if (img != null) { MapWinGIS.LineSegment line = _options.LinePattern.get_Line(e.RowIndex); if (line != null) { Graphics g = Graphics.FromImage(img); g.Clear(Color.White); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; IntPtr ptr = g.GetHdc(); uint backColor = Colors.ColorToUInteger(this.BackColor); line.Draw(ptr, 0, 0, img.Width, img.Height, backColor); g.ReleaseHdc(); g.Dispose(); ((Bitmap)img).MakeTransparent(this.BackColor); } } } } } /// <summary> /// Shows the options of the curently selected line /// </summary> private void dgv_SelectionChanged(object sender, EventArgs e) { Options2GUI(); RefreshControlState(); } #endregion #region Managing lines /// <summary> /// Adds a line to the pattern /// </summary> private void btnAdd_Click(object sender, EventArgs e) { if (_options.LinePattern == null) { _options.LinePattern = new LinePattern(); } if (cboLineType.SelectedIndex == (int)tkLineType.lltSimple) { _options.LinePattern.AddLine(Colors.ColorToUInteger(Color.Black), 1.0f, tkDashStyle.dsSolid); } else { LineSegment segment = _options.LinePattern.AddMarker(tkDefaultPointSymbol.dpsCircle); } Options2Grid(); //GUI2Options(null, null); DrawPreview(); // selecting the added line _noEvents = true; dgv.ClearSelection(); _noEvents = false; int index = dgv.Rows.Count - 1; dgv.Rows[index].Selected = true; btnApply.Enabled = true; RefreshControlState(); } /// <summary> /// Removes the current line. It's impossible to remove the last line /// </summary> private void btnRemove_Click(object sender, EventArgs e) { if (dgv.SelectedRows.Count > 0 && dgv.Rows.Count > 1) { int index = dgv.SelectedRows[0].Index; _options.LinePattern.RemoveItem(index); Options2Grid(); //GUI2Options(null, null); DrawPreview(); // restoring selection _noEvents = true; dgv.ClearSelection(); _noEvents = false; if (index >= dgv.Rows.Count ) index--; dgv.Rows[index].Selected = true; btnApply.Enabled = true; RefreshControlState(); } } /// <summary> /// Moves the selected line to the top of the pattern /// </summary> private void btnMoveUp_Click(object sender, EventArgs e) { if (dgv.SelectedRows.Count > 0) { int index = dgv.SelectedRows[0].Index; if (index > 0) { MapWinGIS.LineSegment segm = _options.LinePattern.get_Line(index); MapWinGIS.LineSegment segmBefore = _options.LinePattern.get_Line(index - 1); _options.LinePattern.set_Line(index - 1, segm); _options.LinePattern.set_Line(index, segmBefore); Options2Grid(); DrawPreview(); _noEvents = true; dgv.ClearSelection(); _noEvents = false; dgv.Rows[index - 1].Selected = true; btnApply.Enabled = true; RefreshControlState(); } } } /// <summary> /// Moves the selected line to the bottom of the pattern /// </summary> private void btnMoveDown_Click(object sender, EventArgs e) { if (dgv.SelectedRows.Count > 0) { int index = dgv.SelectedRows[0].Index; if (index < dgv.Rows.Count - 1) { MapWinGIS.LineSegment segm = _options.LinePattern.get_Line(index); MapWinGIS.LineSegment segmAfter = _options.LinePattern.get_Line(index + 1); _options.LinePattern.set_Line(index + 1, segm); _options.LinePattern.set_Line(index, segmAfter); Options2Grid(); DrawPreview(); _noEvents = true; dgv.ClearSelection(); _noEvents = false; dgv.Rows[index + 1].Selected = true; btnApply.Enabled = true; RefreshControlState(); } } } /// <summary> /// Chnages the marker for the current line /// </summary> private void pointSymbolControl1_SelectionChanged() { GUI2Options(null, null); } #endregion /// <summary> /// Preserving the selected index /// </summary> private void btnOk_Click(object sender, EventArgs e) { ApplyPattern(); if (_initState != _options.Serialize()) { m_legend.FireLayerPropertiesChanged(m_layer.Handle); m_legend.RedrawLegendAndMap(); } _tabIndex = tabControl1.SelectedIndex; // saves options for default loading behavior //SymbologyPlugin.SaveLayerOptions(_layerHandle); linePatternControl1.SaveToXML(); } private void transparencyControl1_ValueChanged(object sender, byte value) { GUI2Options(null, null); } /// <summary> /// Updates map and saves the changes without closing the window /// </summary> private void btnApply_Click(object sender, EventArgs e) { ApplyPattern(); if (m_legend != null) { m_legend.RedrawLegendAndMap(); m_legend.FireLayerPropertiesChanged(m_layer.Handle); } _initState = _options.Serialize(); btnApply.Enabled = false; } /// <summary> /// Reverts the changes if cancel was selected /// </summary> private void frmLines_FormClosing(object sender, FormClosingEventArgs e) { _tabIndex = tabControl1.SelectedIndex; if (this.DialogResult == DialogResult.Cancel) { _options.Deserialize(_initState); } } #region Synchronization /// <summary> /// Returns true if the current line should be represented by the line pattern /// </summary> private bool CanUseLinePattern() { if (_options.LinePattern != null) { if (_options.LinePattern.Count > 0) { return _options.LinePattern.Count > 1 || (_options.LinePattern.Count == 1 && _options.LinePattern.get_Line(0).LineType == tkLineType.lltMarker); } } return false; } /// <summary> /// Fills grid using ShapeDrawingOptions /// </summary> private void Options2Grid() { dgv.Rows.Clear(); if (CanUseLinePattern()) { dgv.Rows.Add(_options.LinePattern.Count); for (int i = 0; i < _options.LinePattern.Count; i++) { dgv[CMN_TYPE, i].Value = _options.LinePattern.get_Line(i).LineType == tkLineType.lltSimple ? "line" : "marker"; Bitmap bmp = new Bitmap(60, 14); dgv[CMN_PICTURE, i].Value = bmp; } _options.UseLinePattern = true; } else { // a single line dgv.Rows.Add(1); dgv[CMN_TYPE, 0].Value = "line"; Bitmap bmp = new Bitmap(60, 14); dgv[CMN_PICTURE, 0].Value = bmp; _options.UseLinePattern = false; } } #endregion /// <summary> /// Chooses in which form to draw line, as common line or pattern /// </summary> void ApplyPattern() { if (_options.LinePattern == null) { // using line settings _options.UseLinePattern = false; } else if (_options.LinePattern.Count == 1 && _options.LinePattern.get_Line(0).LineType == tkLineType.lltSimple) { // the pattern can be represented as a single line // we need to copy the options only, as all settings were set to pattern ILineSegment line = _options.LinePattern.get_Line(0); if (line != null) { _options.LineStipple = line.LineStyle; _options.LineWidth = line.LineWidth; _options.LineColor = line.Color; } _options.UseLinePattern = false; } else { // line pattern _options.UseLinePattern = true; } } #region Line pattern styles /// <summary> /// Handles the change of the style (style is displayed in preview) /// </summary> private void linePatternControl1_SelectionChanged() { if (_noEvents) return; MapWinGIS.LinePattern pattern = linePatternControl1.SelectedPattern; if (pattern != null) { string s = pattern.Serialize(); _options.LinePattern = new LinePattern(); _options.LinePattern.Deserialize(s); this.ApplyPattern(); Options2Grid(); Options2GUI(); btnApply.Enabled = true; } } /// <summary> /// Adds current options as a style to the list /// </summary> private void btnAddStyle_Click(object sender, EventArgs e) { MapWinGIS.LinePattern pattern = new LinePattern(); this.ApplyPattern(); if (_options.UseLinePattern && _options.LinePattern != null) { string s = _options.LinePattern.Serialize(); pattern.Deserialize(s); } else { // there is no actual patter, a single line only; // pattern object should be created on the fly pattern.AddLine(_options.LineColor, _options.LineWidth, _options.LineStipple); } linePatternControl1.AddPattern(pattern); } /// <summary> /// Removes selected style from the list /// </summary> private void btnRemoveStyle_Click(object sender, EventArgs e) { linePatternControl1.RemovePattern(linePatternControl1.SelectedIndex); } /// <summary> /// Tests ssaving. Temporary /// </summary> private void btnSaveStyles_Click(object sender, EventArgs e) { linePatternControl1.SaveToXML(); } /// <summary> /// Tests loading. Temporary /// </summary> private void btnLoadStyles_Click(object sender, EventArgs e) { linePatternControl1.LoadFromXML(); } #endregion } }
36.558946
132
0.498767
[ "MPL-2.0" ]
nextfullstorm/MapWinGIS
demo/MWLite.Symbology/Forms/Symbology/LinesForm.cs
26,361
C#
using NServiceBus; namespace Messages { public class OrderCreated : IEvent { public string OrderId { get; set; } } }
15.333333
43
0.630435
[ "Apache-2.0" ]
SzymonPobiega/EventDrivenServices
src/Blue.AggregateChains/Messages/OrderCreated.cs
140
C#
using System; namespace ForkHttpListener { public sealed class HttpListenerRequestEventArgs : EventArgs { internal HttpListenerRequestEventArgs(HttpListenerRequest request, HttpListenerResponse response) { Request = request; Response = response; } /// <summary> /// Gets the Request. /// </summary> public HttpListenerRequest Request { get; private set; } /// <summary> /// Gets the Response. /// </summary> public HttpListenerResponse Response { get; private set; } } }
25.956522
105
0.60134
[ "MIT" ]
codeyu/WebServer
src/ForkHttpListener/HttpListenerRequestEventArgs.cs
597
C#
using System; using System.ComponentModel; using RectangleF = CoreGraphics.CGRect; using SizeF = CoreGraphics.CGSize; using Foundation; using System.Collections.Generic; using CoreGraphics; using System.Diagnostics; #if __MOBILE__ using UIKit; using NativeLabel = UIKit.UILabel; #else using AppKit; using NativeLabel = AppKit.NSTextField; #endif #if __MOBILE__ namespace Xamarin.Forms.Platform.iOS #else namespace Xamarin.Forms.Platform.MacOS #endif { public class LabelRenderer : ViewRenderer<Label, NativeLabel> { SizeRequest _perfectSize; bool _perfectSizeValid; FormattedString _formatted; bool IsTextFormatted => _formatted != null; static HashSet<string> s_perfectSizeSet = new HashSet<string> { Label.TextProperty.PropertyName, Label.TextColorProperty.PropertyName, Label.FontProperty.PropertyName, Label.FormattedTextProperty.PropertyName, Label.LineBreakModeProperty.PropertyName, Label.LineHeightProperty.PropertyName, Label.PaddingProperty.PropertyName, Label.TextTypeProperty.PropertyName }; [Internals.Preserve(Conditional = true)] public LabelRenderer() { } public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint) { if (!_perfectSizeValid) { _perfectSize = base.GetDesiredSize(double.PositiveInfinity, double.PositiveInfinity); _perfectSize.Minimum = new Size(Math.Min(10, _perfectSize.Request.Width), _perfectSize.Request.Height); _perfectSizeValid = true; } var widthFits = widthConstraint >= _perfectSize.Request.Width; var heightFits = heightConstraint >= _perfectSize.Request.Height; if (widthFits && heightFits) return _perfectSize; var result = base.GetDesiredSize(widthConstraint, heightConstraint); var tinyWidth = Math.Min(10, result.Request.Width); result.Minimum = new Size(tinyWidth, result.Request.Height); if (widthFits || Element.LineBreakMode == LineBreakMode.NoWrap) return result; bool containerIsNotInfinitelyWide = !double.IsInfinity(widthConstraint); if (containerIsNotInfinitelyWide) { bool textCouldHaveWrapped = Element.LineBreakMode == LineBreakMode.WordWrap || Element.LineBreakMode == LineBreakMode.CharacterWrap; bool textExceedsContainer = result.Request.Width > widthConstraint; if (textExceedsContainer || textCouldHaveWrapped) { var expandedWidth = Math.Max(tinyWidth, widthConstraint); result.Request = new Size(expandedWidth, result.Request.Height); } } return result; } #if __MOBILE__ public override void LayoutSubviews() { base.LayoutSubviews(); #else public override void Layout() { base.Layout(); #endif if (Control == null) return; SizeF fitSize; nfloat labelHeight; switch (Element.VerticalTextAlignment) { case TextAlignment.Start: fitSize = Control.SizeThatFits(Element.Bounds.Size.ToSizeF()); labelHeight = (nfloat)Math.Min(Bounds.Height, fitSize.Height); Control.Frame = new RectangleF(0, 0, (nfloat)Element.Width, labelHeight); break; case TextAlignment.Center: #if __MOBILE__ Control.Frame = new RectangleF(0, 0, (nfloat)Element.Width, (nfloat)Element.Height); #else fitSize = Control.SizeThatFits(Element.Bounds.Size.ToSizeF()); labelHeight = (nfloat)Math.Min(Bounds.Height, fitSize.Height); var yOffset = (int)(Element.Height / 2 - labelHeight / 2); Control.Frame = new RectangleF(0, 0, (nfloat)Element.Width, (nfloat)Element.Height - yOffset); #endif break; case TextAlignment.End: fitSize = Control.SizeThatFits(Element.Bounds.Size.ToSizeF()); labelHeight = (nfloat)Math.Min(Bounds.Height, fitSize.Height); #if __MOBILE__ nfloat yOffset = 0; yOffset = (nfloat)(Element.Height - labelHeight); Control.Frame = new RectangleF(0, yOffset, (nfloat)Element.Width, labelHeight); #else Control.Frame = new RectangleF(0, 0, (nfloat)Element.Width, labelHeight); #endif break; } Control.RecalculateSpanPositions(Element); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (Element != null) { Element.PropertyChanging -= ElementPropertyChanging; } } } protected override void OnElementChanged(ElementChangedEventArgs<Label> e) { _perfectSizeValid = false; if (e.OldElement != null) { e.OldElement.PropertyChanging -= ElementPropertyChanging; } if (e.NewElement != null) { e.NewElement.PropertyChanging += ElementPropertyChanging; if (Control == null) { SetNativeControl(CreateNativeControl()); #if !__MOBILE__ Control.Editable = false; Control.Bezeled = false; Control.DrawsBackground = false; #endif } UpdateLineBreakMode(); UpdateText(); UpdateTextDecorations(); UpdateTextColor(); UpdateFont(); UpdateMaxLines(); UpdateCharacterSpacing(); UpdatePadding(); UpdateHorizontalTextAlignment(); } base.OnElementChanged(e); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == Label.HorizontalTextAlignmentProperty.PropertyName) UpdateHorizontalTextAlignment(); else if (e.PropertyName == Label.VerticalTextAlignmentProperty.PropertyName) UpdateLayout(); else if (e.PropertyName == Label.TextColorProperty.PropertyName) UpdateTextColor(); else if (e.PropertyName == Label.FontProperty.PropertyName) UpdateFont(); else if (e.PropertyName == Label.TextProperty.PropertyName) { UpdateText(); UpdateTextColor(); UpdateTextDecorations(); UpdateCharacterSpacing(); } else if (e.PropertyName == Label.CharacterSpacingProperty.PropertyName) UpdateCharacterSpacing(); else if (e.PropertyName == Label.TextDecorationsProperty.PropertyName) UpdateTextDecorations(); else if (e.PropertyName == Label.FormattedTextProperty.PropertyName) { UpdateText(); UpdateTextDecorations(); } else if (e.PropertyName == Label.LineBreakModeProperty.PropertyName) UpdateLineBreakMode(); else if (e.PropertyName == VisualElement.FlowDirectionProperty.PropertyName) UpdateHorizontalTextAlignment(); else if (e.PropertyName == Label.LineHeightProperty.PropertyName) UpdateText(); else if (e.PropertyName == Label.MaxLinesProperty.PropertyName) UpdateMaxLines(); else if (e.PropertyName == Label.PaddingProperty.PropertyName) UpdatePadding(); else if (e.PropertyName == Label.TextTypeProperty.PropertyName) UpdateText(); else if (e.PropertyName == Label.TextTransformProperty.PropertyName) UpdateText(); } protected override NativeLabel CreateNativeControl() { #if __MOBILE__ return Element.Padding.IsEmpty ? new NativeLabel(RectangleF.Empty) : new FormsLabel(RectangleF.Empty); #else return new NativeLabel(RectangleF.Empty); #endif } void ElementPropertyChanging(object sender, PropertyChangingEventArgs e) { if (s_perfectSizeSet.Contains(e.PropertyName)) _perfectSizeValid = false; } void UpdateTextDecorations() { if (IsElementOrControlEmpty) return; if (Element?.TextType != TextType.Text) return; #if __MOBILE__ if (!(Control.AttributedText?.Length > 0)) return; #else if (!(Control.AttributedStringValue?.Length > 0)) return; #endif var textDecorations = Element.TextDecorations; #if __MOBILE__ var newAttributedText = new NSMutableAttributedString(Control.AttributedText); var strikeThroughStyleKey = UIStringAttributeKey.StrikethroughStyle; var underlineStyleKey = UIStringAttributeKey.UnderlineStyle; #else var newAttributedText = new NSMutableAttributedString(Control.AttributedStringValue); var strikeThroughStyleKey = NSStringAttributeKey.StrikethroughStyle; var underlineStyleKey = NSStringAttributeKey.UnderlineStyle; #endif var range = new NSRange(0, newAttributedText.Length); if ((textDecorations & TextDecorations.Strikethrough) == 0) newAttributedText.RemoveAttribute(strikeThroughStyleKey, range); else newAttributedText.AddAttribute(strikeThroughStyleKey, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range); if ((textDecorations & TextDecorations.Underline) == 0) newAttributedText.RemoveAttribute(underlineStyleKey, range); else newAttributedText.AddAttribute(underlineStyleKey, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range); #if __MOBILE__ Control.AttributedText = newAttributedText; #else Control.AttributedStringValue = newAttributedText; #endif UpdateCharacterSpacing(); _perfectSizeValid = false; } #if __MOBILE__ protected override void SetAccessibilityLabel() { // If we have not specified an AccessibilityLabel and the AccessibiltyLabel is current bound to the Text, // exit this method so we don't set the AccessibilityLabel value and break the binding. // This may pose a problem for users who want to explicitly set the AccessibilityLabel to null, but this // will prevent us from inadvertently breaking UI Tests that are using Query.Marked to get the dynamic Text // of the Label. var elemValue = (string)Element?.GetValue(AutomationProperties.NameProperty); if (string.IsNullOrWhiteSpace(elemValue) && Control?.AccessibilityLabel == Control?.Text) return; base.SetAccessibilityLabel(); } #endif protected override void SetBackgroundColor(Color color) { #if __MOBILE__ if (color == Color.Default) BackgroundColor = UIColor.Clear; else BackgroundColor = color.ToUIColor(); #else if (color == Color.Default) Layer.BackgroundColor = NSColor.Clear.CGColor; else Layer.BackgroundColor = color.ToCGColor(); #endif } protected override void SetBackground(Brush brush) { var backgroundLayer = this.GetBackgroundLayer(brush); if (backgroundLayer != null) { #if __MOBILE__ Layer.BackgroundColor = UIColor.Clear.CGColor; #endif Layer.InsertBackgroundLayer(backgroundLayer, 0); } else Layer.RemoveBackgroundLayer(); } void UpdateHorizontalTextAlignment() { #if __MOBILE__ Control.TextAlignment = Element.HorizontalTextAlignment.ToNativeTextAlignment(((IVisualElementController)Element).EffectiveFlowDirection); #else Control.Alignment = Element.HorizontalTextAlignment.ToNativeTextAlignment(((IVisualElementController)Element).EffectiveFlowDirection); #endif } void UpdateLineBreakMode() { #if __MOBILE__ switch (Element.LineBreakMode) { case LineBreakMode.NoWrap: Control.LineBreakMode = UILineBreakMode.Clip; break; case LineBreakMode.WordWrap: Control.LineBreakMode = UILineBreakMode.WordWrap; break; case LineBreakMode.CharacterWrap: Control.LineBreakMode = UILineBreakMode.CharacterWrap; break; case LineBreakMode.HeadTruncation: Control.LineBreakMode = UILineBreakMode.HeadTruncation; break; case LineBreakMode.MiddleTruncation: Control.LineBreakMode = UILineBreakMode.MiddleTruncation; break; case LineBreakMode.TailTruncation: Control.LineBreakMode = UILineBreakMode.TailTruncation; break; } #else switch (Element.LineBreakMode) { case LineBreakMode.NoWrap: Control.LineBreakMode = NSLineBreakMode.Clipping; break; case LineBreakMode.WordWrap: Control.LineBreakMode = NSLineBreakMode.ByWordWrapping; break; case LineBreakMode.CharacterWrap: Control.LineBreakMode = NSLineBreakMode.CharWrapping; break; case LineBreakMode.HeadTruncation: Control.LineBreakMode = NSLineBreakMode.TruncatingHead; break; case LineBreakMode.MiddleTruncation: Control.LineBreakMode = NSLineBreakMode.TruncatingMiddle; break; case LineBreakMode.TailTruncation: Control.LineBreakMode = NSLineBreakMode.TruncatingTail; break; } #endif } void UpdateCharacterSpacing() { if (IsElementOrControlEmpty) return; if (Element?.TextType != TextType.Text) return; #if __MOBILE__ var textAttr = Control.AttributedText.AddCharacterSpacing(Element.Text, Element.CharacterSpacing); if (textAttr != null) Control.AttributedText = textAttr; #else var textAttr = Control.AttributedStringValue.AddCharacterSpacing(Element.Text, Element.CharacterSpacing); if (textAttr != null) Control.AttributedStringValue = textAttr; #endif _perfectSizeValid = false; } void UpdateText() { if (IsElementOrControlEmpty) return; switch (Element.TextType) { case TextType.Html: UpdateTextHtml(); break; default: UpdateTextPlainText(); break; } } void UpdateTextPlainText() { _formatted = Element.FormattedText; if (_formatted == null && Element.LineHeight >= 0) _formatted = Element.Text; if (IsTextFormatted) { UpdateFormattedText(); } else { var text = Element.UpdateFormsText(Element.Text, Element.TextTransform); #if __MOBILE__ Control.Text = text; #else Control.StringValue = text ?? ""; #endif } UpdateLayout(); } void UpdateFormattedText() { #if __MOBILE__ Control.AttributedText = _formatted.ToAttributed(Element, Element.TextColor, Element.HorizontalTextAlignment, Element.LineHeight); #else Control.AttributedStringValue = _formatted.ToAttributed(Element, Element.TextColor, Element.HorizontalTextAlignment, Element.LineHeight); #endif _perfectSizeValid = false; UpdateHorizontalTextAlignment(); UpdateLineBreakMode(); } void UpdateTextHtml() { if (IsElementOrControlEmpty) return; string text = Element.Text ?? string.Empty; var attr = GetNSAttributedStringDocumentAttributes(); #if __MOBILE__ NSError nsError = null; Control.AttributedText = new NSAttributedString(text, attr, ref nsError); #else var htmlData = new NSMutableData(); htmlData.SetData(text); Control.AttributedStringValue = new NSAttributedString(htmlData, attr, out _); #endif _perfectSizeValid = false; // Setting AttributedText will reset style-related properties, so we'll need to update them again UpdateTextColor(); UpdateFont(); } protected virtual NSAttributedStringDocumentAttributes GetNSAttributedStringDocumentAttributes() { return new NSAttributedStringDocumentAttributes { DocumentType = NSDocumentType.HTML, StringEncoding = NSStringEncoding.UTF8 }; } static bool FontIsDefault(Label label) { if (label.IsSet(Label.FontAttributesProperty)) { return false; } if (label.IsSet(Label.FontFamilyProperty)) { return false; } if (label.IsSet(Label.FontSizeProperty)) { return false; } return true; } void UpdateFont() { if(Element == null) { return; } if (IsTextFormatted) { UpdateFormattedText(); return; } if (Element.TextType == TextType.Html && FontIsDefault(Element)) { // If no explicit font properties have been specified and we're display HTML, // let the HTML determine the typeface return; } #if __MOBILE__ Control.Font = Element.ToUIFont(); #else Control.Font = Element.ToNSFont(); #endif UpdateLayout(); } void UpdateTextColor() { if (IsTextFormatted) { UpdateFormattedText(); return; } var textColor = (Color)Element.GetValue(Label.TextColorProperty); if (textColor.IsDefault && Element.TextType == TextType.Html) { // If no explicit text color has been specified and we're displaying HTML, // let the HTML determine the colors return; } // default value of color documented to be black in iOS docs #if __MOBILE__ Control.TextColor = textColor.ToUIColor(ColorExtensions.LabelColor); #else var alignment = Element.HorizontalTextAlignment.ToNativeTextAlignment(((IVisualElementController)Element).EffectiveFlowDirection); var textWithColor = new NSAttributedString(Element.Text ?? "", font: Element.ToNSFont(), foregroundColor: textColor.ToNSColor(ColorExtensions.TextColor), paragraphStyle: new NSMutableParagraphStyle() { Alignment = alignment }); textWithColor = textWithColor.AddCharacterSpacing(Element.Text ?? string.Empty, Element.CharacterSpacing); Control.AttributedStringValue = textWithColor; #endif UpdateLayout(); } void UpdateLayout() { #if __MOBILE__ LayoutSubviews(); #else Layout(); #endif } void UpdateMaxLines() { if (Element.MaxLines >= 0) { #if __MOBILE__ Control.Lines = Element.MaxLines; LayoutSubviews(); #else Control.MaximumNumberOfLines = Element.MaxLines; Layout(); #endif } else { #if __MOBILE__ switch (Element.LineBreakMode) { case LineBreakMode.WordWrap: case LineBreakMode.CharacterWrap: Control.Lines = 0; break; case LineBreakMode.NoWrap: case LineBreakMode.HeadTruncation: case LineBreakMode.MiddleTruncation: case LineBreakMode.TailTruncation: Control.Lines = 1; break; } LayoutSubviews(); #else switch (Element.LineBreakMode) { case LineBreakMode.WordWrap: case LineBreakMode.CharacterWrap: Control.MaximumNumberOfLines = 0; break; case LineBreakMode.NoWrap: case LineBreakMode.HeadTruncation: case LineBreakMode.MiddleTruncation: case LineBreakMode.TailTruncation: Control.MaximumNumberOfLines = 1; break; } Layout(); #endif } } void UpdatePadding() { if (IsElementOrControlEmpty) return; if (Element.Padding.IsEmpty) return; #if __MOBILE__ var formsLabel = Control as FormsLabel; if (formsLabel == null) { Debug.WriteLine($"{nameof(LabelRenderer)}: On iOS, a Label created with no padding will ignore padding changes"); return; } formsLabel.TextInsets = new UIEdgeInsets( (float)Element.Padding.Top, (float)Element.Padding.Left, (float)Element.Padding.Bottom, (float)Element.Padding.Right); UpdateLayout(); #endif } #if __MOBILE__ class FormsLabel : NativeLabel { public UIEdgeInsets TextInsets { get; set; } public FormsLabel(RectangleF frame) : base(frame) { } public override void DrawText(RectangleF rect) => base.DrawText(TextInsets.InsetRect(rect)); public override SizeF SizeThatFits(SizeF size) => AddInsets(base.SizeThatFits(size)); SizeF AddInsets(SizeF size) => new SizeF( width: size.Width + TextInsets.Left + TextInsets.Right, height: size.Height + TextInsets.Top + TextInsets.Bottom); } #endif } }
26.785303
230
0.725859
[ "MIT" ]
PavanKumarGithub/Xamarin.Forms
Xamarin.Forms.Platform.iOS/Renderers/LabelRenderer.cs
18,589
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AkCodeWorkSpaceCreator.Settings { internal class AkTerminalCustomizations { public AkTerminalCustomizations(Dictionary<string, object> settings) { var innerData = new Dictionary<string, object>(); var innerData2 = new Dictionary<string, object>(); settings["terminal.integrated.profiles.windows"] = innerData; innerData["PowerShell"] = innerData2; var innerList = new List<string>(); innerData2["path"] = innerList; innerList.Add(@"C:\Program Files\PowerShell\7\pwsh.exe"); innerData["icon"] = "terminal-powershell"; // "terminal.integrated.profiles.windows": { // "PowerShell": { // "path": [ // "C:\\Program Files\\PowerShell\\7\\pwsh.exe" // ], //"icon": "terminal-powershell" // }, } } }
32.029412
76
0.557392
[ "MIT" ]
sr2200/AkCodeWorkSpaceCreator
src/AkCodeWorkSpaceCreator/Settings/AkTerminalCustomizations.cs
1,091
C#
#region License // Copyright (c) 2011, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This software is licensed under the Open Software License v3.0. // For the complete license, see http://www.clearcanvas.ca/OSLv3.0 #endregion using System.Drawing; namespace ClearCanvas.ImageViewer.Imaging { /// <summary> /// The default (grayscale) color map. /// </summary> internal sealed class GrayscaleColorMapFactory : ColorMapFactoryBase<GrayscaleColorMap> { /// <summary> /// Returns the factory name. /// </summary> public static readonly string FactoryName = "Grayscale"; /// <summary> /// Default Constructor. /// </summary> public GrayscaleColorMapFactory() { } /// <summary> /// Returns the Name of the factory. /// </summary> public override string Name { get { return FactoryName; } } /// <summary> /// Returns a brief description of the Factory. /// </summary> public override string Description { get { return SR.DescriptionGrayscaleColorMap; } } } /// <summary> /// A Grayscale Color Map. /// </summary> /// <remarks> /// This class should not be instantiated directly, but through the corresponding factory. /// </remarks> internal class GrayscaleColorMap : ColorMap { /// <summary> /// Default Constructor. /// </summary> public GrayscaleColorMap() : base() { } /// <summary> /// Generates the Lut. /// </summary> protected override void Create() { Color color; int j = 0; int maxGrayLevel = this.Length - 1; int min = MinInputValue; int max = MaxInputValue; for (int i = min; i <= max; i++) { float scale = j / (float)maxGrayLevel; j++; int value = (int)(byte.MaxValue * scale); color = Color.FromArgb(255, value, value, value); this[i] = color.ToArgb(); } } /// <summary> /// Returns an abbreviated description of the Lut. /// </summary> public override string GetDescription() { return SR.DescriptionGrayscaleColorMap; } } }
21.876289
92
0.617342
[ "Apache-2.0" ]
SNBnani/Xian
ImageViewer/Imaging/StandardColorMaps.cs
2,122
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class GeneratorDriverTests : CSharpTestBase { [Fact] public void Running_With_No_Changes_Is_NoOp() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Empty(diagnostics); Assert.Single(outputCompilation.SyntaxTrees); Assert.Equal(compilation, outputCompilation); } [Fact] public void Generator_Is_Initialized_Before_Running() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Equal(1, initCount); Assert.Equal(1, executeCount); } [Fact] public void Generator_Is_Not_Initialized_If_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); Assert.Equal(0, initCount); Assert.Equal(0, executeCount); } [Fact] public void Generator_Is_Only_Initialized_Once() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++, source: "public class C { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); driver = driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _); driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _); Assert.Equal(1, initCount); Assert.Equal(3, executeCount); } [Fact] public void Single_File_Is_Added() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); Assert.NotEqual(compilation, outputCompilation); var generatedClass = outputCompilation.GlobalNamespace.GetTypeMembers("GeneratedClass").Single(); Assert.True(generatedClass.Locations.Single().IsInSource); } [Fact] public void Analyzer_Is_Run() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; var analyzer = new Analyzer_Is_Run_Analyzer(); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); compilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.GeneratedClassCount); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.GeneratedClassCount); } private class Analyzer_Is_Run_Analyzer : DiagnosticAnalyzer { public int GeneratedClassCount; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "GeneratedClass": Interlocked.Increment(ref GeneratedClassCount); break; case "C": case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void Single_File_Is_Added_OnlyOnce_For_Multiple_Calls() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation1, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation2, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation3, out _); Assert.Equal(2, outputCompilation1.SyntaxTrees.Count()); Assert.Equal(2, outputCompilation2.SyntaxTrees.Count()); Assert.Equal(2, outputCompilation3.SyntaxTrees.Count()); Assert.NotEqual(compilation, outputCompilation1); Assert.NotEqual(compilation, outputCompilation2); Assert.NotEqual(compilation, outputCompilation3); } [Fact] public void User_Source_Can_Depend_On_Generated_Source() { var source = @" #pragma warning disable CS0649 class C { public D d; } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); } [Fact] public void TryApply_Edits_Fails_If_FullGeneration_Has_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); AdditionalFileAddedGenerator testGenerator = new AdditionalFileAddedGenerator() { CanApplyChanges = false }; GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); // try apply edits should fail if we've not run a full compilation yet driver = driver.TryApplyEdits(compilation, out var outputCompilation, out var succeeded); Assert.False(succeeded); Assert.Equal(compilation, outputCompilation); } [Fact] public void TryApply_Edits_Does_Nothing_When_Nothing_Pending() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); AdditionalFileAddedGenerator testGenerator = new AdditionalFileAddedGenerator(); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); // run an initial generation pass driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Single(outputCompilation.SyntaxTrees); // now try apply edits (which should succeed, but do nothing) driver = driver.TryApplyEdits(compilation, out var editedCompilation, out var succeeded); Assert.True(succeeded); Assert.Equal(outputCompilation, editedCompilation); } [Fact] public void Failed_Edit_Does_Not_Change_Compilation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); AdditionalFileAddedGenerator testGenerator = new AdditionalFileAddedGenerator() { CanApplyChanges = false }; GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Single(outputCompilation.SyntaxTrees); // create an edit AdditionalFileAddedEdit edit = new AdditionalFileAddedEdit(new InMemoryAdditionalText("a\\file2.cs", "")); driver = driver.WithPendingEdits(ImmutableArray.Create<PendingEdit>(edit)); // now try apply edits (which will fail) driver = driver.TryApplyEdits(compilation, out var editedCompilation, out var succeeded); Assert.False(succeeded); Assert.Single(editedCompilation.SyntaxTrees); Assert.Equal(compilation, editedCompilation); } [Fact] public void Added_Additional_File() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); AdditionalFileAddedGenerator testGenerator = new AdditionalFileAddedGenerator(); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); // run initial generation pass driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Single(outputCompilation.SyntaxTrees); // create an edit AdditionalFileAddedEdit edit = new AdditionalFileAddedEdit(new InMemoryAdditionalText("a\\file1.cs", "")); driver = driver.WithPendingEdits(ImmutableArray.Create<PendingEdit>(edit)); // now try apply edits driver = driver.TryApplyEdits(compilation, out outputCompilation, out var succeeded); Assert.True(succeeded); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [Fact] public void Multiple_Added_Additional_Files() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); AdditionalFileAddedGenerator testGenerator = new AdditionalFileAddedGenerator(); GeneratorDriver driver = CSharpGeneratorDriver.Create(parseOptions: parseOptions, generators: ImmutableArray.Create<ISourceGenerator>(testGenerator), optionsProvider: CompilerAnalyzerConfigOptionsProvider.Empty, additionalTexts: ImmutableArray.Create<AdditionalText>(new InMemoryAdditionalText("a\\file1.cs", ""))); // run initial generation pass driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); // create an edit AdditionalFileAddedEdit edit = new AdditionalFileAddedEdit(new InMemoryAdditionalText("a\\file2.cs", "")); driver = driver.WithPendingEdits(ImmutableArray.Create<PendingEdit>(edit)); // now try apply edits driver = driver.TryApplyEdits(compilation, out var editedCompilation, out var succeeded); Assert.True(succeeded); Assert.Equal(3, editedCompilation.SyntaxTrees.Count()); // if we run a full compilation again, we should still get 3 syntax trees driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out outputCompilation, out _); Assert.Equal(3, outputCompilation.SyntaxTrees.Count()); // lets add multiple edits driver = driver.WithPendingEdits(ImmutableArray.Create<PendingEdit>(new AdditionalFileAddedEdit(new InMemoryAdditionalText("a\\file3.cs", "")), new AdditionalFileAddedEdit(new InMemoryAdditionalText("a\\file4.cs", "")), new AdditionalFileAddedEdit(new InMemoryAdditionalText("a\\file5.cs", "")))); // now try apply edits driver = driver.TryApplyEdits(compilation, out editedCompilation, out succeeded); Assert.True(succeeded); Assert.Equal(6, editedCompilation.SyntaxTrees.Count()); } [Fact] public void Added_Additional_File_With_Full_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); AdditionalFileAddedGenerator testGenerator = new AdditionalFileAddedGenerator(); var text = new InMemoryAdditionalText("a\\file1.cs", ""); GeneratorDriver driver = CSharpGeneratorDriver.Create(parseOptions: parseOptions, generators: ImmutableArray.Create<ISourceGenerator>(testGenerator), optionsProvider: CompilerAnalyzerConfigOptionsProvider.Empty, additionalTexts: ImmutableArray.Create<AdditionalText>(new InMemoryAdditionalText("a\\file1.cs", ""))); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); // we should have a single extra file for the additional texts Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); // even if we run a full gen, or partial, nothing should change yet driver = driver.TryApplyEdits(outputCompilation, out var editedCompilation, out var succeeded); Assert.True(succeeded); Assert.Equal(2, editedCompilation.SyntaxTrees.Count()); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out outputCompilation, out _); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); // create an edit AdditionalFileAddedEdit edit = new AdditionalFileAddedEdit(new InMemoryAdditionalText("a\\file2.cs", "")); driver = driver.WithPendingEdits(ImmutableArray.Create<PendingEdit>(edit)); // now try apply edits driver = driver.TryApplyEdits(compilation, out editedCompilation, out succeeded); Assert.True(succeeded); Assert.Equal(3, editedCompilation.SyntaxTrees.Count()); // if we run a full compilation again, we should still get 3 syntax trees driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out outputCompilation, out _); Assert.Equal(3, outputCompilation.SyntaxTrees.Count()); } [Fact] public void Edits_Are_Applied_During_Full_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); AdditionalFileAddedGenerator testGenerator = new AdditionalFileAddedGenerator(); var text = new InMemoryAdditionalText("a\\file1.cs", ""); GeneratorDriver driver = CSharpGeneratorDriver.Create(parseOptions: parseOptions, generators: ImmutableArray.Create<ISourceGenerator>(testGenerator), optionsProvider: CompilerAnalyzerConfigOptionsProvider.Empty, additionalTexts: ImmutableArray.Create<AdditionalText>(new InMemoryAdditionalText("a\\file1.cs", ""))); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); // add multiple edits driver = driver.WithPendingEdits(ImmutableArray.Create<PendingEdit>(new AdditionalFileAddedEdit(new InMemoryAdditionalText("a\\file2.cs", "")), new AdditionalFileAddedEdit(new InMemoryAdditionalText("a\\file3.cs", "")), new AdditionalFileAddedEdit(new InMemoryAdditionalText("a\\file4.cs", "")))); // but just do a full generation (don't try apply) driver.RunGeneratorsAndUpdateCompilation(compilation, out outputCompilation, out _); Assert.Equal(5, outputCompilation.SyntaxTrees.Count()); } [Fact] public void Adding_Another_Generator_Makes_TryApplyEdits_Fail() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator1 = new SingleFileTestGenerator("public class D { }"); SingleFileTestGenerator2 testGenerator2 = new SingleFileTestGenerator2("public class E { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(parseOptions: parseOptions, generators: ImmutableArray.Create<ISourceGenerator>(testGenerator1), optionsProvider: CompilerAnalyzerConfigOptionsProvider.Empty, additionalTexts: ImmutableArray<AdditionalText>.Empty); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); // try apply edits driver = driver.TryApplyEdits(compilation, out _, out bool success); Assert.True(success); // add another generator driver = driver.AddGenerators(ImmutableArray.Create<ISourceGenerator>(testGenerator2)); // try apply changes should now fail driver = driver.TryApplyEdits(compilation, out _, out success); Assert.False(success); // full generation driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out outputCompilation, out _); Assert.Equal(3, outputCompilation.SyntaxTrees.Count()); // try apply changes should now succeed driver.TryApplyEdits(compilation, out _, out success); Assert.True(success); } [Fact] public void Error_During_Initialization_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("init error"); var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1) ); } [Fact] public void Error_During_Initialization_Generator_Does_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("init error"); var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }, source: "class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Single(outputCompilation.SyntaxTrees); } [Fact] public void Error_During_Generation_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_Does_Not_Affect_Other_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { }, source: "public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_With_Dependent_Source() { var source = @" #pragma warning disable CS0649 class C { public D d; } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception, source: "public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_Has_Exception_In_Description() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); // Since translated description strings can have punctuation that differs based on locale, simply ensure the // exception message is contains in the diagnostic description. Assert.Contains(exception.ToString(), generatorDiagnostics.Single().Descriptor.Description.ToString()); } [Fact] public void Generator_Can_Report_Diagnostics() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => sgc.ReportDiagnostic(diagnostic)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( Diagnostic("TG001").WithLocation(1, 1) ); } [Fact] public void Generator_HintName_MustBe_Unique() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); // the assert should swallow the exception, so we'll actually successfully generate Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8))); // also throws for <name> vs <name>.cs Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8))); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [Fact] public void Generator_HintName_Is_Appended_With_GeneratorName() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D {}", "source.cs"); var generator2 = new SingleFileTestGenerator2("public class E {}", "source.cs"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); Assert.Equal(3, outputCompilation.SyntaxTrees.Count()); var filePaths = outputCompilation.SyntaxTrees.Skip(1).Select(t => t.FilePath).ToArray(); Assert.Equal(new[] { Path.Combine(generator.GetType().Assembly.GetName().Name!, generator.GetType().FullName!, "source.cs"), Path.Combine(generator2.GetType().Assembly.GetName().Name!, generator2.GetType().FullName!, "source.cs") }, filePaths); } [Fact] public void RunResults_Are_Empty_Before_Generation() { GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: TestOptions.Regular); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Empty(results.Diagnostics); Assert.Empty(results.Results); } [Fact] public void RunResults_Are_Available_After_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Single(results.GeneratedTrees); Assert.Single(results.Results); Assert.Empty(results.Diagnostics); var result = results.Results.Single(); Assert.Null(result.Exception); Assert.Empty(result.Diagnostics); Assert.Single(result.GeneratedSources); Assert.Equal(results.GeneratedTrees.Single(), result.GeneratedSources.Single().SyntaxTree); } [Fact] public void RunResults_Combine_SyntaxTrees() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); sgc.AddSource("test2", SourceText.From("public class E {}", Encoding.UTF8)); }); var generator2 = new SingleFileTestGenerator("public class F{}"); var generator3 = new SingleFileTestGenerator2("public class G{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(4, results.GeneratedTrees.Length); Assert.Equal(3, results.Results.Length); Assert.Empty(results.Diagnostics); var result1 = results.Results[0]; var result2 = results.Results[1]; var result3 = results.Results[2]; Assert.Null(result1.Exception); Assert.Empty(result1.Diagnostics); Assert.Equal(2, result1.GeneratedSources.Length); Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree); Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree); Assert.Null(result2.Exception); Assert.Empty(result2.Diagnostics); Assert.Single(result2.GeneratedSources); Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree); Assert.Null(result3.Exception); Assert.Empty(result3.Diagnostics); Assert.Single(result3.GeneratedSources); Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree); } [Fact] public void RunResults_Combine_Diagnostics() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None); var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None); var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(2, results.Results.Length); Assert.Equal(3, results.Diagnostics.Length); Assert.Empty(results.GeneratedTrees); var result1 = results.Results[0]; var result2 = results.Results[1]; Assert.Null(result1.Exception); Assert.Equal(2, result1.Diagnostics.Length); Assert.Empty(result1.GeneratedSources); Assert.Equal(results.Diagnostics[0], result1.Diagnostics[0]); Assert.Equal(results.Diagnostics[1], result1.Diagnostics[1]); Assert.Null(result2.Exception); Assert.Single(result2.Diagnostics); Assert.Empty(result2.GeneratedSources); Assert.Equal(results.Diagnostics[2], result2.Diagnostics[0]); } [Fact] public void FullGeneration_Diagnostics_AreSame_As_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None); var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None); var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var fullDiagnostics); var results = driver.GetRunResult(); Assert.Equal(3, results.Diagnostics.Length); Assert.Equal(3, fullDiagnostics.Length); AssertEx.Equal(results.Diagnostics, fullDiagnostics); } [Fact] public void Cancellation_During_Initialization_Doesnt_Report_As_Generator_Error() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); var testGenerator = new CallbackGenerator( onInit: (i) => { cts.Cancel(); }, onExecute: (e) => { } ); // test generator cancels the token. Check that the call to this generator doesn't make it look like it errored. var testGenerator2 = new CallbackGenerator2( onInit: (i) => { i.CancellationToken.ThrowIfCancellationRequested(); }, onExecute: (e) => { throw ExceptionUtilities.Unreachable; }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions); var oldDriver = driver; Assert.Throws<OperationCanceledException>(() => driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics, cts.Token) ); Assert.Same(oldDriver, driver); } [Fact] public void Cancellation_During_Execution_Doesnt_Report_As_Generator_Error() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => { cts.Cancel(); } ); // test generator cancels the token. Check that the call to this generator doesn't make it look like it errored. var testGenerator2 = new CallbackGenerator2( onInit: (i) => { }, onExecute: (e) => { e.AddSource("a", SourceText.From("public class E {}", Encoding.UTF8)); e.CancellationToken.ThrowIfCancellationRequested(); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions); var oldDriver = driver; Assert.Throws<OperationCanceledException>(() => driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics, cts.Token) ); Assert.Same(oldDriver, driver); } [ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")] public void Adding_A_Source_Text_Without_Encoding_Fails_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("a", SourceText.From("")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var outputDiagnostics); Assert.Single(outputDiagnostics); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "ArgumentException", "The provided SourceText must have an explicit encoding set. (Parameter 'source')").WithLocation(1, 1) ); } [Fact] public void ParseOptions_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ParseOptions? passedOptions = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => { passedOptions = e.ParseOptions; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Same(parseOptions, passedOptions); } [Fact] public void Generator_Can_Provide_Source_In_PostInit() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [Fact] public void PostInit_Source_Is_Available_During_Execute() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } INamedTypeSymbol? dSymbol = null; var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.NotNull(dSymbol); } [Fact] public void PostInit_Source_Is_Available_To_Other_Generators_During_Execute() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } INamedTypeSymbol? dSymbol = null; var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.NotNull(dSymbol); } [Fact] public void PostInit_Is_Only_Called_Once() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int postInitCount = 0; int executeCount = 0; void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); postInitCount++; } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => executeCount++, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.Equal(1, postInitCount); Assert.Equal(3, executeCount); } [Fact] public void Error_During_PostInit_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); throw new InvalidOperationException("post init error"); } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'post init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "post init error").WithLocation(1, 1) ); } [Fact] public void Error_During_Initialization_PostInit_Does_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void init(GeneratorInitializationContext context) { context.RegisterForPostInitialization(postInit); throw new InvalidOperationException("init error"); } static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); Assert.True(false, "Should not execute"); } var generator = new CallbackGenerator(init, (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1) ); } [Fact] public void PostInit_SyntaxTrees_Are_Available_In_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Single(results.Results); Assert.Empty(results.Diagnostics); var result = results.Results[0]; Assert.Null(result.Exception); Assert.Empty(result.Diagnostics); Assert.Equal(2, result.GeneratedSources.Length); } [Fact] public void PostInit_SyntaxTrees_Are_Combined_In_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}"); var generator2 = new SingleFileTestGenerator("public class F{}"); var generator3 = new SingleFileTestGenerator2("public class G{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(4, results.GeneratedTrees.Length); Assert.Equal(3, results.Results.Length); Assert.Empty(results.Diagnostics); var result1 = results.Results[0]; var result2 = results.Results[1]; var result3 = results.Results[2]; Assert.Null(result1.Exception); Assert.Empty(result1.Diagnostics); Assert.Equal(2, result1.GeneratedSources.Length); Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree); Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree); Assert.Null(result2.Exception); Assert.Empty(result2.Diagnostics); Assert.Single(result2.GeneratedSources); Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree); Assert.Null(result3.Exception); Assert.Empty(result3.Diagnostics); Assert.Single(result3.GeneratedSources); Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree); } [Fact] public void SyntaxTrees_Are_Lazy() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D {}", "source.cs"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); var tree = Assert.Single(results.GeneratedTrees); Assert.False(tree.TryGetRoot(out _)); var rootFromGetRoot = tree.GetRoot(); Assert.NotNull(rootFromGetRoot); Assert.True(tree.TryGetRoot(out var rootFromTryGetRoot)); Assert.Same(rootFromGetRoot, rootFromTryGetRoot); } [Fact] public void Diagnostics_Respect_Suppression() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) => { c.ReportDiagnostic(CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2)); c.ReportDiagnostic(CSDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 3)); }); var options = ((CSharpCompilationOptions)compilation.Options); // generator driver diagnostics are reported seperately from the compilation verifyDiagnosticsWithOptions(options, Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)); // warnings can be individually suppressed verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Suppress), Diagnostic("GEN002").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Suppress), Diagnostic("GEN001").WithLocation(1, 1)); // warning level is respected verifyDiagnosticsWithOptions(options.WithWarningLevel(0)); verifyDiagnosticsWithOptions(options.WithWarningLevel(2), Diagnostic("GEN001").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithWarningLevel(3), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)); // warnings can be upgraded to errors verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Error), Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(true), Diagnostic("GEN002").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Error), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(true)); void verifyDiagnosticsWithOptions(CompilationOptions options, params DiagnosticDescription[] expected) { GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions); var updatedCompilation = compilation.WithOptions(options); driver.RunGeneratorsAndUpdateCompilation(updatedCompilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); diagnostics.Verify(expected); } } [Fact] public void Diagnostics_Respect_Pragma_Suppression() { var gen001 = CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2); // reported diagnostics can have a location in source verifyDiagnosticsWithSource("//comment", new[] { (gen001, TextSpan.FromBounds(2, 5)) }, Diagnostic("GEN001", "com").WithLocation(1, 3)); // diagnostics are suppressed via #pragma verifyDiagnosticsWithSource( @"#pragma warning disable //comment", new[] { (gen001, TextSpan.FromBounds(27, 30)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3)); // but not when they don't have a source location verifyDiagnosticsWithSource( @"#pragma warning disable //comment", new[] { (gen001, new TextSpan(0, 0)) }, Diagnostic("GEN001").WithLocation(1, 1)); // can be suppressed explicitly verifyDiagnosticsWithSource( @"#pragma warning disable GEN001 //comment", new[] { (gen001, TextSpan.FromBounds(34, 37)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3)); // suppress + restore verifyDiagnosticsWithSource( @"#pragma warning disable GEN001 //comment #pragma warning restore GEN001 //another", new[] { (gen001, TextSpan.FromBounds(34, 37)), (gen001, TextSpan.FromBounds(77, 80)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3), Diagnostic("GEN001", "ano").WithLocation(4, 3)); void verifyDiagnosticsWithSource(string source, (Diagnostic, TextSpan)[] reportDiagnostics, params DiagnosticDescription[] expected) { var parseOptions = TestOptions.Regular; source = source.Replace(Environment.NewLine, "\r\n"); Compilation compilation = CreateCompilation(source, sourceFileName: "sourcefile.cs", options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) => { foreach ((var d, var l) in reportDiagnostics) { if (l.IsEmpty) { c.ReportDiagnostic(d); } else { c.ReportDiagnostic(d.WithLocation(Location.Create(c.Compilation.SyntaxTrees.First(), l))); } } }); GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); diagnostics.Verify(expected); } } } }
47.018048
247
0.644507
[ "MIT" ]
Acidburn0zzz/roslyn
src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.cs
70,341
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System.Collections; using System.Collections.Generic; using Microsoft.TestCommon; namespace System.Web.Http.OData { public class TypeHelperTest { public static TheoryDataSet<Type, Type> CollectionTypesData { get { return new TheoryDataSet<Type, Type> { { typeof(ICollection<string>), typeof(string) }, { typeof(IList<string>), typeof(string) }, { typeof(List<int>), typeof(int) }, { typeof(IsCollection_with_Collections_TestClass), typeof(bool) }, { typeof(IEnumerable<int>), typeof(int) }, { typeof(int[]), typeof(int) }, { typeof(MyCustomCollection), typeof(int) }, }; } } [Theory] [PropertyData("CollectionTypesData")] public void IsCollection_with_Collections(Type collectionType, Type elementType) { Type type; Assert.True(collectionType.IsCollection(out type)); Assert.Equal(elementType, type); } [Theory] [PropertyData("CollectionTypesData")] public void GetInnerElementType(Type collectionType, Type elementType) { Assert.Equal(elementType, collectionType.GetInnerElementType()); } [Theory] [InlineData(typeof(object))] [InlineData(typeof(ICollection))] [InlineData(typeof(IEnumerable))] [InlineData(typeof(string))] public void IsCollection_with_NonCollections(Type type) { Assert.False(type.IsCollection()); } private sealed class IsCollection_with_Collections_TestClass : List<bool> { } private class MyCustomCollection : List<int> { } } }
31.904762
133
0.577612
[ "Apache-2.0" ]
charliefr/aspnetwebstack
test/System.Web.Http.OData.Test/TypeHelperTest.cs
2,012
C#
using GSU.Museum.CommonClassLibrary.Models; using GSU.Museum.Web.Interfaces; using GSU.Museum.Web.Models; using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.GridFS; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace GSU.Museum.Web.Repositories { public class HallsRepository : IHallsRepository { private readonly IMongoCollection<HallViewModel> _halls; private readonly IGridFSBucket _gridFS; public HallsRepository(DatabaseSettings settings) { var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); _halls = database.GetCollection<HallViewModel>(settings.CollectionName); _gridFS = new GridFSBucket(database); } public async Task<List<HallViewModel>> GetAllAsync() { var halls = await _halls.Find(hall => true).ToListAsync(); foreach (var hall in halls) { if (!string.IsNullOrEmpty(hall.Photo?.Id)) { hall.Photo.Photo = await _gridFS.DownloadAsBytesAsync(ObjectId.Parse(hall.Photo.Id)); } } return halls; } public async Task<HallViewModel> GetAsync(string id) { var hall = await _halls.Find(hall => hall.Id.Equals(id)).FirstOrDefaultAsync(); if (!string.IsNullOrEmpty(hall.Photo?.Id)) { hall.Photo.Photo = await _gridFS.DownloadAsBytesAsync(ObjectId.Parse(hall.Photo.Id)); } return hall; } public async Task<string> CreateAsync(HallViewModel hall) { if (hall.Photo?.Photo != null) { ObjectId id = await _gridFS.UploadFromBytesAsync(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffff"), hall.Photo.Photo); hall.Photo.Id = id.ToString(); hall.Photo.Photo = null; } hall.Id = ObjectId.GenerateNewId().ToString(); await _halls.InsertOneAsync(hall); return hall.Id; } public async Task UpdateAsync(string id, HallViewModel hallIn) { hallIn.Id = id; if (!string.IsNullOrEmpty(hallIn.Photo?.Id)) { await _gridFS.DeleteAsync(ObjectId.Parse(hallIn.Photo.Id)); } if (hallIn.Photo?.Photo != null) { ObjectId photoId = await _gridFS.UploadFromBytesAsync(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffff"), hallIn.Photo.Photo); hallIn.Photo.Id = photoId.ToString(); hallIn.Photo.Photo = null; } else { hallIn.Photo = null; } await _halls.ReplaceOneAsync(hall => hall.Id.Equals(id), hallIn); } public async Task RemoveAsync(HallViewModel hallIn) { if (hallIn.Photo?.Id != null) { await _gridFS.DeleteAsync(ObjectId.Parse(hallIn.Photo.Id)); } foreach(var stand in hallIn.Stands) { if (stand.Photo?.Id != null) { await _gridFS.DeleteAsync(ObjectId.Parse(stand.Photo.Id)); } foreach(var exhibit in stand.Exhibits) { if(exhibit.Photos != null && exhibit.Photos?.Count != 0) { foreach(var photo in exhibit.Photos) { if (photo?.Id != null) { await _gridFS.DeleteAsync(ObjectId.Parse(photo.Id)); } } } } } await _halls.DeleteOneAsync(hall => hall.Id.Equals(hallIn.Id)); } public async Task RemoveAsync(string id) { var hall = await GetAsync(id); await RemoveAsync(hall); } } }
35.127119
144
0.529312
[ "MIT" ]
Neroz1x/GSU.Museum
GSU.Museum.Web/Repositories/HallsRepository.cs
4,147
C#
using System.Collections.Generic; namespace Upp.Net { public enum AddResult { Stale, Current, TooFarInFuture } public class ByFramePlayoutBuffer<T> where T : ISequencedMessage { private readonly T[] _buffer; private int _bufferBaseIndex; private int _capacity; private ushort _bufferBaseSequence; private int _capacityBitMask; private int _fillLevel; public ByFramePlayoutBuffer(int capacityAsIndexOfMsb) { _capacity = capacityAsIndexOfMsb; _capacityBitMask = (1 << _capacity) - 1; _buffer = new T[1 << _capacity]; } public int GetFillLevel() { return _fillLevel; } public void ResetWithBaseId(ushort baseSequenceId) { _bufferBaseSequence = baseSequenceId; _fillLevel = 0; _bufferBaseIndex = 0; } public AddResult Add(T item) { var delta = (65536 + item.SequenceId - _bufferBaseSequence) & 65535; // TODO: what do the following two cases really mean? if ((delta >> _capacity) != 0) { return AddResult.TooFarInFuture; } if (delta < 0) { return AddResult.Stale; } _fillLevel++; _buffer[(_bufferBaseIndex + delta) & _capacityBitMask] = item; return AddResult.Current; } public T GetNext() { var item = _buffer[_bufferBaseIndex]; _buffer[_bufferBaseIndex] = default(T); _bufferBaseIndex = (_bufferBaseIndex + 1) & _capacityBitMask; _bufferBaseSequence = (ushort)(_bufferBaseSequence + 1); if (!EqualityComparer<T>.Default.Equals(item, default(T))) { _fillLevel--; } return item; } } }
26.594595
80
0.538618
[ "Apache-2.0" ]
ThomasZeman/Upp.Net
Source/Upp.Net/BySequencePlayoutBuffer.cs
1,970
C#
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Pine Gap Dark")] [assembly: AssemblyDescription("Based on the VS Code theme Ayu Mirage Bordered by ayu-theme")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Neon Clouds")] [assembly: AssemblyProduct("Pine Gap Dark")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a78fb2a1-8c18-4cea-8bb3-f57d5b4cd7ac")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: NeutralResourcesLanguage("en-US")]
38.277778
94
0.754717
[ "MIT" ]
tmacharia/pine-gap
src/Properties/AssemblyInfo.cs
1,381
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IAGrim.Backup.Azure.Dto { class AzureItemContainer { public AzureItemPartitionDto Partition { get; set; } public List<AzureItem> Items { get; set; } } }
23.461538
60
0.718033
[ "MIT" ]
Anomandrake/iagd
IAGrim/Backup/Azure/Dto/AzureItemContainer.cs
307
C#
 using Lockstep.Collision2D; using Lockstep.Math; using System.Collections.Generic; public class BaseEntity : BaseLifeCycle { public int EntityId; public int PrefabId; public CTransform2D transform = new CTransform2D(); public object engineTransform; protected List<BaseComponent> allComponents; public IGameStateService GameStateService { get; set; } public IServiceContainer ServiceContainer { get; set; } public IDebugService DebugService { get; set; } public IEntityView EntityView; public T GetService<T>() where T : IService { return ServiceContainer.GetService<T>(); } public void DoBindRef() { BindRef(); } protected virtual void BindRef() { allComponents?.Clear(); } protected void RegisterComponent(BaseComponent comp) { if (allComponents == null) { allComponents = new List<BaseComponent>(); } allComponents.Add(comp); comp.BindEntity(this); } public override void DoAwake() { if (allComponents == null) return; foreach (var comp in allComponents) { comp.DoAwake(); } } public override void DoStart() { if (allComponents == null) return; foreach (var comp in allComponents) { comp.DoStart(); } } public override void DoUpdate(LFloat deltaTime) { if (allComponents == null) return; foreach (var comp in allComponents) { comp.DoUpdate(deltaTime); } } public override void DoDestroy() { if (allComponents == null) return; foreach (var comp in allComponents) { comp.DoDestroy(); } } public virtual void OnRollbackDestroy() { EntityView?.OnRollbackDestroy(); EntityView = null; engineTransform = null; } }
21.865169
59
0.594553
[ "MIT" ]
XingHong/SimpleLockStepClient
Assets/Scripts/Logic/Framework/Base/BaseEntity.cs
1,948
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #nullable enable using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Framework; using DocumentFormat.OpenXml.Framework.Metadata; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation.Schema; using DocumentFormat.OpenXml.Wordprocessing; using System; using System.Collections.Generic; using System.IO.Packaging; namespace DocumentFormat.OpenXml.Office2019.Word.Cid { /// <summary> /// <para>Defines the CommentsIds Class.</para> /// <para>This class is available in Office 2019 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is w16cid:commentsIds.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2019.Word.Cid.CommentId" /> <c>&lt;w16cid:commentId></c></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr("w16cid:commentsIds")] #pragma warning restore CS0618 // Type or member is obsolete public partial class CommentsIds : OpenXmlPartRootElement { /// <summary> /// Initializes a new instance of the CommentsIds class. /// </summary> public CommentsIds() : base() { } /// <summary> /// Initializes a new instance of the CommentsIds class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public CommentsIds(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the CommentsIds class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public CommentsIds(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the CommentsIds class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public CommentsIds(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("w16cid:commentsIds"); builder.Availability = FileFormatVersions.Office2019; builder.AddChild<DocumentFormat.OpenXml.Office2019.Word.Cid.CommentId>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2019.Word.Cid.CommentId), 0, 0, version: FileFormatVersions.Office2019) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<CommentsIds>(deep); internal CommentsIds(WordprocessingCommentsIdsPart ownerPart) : base(ownerPart) { } /// <summary> /// Loads the DOM from the WordprocessingCommentsIdsPart /// </summary> /// <param name="openXmlPart">Specifies the part to be loaded.</param> public void Load(WordprocessingCommentsIdsPart openXmlPart) { LoadFromPart(openXmlPart); } /// <summary> /// Saves the DOM into the WordprocessingCommentsIdsPart. /// </summary> /// <param name="openXmlPart">Specifies the part to save to.</param> public void Save(WordprocessingCommentsIdsPart openXmlPart) { base.SaveToPart(openXmlPart); } /// <summary> /// Gets the WordprocessingCommentsIdsPart associated with this element. /// </summary> public WordprocessingCommentsIdsPart? WordprocessingCommentsIdsPart { get => OpenXmlPart as WordprocessingCommentsIdsPart; internal set => OpenXmlPart = value; } } /// <summary> /// <para>Defines the CommentId Class.</para> /// <para>This class is available in Office 2019 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is w16cid:commentId.</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr("w16cid:commentId")] #pragma warning restore CS0618 // Type or member is obsolete public partial class CommentId : OpenXmlLeafElement { /// <summary> /// Initializes a new instance of the CommentId class. /// </summary> public CommentId() : base() { } /// <summary> /// <para>paraId, this property is only available in Office 2019 and later.</para> /// <para>Represents the following attribute in the schema: w16cid:paraId</para> /// </summary> /// <remark> /// xmlns:w16cid=http://schemas.microsoft.com/office/word/2016/wordml/cid /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr("w16cid:paraId")] #pragma warning restore CS0618 // Type or member is obsolete public HexBinaryValue? ParaId { get => GetAttribute<HexBinaryValue>(); set => SetAttribute(value); } /// <summary> /// <para>durableId, this property is only available in Office 2019 and later.</para> /// <para>Represents the following attribute in the schema: w16cid:durableId</para> /// </summary> /// <remark> /// xmlns:w16cid=http://schemas.microsoft.com/office/word/2016/wordml/cid /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr("w16cid:durableId")] #pragma warning restore CS0618 // Type or member is obsolete public HexBinaryValue? DurableId { get => GetAttribute<HexBinaryValue>(); set => SetAttribute(value); } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("w16cid:commentId"); builder.Availability = FileFormatVersions.Office2019; builder.AddElement<CommentId>() .AddAttribute("w16cid:paraId", a => a.ParaId, aBuilder => { aBuilder.AddValidator(RequiredValidator.Instance); aBuilder.AddValidator(new OfficeVersionValidator(FileFormatVersions.Office2019)); aBuilder.AddValidator(new StringValidator() { Length = (4L) }); }) .AddAttribute("w16cid:durableId", a => a.DurableId, aBuilder => { aBuilder.AddValidator(RequiredValidator.Instance); aBuilder.AddValidator(new OfficeVersionValidator(FileFormatVersions.Office2019)); aBuilder.AddValidator(new StringValidator() { Length = (4L) }); }); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<CommentId>(deep); } }
38.115789
146
0.64982
[ "MIT" ]
JaimeStill/Open-XML-SDK
src/DocumentFormat.OpenXml/GeneratedCode/schemas_microsoft_com_office_word_2016_wordml_cid.g.cs
7,244
C#
// Copyright (c) Microsoft. All rights reserved. namespace Microsoft.Azure.Devices.Edge.Test.Common.Windows { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Devices.Client; using Microsoft.Azure.Devices.Edge.Test.Common.Certs; using Microsoft.Azure.Devices.Edge.Util; public class OsPlatform : Common.OsPlatform, IOsPlatform { public async Task<string> CollectDaemonLogsAsync(DateTime testStartTime, string filePrefix, CancellationToken token) { string command = "Get-WinEvent -ErrorAction SilentlyContinue " + $"-FilterHashtable @{{ProviderName='iotedged';LogName='application';StartTime='{testStartTime}'}} " + "| Select TimeCreated, Message " + "| Sort-Object @{Expression=\'TimeCreated\';Descending=$false} " + "| Format-Table -AutoSize -HideTableHeaders " + "| Out-String -Width 512"; string[] output = await Process.RunAsync("powershell", command, token); string daemonLog = $"{filePrefix}-iotedged.log"; await File.WriteAllLinesAsync(daemonLog, output, token); return daemonLog; } public Task<IEdgeDaemon> CreateEdgeDaemonAsync( Option<string> installerPath, Option<string> bootstrapAgentImage, Option<Registry> bootstrapRegistry, CancellationToken _) => Task.FromResult(new EdgeDaemon(installerPath, bootstrapAgentImage, bootstrapRegistry) as IEdgeDaemon); public async Task<IdCertificates> GenerateIdentityCertificatesAsync(string deviceId, string scriptPath, CancellationToken token) { var command = BuildCertCommand($"New-CACertsDevice '{deviceId}'", scriptPath); await this.RunScriptAsync(("powershell", command), token); // Windows requires all the certificates from root up to leaf to be installed. await this.RunScriptAsync(("powershell", $"Import-Certificate -CertStoreLocation 'cert:\\LocalMachine\\Root' -FilePath " + Path.Combine(scriptPath, "certs", "azure-iot-test-only.root.ca.cert.pem") + " | Out-Host"), token); await this.RunScriptAsync(("powershell", $"Import-Certificate -CertStoreLocation 'cert:\\LocalMachine\\Root' -FilePath " + Path.Combine(scriptPath, "certs", "azure-iot-test-only.intermediate.cert.pem") + " | Out-Host"), token); return new IdCertificates(deviceId, scriptPath); } public async Task<CaCertificates> GenerateCaCertificatesAsync(string deviceId, string scriptPath, CancellationToken token) { string command = BuildCertCommand( $"New-CACertsEdgeDevice '{deviceId}'", scriptPath); await this.RunScriptAsync(("powershell", command), token); return new CaCertificates(deviceId, scriptPath); } public CaCertificates GetEdgeQuickstartCertificates() { string certsBasePath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"iotedge\hsm"); return this.GetEdgeQuickstartCertificates(certsBasePath); } public void InstallCaCertificates(IEnumerable<X509Certificate2> certs, ITransportSettings transportSettings) => transportSettings.SetupCertificateValidation(certs.First()); public Task InstallRootCertificateAsync(string certPath, string keyPath, string password, string scriptPath, CancellationToken token) { string command = BuildCertCommand( $"Install-RootCACertificate '{certPath}' '{keyPath}' 'rsa' {password}", scriptPath); return this.InstallRootCertificateAsync(scriptPath, ("powershell", command), token); } public void InstallTrustedCertificates(IEnumerable<X509Certificate2> certs) => // On Windows, store certs under intermediate CA instead of root CA to avoid security UI in automated tests this.InstallTrustedCertificates(certs, StoreName.CertificateAuthority); static string BuildCertCommand(string command, string scriptPath) { var commands = new[] { $". {Path.Combine(scriptPath, "ca-certs.ps1")}", command }; return string.Join(";", commands); } } }
47.295918
239
0.656526
[ "MIT" ]
ArchanaMSFT/iotedge
test/Microsoft.Azure.Devices.Edge.Test.Common/windows/OsPlatform.cs
4,635
C#
// https://disqus.com/api/docs/errors/ //Error Codes // //Every error is represented with an HTTP status code, as well as a code and response message within the actual response body. // //There are two exceptions to these rules: // //Invalid formats will return an HTTP 415 with an error message as the response body. //JSONP without a callback will return a javascript commented response. //HTTP Code Meaning //200 0 Success //400 1 Endpoint not valid //400 2 Missing or invalid argument //400 3 Endpoint resource not valid //401 4 You must be authenticated to perform this action //403 5 Invalid API key //400 6 Invalid API version //400 7 You cannot access this resource using %(request_method)s //404 8 A requested object was not found //400 9 You cannot access this resource using your %(access_type)s API key //400 10 This operation is not supported //400 11 Your API key is not valid on this domain //400 12 This application does not have enough privileges to access this resource //400 13 You have exceeded the rate limit for this resource //400 14 You have exceeded the rate limit for your account //500 15 There was internal server error while processing your request //408 16 Your request timed out //400 17 The authenticated user does not have access to this feature //400 18 The authorization signature you passed was not valid //400 19 You must re-submit this request with a response to the captcha challenge //503 20 The API is currently undergoing maintenance, and your changes were saved, but will not be visible yet. //503 21 The API is currently undergoing maintenance, and your changes could not be saved. //400 22 You do not have the appropriate permissions to access this resource //400 23 You must be authenticated and verified by the forum owner to perform this action //400 24 You have exceeded the maximum number of creations for this resource
50.675676
126
0.778667
[ "MIT" ]
stuarthillary/DisqusN
src/DisqusN/ApiResponse.cs
1,877
C#
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. // <auto-generated/> #nullable enable using System; using System.Security; using System.Runtime.InteropServices; namespace ImageMagick { internal static partial class MagickMemory { [SuppressUnmanagedCodeSecurity] private static unsafe class NativeMethods { #if PLATFORM_x64 || PLATFORM_AnyCPU public static class X64 { [DllImport(NativeLibrary.X64Name, CallingConvention = CallingConvention.Cdecl)] public static extern void MagickMemory_Relinquish(IntPtr value); } #endif #if PLATFORM_arm64 || PLATFORM_AnyCPU public static class ARM64 { [DllImport(NativeLibrary.ARM64Name, CallingConvention = CallingConvention.Cdecl)] public static extern void MagickMemory_Relinquish(IntPtr value); } #endif #if PLATFORM_x86 || PLATFORM_AnyCPU public static class X86 { [DllImport(NativeLibrary.X86Name, CallingConvention = CallingConvention.Cdecl)] public static extern void MagickMemory_Relinquish(IntPtr value); } #endif } private unsafe static class NativeMagickMemory { static NativeMagickMemory() { Environment.Initialize(); } public static void Relinquish(IntPtr value) { #if PLATFORM_AnyCPU if (OperatingSystem.IsArm64) #endif #if PLATFORM_arm64 || PLATFORM_AnyCPU NativeMethods.ARM64.MagickMemory_Relinquish(value); #endif #if PLATFORM_AnyCPU else if (OperatingSystem.Is64Bit) #endif #if PLATFORM_x64 || PLATFORM_AnyCPU NativeMethods.X64.MagickMemory_Relinquish(value); #endif #if PLATFORM_AnyCPU else #endif #if PLATFORM_x86 || PLATFORM_AnyCPU NativeMethods.X86.MagickMemory_Relinquish(value); #endif } } } }
34.939394
97
0.575455
[ "Apache-2.0" ]
aTiKhan/Magick.NET
src/Magick.NET/Native/Helpers/MagickMemory.cs
2,306
C#
using System; using System.Collections.Generic; using System.Text; using System.Data; using DrugShop.Model; namespace DrugShop.Date { public interface ICompanyTypeDAO { /// <summary> /// 往CompanyType表中新增一条数据 /// </summary> /// <param name="type"></param> /// <param name="conn"></param> void InsertCompanyType(CompanyType type,IDbConnection conn); /// <summary> /// 往CompanyType表中新增一条数据 /// </summary> /// <param name="type"></param> /// <param name="conn"></param> /// <param name="trans"></param> void InsertCompanyType(CompanyType type,IDbConnection conn,IDbTransaction trans); /// <summary> /// 更新CompanyType表中一条已有的数据 /// </summary> /// <param name="type"></param> /// <param name="conn"></param> void UpdateCompanyType(CompanyType type,IDbConnection conn); /// <summary> /// 更新CompanyType表中一条已有的数据 /// </summary> /// <param name="type"></param> /// <param name="conn"></param> /// <param name="trans"></param> void UpdateCompanyType(CompanyType type,IDbConnection conn,IDbTransaction trans); /// <summary> /// 根据ID删除CompanyType表中的一条数据 /// </summary> /// <param name="id"></param> /// <param name="conn"></param> void DeleteCompanyType(int id,IDbConnection conn); /// <summary> /// 根据ID删除CompanyType表中的一条数据 /// </summary> /// <param name="id"></param> /// <param name="conn"></param> /// <param name="trans"></param> void DeleteCompanyType(int id,IDbConnection conn,IDbTransaction trans); /// <summary> /// 检索CompanyType表中的所有数据 /// </summary> /// <param name="conn"></param> /// <returns></returns> List<CompanyType> SelectAllCompanyType(IDbConnection conn); /// <summary> /// 根据ID检索对应的CompanyType /// </summary> /// <param name="id"></param> /// <param name="conn"></param> /// <returns></returns> CompanyType SelectCompanyType(int id,IDbConnection conn); /// <summary> /// 根据条件进行模糊检索 /// </summary> /// <param name="code"></param> /// <param name="name"></param> /// <param name="conn"></param> /// <returns></returns> List<CompanyType> SearchCompanyType(string code,string name,IDbConnection conn); } }
33.959459
89
0.553124
[ "MIT" ]
kuaidaoyanglang/DrugShop
DrugShop.Date/ICompanyTypeDAO.cs
2,691
C#
using System; using EdFi.SampleDataGenerator.Core.Entities; namespace EdFi.CalendarGenerator.Console { public class SchoolCalendarDate { public DateTime Date { get; set; } public CalendarEventDescriptor Descriptor { get; set; } } }
23.636364
63
0.715385
[ "Apache-2.0" ]
CSR2017/Ed-Fi-SampleDataGenerator
src/Utilities/EdFi.CalendarGenerator.Console/SchoolCalendarDate.cs
260
C#
using System.Reflection; using System.Runtime.InteropServices; using MelonLoader; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("StayMute")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("StayMute")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: MelonInfo(typeof(StayMute.StayMute), "StayMute", "1.0.1", "Elly")] [assembly: MelonGame("VRChat", "VRChat")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("08CD01E9-02A0-44ED-9F54-241A40A412D0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.189189
84
0.738399
[ "MIT" ]
EllyVR/StayMute
StayMute/Properties/AssemblyInfo.cs
1,490
C#
using System; using System.Linq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Caching; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.UnitOfWork; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; namespace Umbraco.Tests.Persistence.Repositories { [TestFixture] public class MemberRepositoryTest : BaseDatabaseFactoryTest { [SetUp] public override void Initialize() { base.Initialize(); } [TearDown] public override void TearDown() { base.TearDown(); } private MemberRepository CreateRepository(IDatabaseUnitOfWork unitOfWork, out MemberTypeRepository memberTypeRepository) { memberTypeRepository = new MemberTypeRepository(unitOfWork, NullCacheProvider.Current); var tagRepo = new TagsRepository(unitOfWork, NullCacheProvider.Current); var repository = new MemberRepository(unitOfWork, NullCacheProvider.Current, memberTypeRepository, tagRepo); return repository; } [Test] public void Can_Instantiate_Repository_From_Resolver() { // Arrange var provider = new PetaPocoUnitOfWorkProvider(); var unitOfWork = provider.GetUnitOfWork(); // Act var repository = RepositoryResolver.Current.ResolveByType<IMemberRepository>(unitOfWork); // Assert Assert.That(repository, Is.Not.Null); } [Test, NUnit.Framework.Ignore] public void MemberRepository_Can_Get_Member_By_Id() { var provider = new PetaPocoUnitOfWorkProvider(); var unitOfWork = provider.GetUnitOfWork(); MemberTypeRepository memberTypeRepository; using (var repository = CreateRepository(unitOfWork, out memberTypeRepository)) { var member = repository.Get(1341); Assert.That(member, Is.Not.Null); } } [Test, NUnit.Framework.Ignore] public void MemberRepository_Can_Get_Specific_Members() { var provider = new PetaPocoUnitOfWorkProvider(); var unitOfWork = provider.GetUnitOfWork(); MemberTypeRepository memberTypeRepository; using (var repository = CreateRepository(unitOfWork, out memberTypeRepository)) { var members = repository.GetAll(1341, 1383); Assert.That(members, Is.Not.Null); Assert.That(members.Any(x => x == null), Is.False); Assert.That(members.Count(), Is.EqualTo(2)); } } [Test, NUnit.Framework.Ignore] public void MemberRepository_Can_Get_All_Members() { var provider = new PetaPocoUnitOfWorkProvider(); var unitOfWork = provider.GetUnitOfWork(); MemberTypeRepository memberTypeRepository; using (var repository = CreateRepository(unitOfWork, out memberTypeRepository)) { var members = repository.GetAll(); Assert.That(members, Is.Not.Null); Assert.That(members.Any(x => x == null), Is.False); Assert.That(members.Count(), Is.EqualTo(6)); } } [Test, NUnit.Framework.Ignore] public void MemberRepository_Can_Perform_GetByQuery_With_Key() { // Arrange var provider = new PetaPocoUnitOfWorkProvider(); var unitOfWork = provider.GetUnitOfWork(); MemberTypeRepository memberTypeRepository; using (var repository = CreateRepository(unitOfWork, out memberTypeRepository)) { // Act var query = Query<IMember>.Builder.Where(x => x.Key == new Guid("A6B9CA6B-0615-42CA-B5F5-338417EC76BE")); var result = repository.GetByQuery(query); // Assert Assert.That(result.Count(), Is.EqualTo(1)); Assert.That(result.First().Id, Is.EqualTo(1341)); } } [Test, NUnit.Framework.Ignore] public void MemberRepository_Can_Perform_GetByQuery_With_Property_Value() { // Arrange var provider = new PetaPocoUnitOfWorkProvider(); var unitOfWork = provider.GetUnitOfWork(); MemberTypeRepository memberTypeRepository; using (var repository = CreateRepository(unitOfWork, out memberTypeRepository)) { // Act var query = Query<IMember>.Builder.Where(x => ((Member) x).ShortStringPropertyValue.EndsWith("piquet_h")); var result = repository.GetByQuery(query); // Assert Assert.That(result.Any(x => x == null), Is.False); Assert.That(result.Count(), Is.EqualTo(1)); Assert.That(result.First().Id, Is.EqualTo(1341)); } } [Test, NUnit.Framework.Ignore] public void MemberRepository_Can_Perform_GetByQuery_With_Property_Alias_And_Value() { // Arrange var provider = new PetaPocoUnitOfWorkProvider(); var unitOfWork = provider.GetUnitOfWork(); MemberTypeRepository memberTypeRepository; using (var repository = CreateRepository(unitOfWork, out memberTypeRepository)) { // Act var query = Query<IMember>.Builder.Where(x => ((Member) x).LongStringPropertyValue.Contains("1095") && ((Member) x).PropertyTypeAlias == "headshot"); var result = repository.GetByQuery(query); // Assert Assert.That(result.Any(x => x == null), Is.False); Assert.That(result.Count(), Is.EqualTo(5)); } } [Test] public void MemberRepository_Can_Persist_Member() { IMember sut; var provider = new PetaPocoUnitOfWorkProvider(); var unitOfWork = provider.GetUnitOfWork(); MemberTypeRepository memberTypeRepository; using (var repository = CreateRepository(unitOfWork, out memberTypeRepository)) { var memberType = MockedContentTypes.CreateSimpleMemberType(); memberTypeRepository.AddOrUpdate(memberType); unitOfWork.Commit(); var member = MockedMember.CreateSimpleContent(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty", -1); repository.AddOrUpdate(member); unitOfWork.Commit(); sut = repository.Get(member.Id); Assert.That(sut, Is.Not.Null); Assert.That(sut.ContentType.PropertyGroups.Count(), Is.EqualTo(1)); Assert.That(sut.ContentType.PropertyTypes.Count(), Is.EqualTo(12)); Assert.That(sut.Properties.Count(), Is.EqualTo(12)); Assert.That(sut.Properties.Any(x => x.HasIdentity == false || x.Id == 0), Is.False); } } [Test] public void MemberRepository_Does_Not_Replace_Password_When_Null() { IMember sut; var provider = new PetaPocoUnitOfWorkProvider(); var unitOfWork = provider.GetUnitOfWork(); MemberTypeRepository memberTypeRepository; using (var repository = CreateRepository(unitOfWork, out memberTypeRepository)) { var memberType = MockedContentTypes.CreateSimpleMemberType(); memberTypeRepository.AddOrUpdate(memberType); unitOfWork.Commit(); var member = MockedMember.CreateSimpleContent(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty", -1); repository.AddOrUpdate(member); unitOfWork.Commit(); sut = repository.Get(member.Id); //when the password is null it will not overwrite what is already there. sut.Password = null; repository.AddOrUpdate(sut); unitOfWork.Commit(); sut = repository.Get(member.Id); Assert.That(sut.Password, Is.EqualTo("123")); } } [Test] public void MemberRepository_Can_Update_Email_And_Login_When_Changed() { IMember sut; var provider = new PetaPocoUnitOfWorkProvider(); var unitOfWork = provider.GetUnitOfWork(); MemberTypeRepository memberTypeRepository; using (var repository = CreateRepository(unitOfWork, out memberTypeRepository)) { var memberType = MockedContentTypes.CreateSimpleMemberType(); memberTypeRepository.AddOrUpdate(memberType); unitOfWork.Commit(); var member = MockedMember.CreateSimpleContent(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty", -1); repository.AddOrUpdate(member); unitOfWork.Commit(); sut = repository.Get(member.Id); sut.Username = "This is new"; sut.Email = "thisisnew@hello.com"; repository.AddOrUpdate(sut); unitOfWork.Commit(); sut = repository.Get(member.Id); Assert.That(sut.Email, Is.EqualTo("thisisnew@hello.com")); Assert.That(sut.Username, Is.EqualTo("This is new")); } } [Test] public void Can_Create_Correct_Subquery() { var query = Query<IMember>.Builder.Where(x => ((Member) x).LongStringPropertyValue.Contains("1095") && ((Member) x).PropertyTypeAlias == "headshot"); var sqlSubquery = GetSubquery(); var translator = new SqlTranslator<IMember>(sqlSubquery, query); var subquery = translator.Translate(); var sql = GetBaseQuery(false) .Append(new Sql("WHERE umbracoNode.id IN (" + subquery.SQL + ")", subquery.Arguments)) .OrderByDescending<ContentVersionDto>(x => x.VersionDate) .OrderBy<NodeDto>(x => x.SortOrder); Console.WriteLine(sql.SQL); Assert.That(sql.SQL, Is.Not.Empty); } private Sql GetBaseQuery(bool isCount) { if (isCount) { var sqlCount = new Sql() .Select("COUNT(*)") .From<NodeDto>() .InnerJoin<ContentDto>().On<ContentDto, NodeDto>(left => left.NodeId, right => right.NodeId) .InnerJoin<ContentTypeDto>().On<ContentTypeDto, ContentDto>(left => left.NodeId, right => right.ContentTypeId) .InnerJoin<ContentVersionDto>().On<ContentVersionDto, NodeDto>(left => left.NodeId, right => right.NodeId) .InnerJoin<MemberDto>().On<MemberDto, ContentDto>(left => left.NodeId, right => right.NodeId) .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId); return sqlCount; } var sql = new Sql(); sql.Select("umbracoNode.*", "cmsContent.contentType", "cmsContentType.alias AS ContentTypeAlias", "cmsContentVersion.VersionId", "cmsContentVersion.VersionDate", "cmsContentVersion.LanguageLocale", "cmsMember.Email", "cmsMember.LoginName", "cmsMember.Password", "cmsPropertyData.id AS PropertyDataId", "cmsPropertyData.propertytypeid", "cmsPropertyData.dataDate", "cmsPropertyData.dataInt", "cmsPropertyData.dataNtext", "cmsPropertyData.dataNvarchar", "cmsPropertyType.id", "cmsPropertyType.Alias", "cmsPropertyType.Description", "cmsPropertyType.Name", "cmsPropertyType.mandatory", "cmsPropertyType.validationRegExp", "cmsPropertyType.helpText", "cmsPropertyType.sortOrder AS PropertyTypeSortOrder", "cmsPropertyType.propertyTypeGroupId", "cmsPropertyType.dataTypeId", "cmsDataType.propertyEditorAlias", "cmsDataType.dbType") .From<NodeDto>() .InnerJoin<ContentDto>().On<ContentDto, NodeDto>(left => left.NodeId, right => right.NodeId) .InnerJoin<ContentTypeDto>().On<ContentTypeDto, ContentDto>(left => left.NodeId, right => right.ContentTypeId) .InnerJoin<ContentVersionDto>().On<ContentVersionDto, NodeDto>(left => left.NodeId, right => right.NodeId) .InnerJoin<MemberDto>().On<MemberDto, ContentDto>(left => left.NodeId, right => right.NodeId) .LeftJoin<PropertyTypeDto>().On<PropertyTypeDto, ContentDto>(left => left.ContentTypeId, right => right.ContentTypeId) .LeftJoin<DataTypeDto>().On<DataTypeDto, PropertyTypeDto>(left => left.DataTypeId, right => right.DataTypeId) .LeftJoin<PropertyDataDto>().On<PropertyDataDto, PropertyTypeDto>(left => left.PropertyTypeId, right => right.Id) .Append("AND cmsPropertyData.versionId = cmsContentVersion.VersionId") .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId); return sql; } private Sql GetSubquery() { var sql = new Sql(); sql.Select("umbracoNode.id") .From<NodeDto>() .InnerJoin<ContentDto>().On<ContentDto, NodeDto>(left => left.NodeId, right => right.NodeId) .InnerJoin<ContentTypeDto>().On<ContentTypeDto, ContentDto>(left => left.NodeId, right => right.ContentTypeId) .InnerJoin<ContentVersionDto>().On<ContentVersionDto, NodeDto>(left => left.NodeId, right => right.NodeId) .InnerJoin<MemberDto>().On<MemberDto, ContentDto>(left => left.NodeId, right => right.NodeId) .LeftJoin<PropertyTypeDto>().On<PropertyTypeDto, ContentDto>(left => left.ContentTypeId, right => right.ContentTypeId) .LeftJoin<DataTypeDto>().On<DataTypeDto, PropertyTypeDto>(left => left.DataTypeId, right => right.DataTypeId) .LeftJoin<PropertyDataDto>().On<PropertyDataDto, PropertyTypeDto>(left => left.PropertyTypeId, right => right.Id) .Append("AND cmsPropertyData.versionId = cmsContentVersion.VersionId") .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId); return sql; } private Guid NodeObjectTypeId { get { return new Guid(Constants.ObjectTypes.Member); } } } }
46.324159
166
0.588527
[ "MIT" ]
ConnectionMaster/Umbraco-CMS
src/Umbraco.Tests/Persistence/Repositories/MemberRepositoryTest.cs
15,150
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // This source file is machine generated. Please do not change the code manually. using System; using System.Collections.Generic; using System.IO.Packaging; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml; namespace DocumentFormat.OpenXml.InkML { /// <summary> /// <para>Defines the Ink Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:ink.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>Annotation &lt;inkml:annotation></description></item> ///<item><description>AnnotationXml &lt;inkml:annotationXML></description></item> ///<item><description>Definitions &lt;inkml:definitions></description></item> ///<item><description>Context &lt;inkml:context></description></item> ///<item><description>Trace &lt;inkml:trace></description></item> ///<item><description>TraceGroup &lt;inkml:traceGroup></description></item> ///<item><description>TraceView &lt;inkml:traceView></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(Annotation))] [ChildElementInfo(typeof(AnnotationXml))] [ChildElementInfo(typeof(Definitions))] [ChildElementInfo(typeof(Context))] [ChildElementInfo(typeof(Trace))] [ChildElementInfo(typeof(TraceGroup))] [ChildElementInfo(typeof(TraceView))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Ink : OpenXmlPartRootElement { private const string tagName = "ink"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12714; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "documentID" }; private static byte[] attributeNamespaceIds = { 0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> documentID.</para> /// <para>Represents the following attribute in the schema: documentID </para> /// </summary> [SchemaAttr(0, "documentID")] public StringValue DocumentId { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// Initializes a new instance of the Ink class. /// </summary> public Ink():base(){} /// <summary> ///Initializes a new instance of the Ink class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Ink(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Ink class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Ink(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Ink class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Ink(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "annotation" == name) return new Annotation(); if( 43 == namespaceId && "annotationXML" == name) return new AnnotationXml(); if( 43 == namespaceId && "definitions" == name) return new Definitions(); if( 43 == namespaceId && "context" == name) return new Context(); if( 43 == namespaceId && "trace" == name) return new Trace(); if( 43 == namespaceId && "traceGroup" == name) return new TraceGroup(); if( 43 == namespaceId && "traceView" == name) return new TraceView(); return null; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "documentID" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Ink>(deep); } } /// <summary> /// <para>Defines the Bind Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:bind.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Bind : OpenXmlLeafElement { private const string tagName = "bind"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12715; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "source","target","column","variable" }; private static byte[] attributeNamespaceIds = { 0,0,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> source.</para> /// <para>Represents the following attribute in the schema: source </para> /// </summary> [SchemaAttr(0, "source")] public StringValue Source { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> target.</para> /// <para>Represents the following attribute in the schema: target </para> /// </summary> [SchemaAttr(0, "target")] public StringValue Target { get { return (StringValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> column.</para> /// <para>Represents the following attribute in the schema: column </para> /// </summary> [SchemaAttr(0, "column")] public StringValue Column { get { return (StringValue)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// <para> variable.</para> /// <para>Represents the following attribute in the schema: variable </para> /// </summary> [SchemaAttr(0, "variable")] public StringValue Variable { get { return (StringValue)Attributes[3]; } set { Attributes[3] = value; } } /// <summary> /// Initializes a new instance of the Bind class. /// </summary> public Bind():base(){} internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "source" == name) return new StringValue(); if( 0 == namespaceId && "target" == name) return new StringValue(); if( 0 == namespaceId && "column" == name) return new StringValue(); if( 0 == namespaceId && "variable" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Bind>(deep); } } /// <summary> /// <para>Defines the Table Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:table.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Table : OpenXmlLeafTextElement { private const string tagName = "table"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12716; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id","apply","interpolation" }; private static byte[] attributeNamespaceIds = { 1,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: xml:id </para> /// </summary> ///<remark> xmlns:xml=http://www.w3.org/XML/1998/namespace ///</remark> [SchemaAttr(1, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> apply.</para> /// <para>Represents the following attribute in the schema: apply </para> /// </summary> [SchemaAttr(0, "apply")] public EnumValue<DocumentFormat.OpenXml.InkML.TableApplyValues> Apply { get { return (EnumValue<DocumentFormat.OpenXml.InkML.TableApplyValues>)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> interpolation.</para> /// <para>Represents the following attribute in the schema: interpolation </para> /// </summary> [SchemaAttr(0, "interpolation")] public EnumValue<DocumentFormat.OpenXml.InkML.TableInterpolationValues> Interpolation { get { return (EnumValue<DocumentFormat.OpenXml.InkML.TableInterpolationValues>)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// Initializes a new instance of the Table class. /// </summary> public Table():base(){} /// <summary> /// Initializes a new instance of the Table class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Table(string text):base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue(){ InnerText = text }; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 1 == namespaceId && "id" == name) return new StringValue(); if( 0 == namespaceId && "apply" == name) return new EnumValue<DocumentFormat.OpenXml.InkML.TableApplyValues>(); if( 0 == namespaceId && "interpolation" == name) return new EnumValue<DocumentFormat.OpenXml.InkML.TableInterpolationValues>(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Table>(deep); } } /// <summary> /// <para>Defines the Matrix Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:matrix.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Matrix : OpenXmlLeafTextElement { private const string tagName = "matrix"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12717; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id" }; private static byte[] attributeNamespaceIds = { 1 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: xml:id </para> /// </summary> ///<remark> xmlns:xml=http://www.w3.org/XML/1998/namespace ///</remark> [SchemaAttr(1, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// Initializes a new instance of the Matrix class. /// </summary> public Matrix():base(){} /// <summary> /// Initializes a new instance of the Matrix class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Matrix(string text):base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue(){ InnerText = text }; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 1 == namespaceId && "id" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Matrix>(deep); } } /// <summary> /// <para>Defines the Mapping Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:mapping.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>Bind &lt;inkml:bind></description></item> ///<item><description>Table &lt;inkml:table></description></item> ///<item><description>Matrix &lt;inkml:matrix></description></item> ///<item><description>Mapping &lt;inkml:mapping></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(Bind))] [ChildElementInfo(typeof(Table))] [ChildElementInfo(typeof(Matrix))] [ChildElementInfo(typeof(Mapping))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Mapping : OpenXmlCompositeElement { private const string tagName = "mapping"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12718; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id","type","mappingRef" }; private static byte[] attributeNamespaceIds = { 1,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: xml:id </para> /// </summary> ///<remark> xmlns:xml=http://www.w3.org/XML/1998/namespace ///</remark> [SchemaAttr(1, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> type.</para> /// <para>Represents the following attribute in the schema: type </para> /// </summary> [SchemaAttr(0, "type")] public EnumValue<DocumentFormat.OpenXml.InkML.MappingTypeValues> Type { get { return (EnumValue<DocumentFormat.OpenXml.InkML.MappingTypeValues>)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> mappingRef.</para> /// <para>Represents the following attribute in the schema: mappingRef </para> /// </summary> [SchemaAttr(0, "mappingRef")] public StringValue MappingRef { get { return (StringValue)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// Initializes a new instance of the Mapping class. /// </summary> public Mapping():base(){} /// <summary> ///Initializes a new instance of the Mapping class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Mapping(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Mapping class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Mapping(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Mapping class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Mapping(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "bind" == name) return new Bind(); if( 43 == namespaceId && "table" == name) return new Table(); if( 43 == namespaceId && "matrix" == name) return new Matrix(); if( 43 == namespaceId && "mapping" == name) return new Mapping(); return null; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 1 == namespaceId && "id" == name) return new StringValue(); if( 0 == namespaceId && "type" == name) return new EnumValue<DocumentFormat.OpenXml.InkML.MappingTypeValues>(); if( 0 == namespaceId && "mappingRef" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Mapping>(deep); } } /// <summary> /// <para>Defines the Channel Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:channel.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>Mapping &lt;inkml:mapping></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(Mapping))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Channel : OpenXmlCompositeElement { private const string tagName = "channel"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12719; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id","name","type","default","min","max","orientation","respectTo","units" }; private static byte[] attributeNamespaceIds = { 1,0,0,0,0,0,0,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: xml:id </para> /// </summary> ///<remark> xmlns:xml=http://www.w3.org/XML/1998/namespace ///</remark> [SchemaAttr(1, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> name.</para> /// <para>Represents the following attribute in the schema: name </para> /// </summary> [SchemaAttr(0, "name")] public StringValue Name { get { return (StringValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> type.</para> /// <para>Represents the following attribute in the schema: type </para> /// </summary> [SchemaAttr(0, "type")] public EnumValue<DocumentFormat.OpenXml.InkML.ChannelDataTypeValues> Type { get { return (EnumValue<DocumentFormat.OpenXml.InkML.ChannelDataTypeValues>)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// <para> default.</para> /// <para>Represents the following attribute in the schema: default </para> /// </summary> [SchemaAttr(0, "default")] public StringValue Default { get { return (StringValue)Attributes[3]; } set { Attributes[3] = value; } } /// <summary> /// <para> min.</para> /// <para>Represents the following attribute in the schema: min </para> /// </summary> [SchemaAttr(0, "min")] public DecimalValue Min { get { return (DecimalValue)Attributes[4]; } set { Attributes[4] = value; } } /// <summary> /// <para> max.</para> /// <para>Represents the following attribute in the schema: max </para> /// </summary> [SchemaAttr(0, "max")] public DecimalValue Max { get { return (DecimalValue)Attributes[5]; } set { Attributes[5] = value; } } /// <summary> /// <para> orientation.</para> /// <para>Represents the following attribute in the schema: orientation </para> /// </summary> [SchemaAttr(0, "orientation")] public EnumValue<DocumentFormat.OpenXml.InkML.ChannelValueOrientationValues> Orientation { get { return (EnumValue<DocumentFormat.OpenXml.InkML.ChannelValueOrientationValues>)Attributes[6]; } set { Attributes[6] = value; } } /// <summary> /// <para> respectTo.</para> /// <para>Represents the following attribute in the schema: respectTo </para> /// </summary> [SchemaAttr(0, "respectTo")] public StringValue RespectTo { get { return (StringValue)Attributes[7]; } set { Attributes[7] = value; } } /// <summary> /// <para> units.</para> /// <para>Represents the following attribute in the schema: units </para> /// </summary> [SchemaAttr(0, "units")] public StringValue Units { get { return (StringValue)Attributes[8]; } set { Attributes[8] = value; } } /// <summary> /// Initializes a new instance of the Channel class. /// </summary> public Channel():base(){} /// <summary> ///Initializes a new instance of the Channel class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Channel(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Channel class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Channel(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Channel class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Channel(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "mapping" == name) return new Mapping(); return null; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 1 == namespaceId && "id" == name) return new StringValue(); if( 0 == namespaceId && "name" == name) return new StringValue(); if( 0 == namespaceId && "type" == name) return new EnumValue<DocumentFormat.OpenXml.InkML.ChannelDataTypeValues>(); if( 0 == namespaceId && "default" == name) return new StringValue(); if( 0 == namespaceId && "min" == name) return new DecimalValue(); if( 0 == namespaceId && "max" == name) return new DecimalValue(); if( 0 == namespaceId && "orientation" == name) return new EnumValue<DocumentFormat.OpenXml.InkML.ChannelValueOrientationValues>(); if( 0 == namespaceId && "respectTo" == name) return new StringValue(); if( 0 == namespaceId && "units" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Channel>(deep); } } /// <summary> /// <para>Defines the IntermittentChannels Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:intermittentChannels.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>Channel &lt;inkml:channel></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(Channel))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class IntermittentChannels : OpenXmlCompositeElement { private const string tagName = "intermittentChannels"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12720; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } /// <summary> /// Initializes a new instance of the IntermittentChannels class. /// </summary> public IntermittentChannels():base(){} /// <summary> ///Initializes a new instance of the IntermittentChannels class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public IntermittentChannels(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the IntermittentChannels class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public IntermittentChannels(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the IntermittentChannels class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public IntermittentChannels(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "channel" == name) return new Channel(); return null; } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<IntermittentChannels>(deep); } } /// <summary> /// <para>Defines the ChannelProperty Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:channelProperty.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class ChannelProperty : OpenXmlLeafElement { private const string tagName = "channelProperty"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12721; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "channel","name","value","units" }; private static byte[] attributeNamespaceIds = { 0,0,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> channel.</para> /// <para>Represents the following attribute in the schema: channel </para> /// </summary> [SchemaAttr(0, "channel")] public StringValue Channel { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> name.</para> /// <para>Represents the following attribute in the schema: name </para> /// </summary> [SchemaAttr(0, "name")] public StringValue Name { get { return (StringValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> value.</para> /// <para>Represents the following attribute in the schema: value </para> /// </summary> [SchemaAttr(0, "value")] public DecimalValue Value { get { return (DecimalValue)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// <para> units.</para> /// <para>Represents the following attribute in the schema: units </para> /// </summary> [SchemaAttr(0, "units")] public StringValue Units { get { return (StringValue)Attributes[3]; } set { Attributes[3] = value; } } /// <summary> /// Initializes a new instance of the ChannelProperty class. /// </summary> public ChannelProperty():base(){} internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "channel" == name) return new StringValue(); if( 0 == namespaceId && "name" == name) return new StringValue(); if( 0 == namespaceId && "value" == name) return new DecimalValue(); if( 0 == namespaceId && "units" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<ChannelProperty>(deep); } } /// <summary> /// <para>Defines the TraceFormat Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:traceFormat.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>Channel &lt;inkml:channel></description></item> ///<item><description>IntermittentChannels &lt;inkml:intermittentChannels></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(Channel))] [ChildElementInfo(typeof(IntermittentChannels))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class TraceFormat : OpenXmlCompositeElement { private const string tagName = "traceFormat"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12722; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id" }; private static byte[] attributeNamespaceIds = { 1 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: xml:id </para> /// </summary> ///<remark> xmlns:xml=http://www.w3.org/XML/1998/namespace ///</remark> [SchemaAttr(1, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// Initializes a new instance of the TraceFormat class. /// </summary> public TraceFormat():base(){} /// <summary> ///Initializes a new instance of the TraceFormat class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public TraceFormat(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the TraceFormat class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public TraceFormat(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the TraceFormat class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public TraceFormat(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "channel" == name) return new Channel(); if( 43 == namespaceId && "intermittentChannels" == name) return new IntermittentChannels(); return null; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 1 == namespaceId && "id" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<TraceFormat>(deep); } } /// <summary> /// <para>Defines the SampleRate Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:sampleRate.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class SampleRate : OpenXmlLeafElement { private const string tagName = "sampleRate"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12723; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "uniform","value" }; private static byte[] attributeNamespaceIds = { 0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> uniform.</para> /// <para>Represents the following attribute in the schema: uniform </para> /// </summary> [SchemaAttr(0, "uniform")] public BooleanValue Uniform { get { return (BooleanValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> value.</para> /// <para>Represents the following attribute in the schema: value </para> /// </summary> [SchemaAttr(0, "value")] public DecimalValue Value { get { return (DecimalValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// Initializes a new instance of the SampleRate class. /// </summary> public SampleRate():base(){} internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "uniform" == name) return new BooleanValue(); if( 0 == namespaceId && "value" == name) return new DecimalValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<SampleRate>(deep); } } /// <summary> /// <para>Defines the Latency Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:latency.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Latency : OpenXmlLeafElement { private const string tagName = "latency"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12724; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "value" }; private static byte[] attributeNamespaceIds = { 0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> value.</para> /// <para>Represents the following attribute in the schema: value </para> /// </summary> [SchemaAttr(0, "value")] public DecimalValue Value { get { return (DecimalValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// Initializes a new instance of the Latency class. /// </summary> public Latency():base(){} internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "value" == name) return new DecimalValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Latency>(deep); } } /// <summary> /// <para>Defines the ActiveArea Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:activeArea.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class ActiveArea : OpenXmlLeafElement { private const string tagName = "activeArea"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12725; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "size","height","width","units" }; private static byte[] attributeNamespaceIds = { 0,0,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> size.</para> /// <para>Represents the following attribute in the schema: size </para> /// </summary> [SchemaAttr(0, "size")] public StringValue Size { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> height.</para> /// <para>Represents the following attribute in the schema: height </para> /// </summary> [SchemaAttr(0, "height")] public DecimalValue Height { get { return (DecimalValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> width.</para> /// <para>Represents the following attribute in the schema: width </para> /// </summary> [SchemaAttr(0, "width")] public DecimalValue Width { get { return (DecimalValue)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// <para> units.</para> /// <para>Represents the following attribute in the schema: units </para> /// </summary> [SchemaAttr(0, "units")] public StringValue Units { get { return (StringValue)Attributes[3]; } set { Attributes[3] = value; } } /// <summary> /// Initializes a new instance of the ActiveArea class. /// </summary> public ActiveArea():base(){} internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "size" == name) return new StringValue(); if( 0 == namespaceId && "height" == name) return new DecimalValue(); if( 0 == namespaceId && "width" == name) return new DecimalValue(); if( 0 == namespaceId && "units" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<ActiveArea>(deep); } } /// <summary> /// <para>Defines the SourceProperty Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:srcProperty.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class SourceProperty : OpenXmlLeafElement { private const string tagName = "srcProperty"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12726; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "name","value","units" }; private static byte[] attributeNamespaceIds = { 0,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> name.</para> /// <para>Represents the following attribute in the schema: name </para> /// </summary> [SchemaAttr(0, "name")] public StringValue Name { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> value.</para> /// <para>Represents the following attribute in the schema: value </para> /// </summary> [SchemaAttr(0, "value")] public DecimalValue Value { get { return (DecimalValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> units.</para> /// <para>Represents the following attribute in the schema: units </para> /// </summary> [SchemaAttr(0, "units")] public StringValue Units { get { return (StringValue)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// Initializes a new instance of the SourceProperty class. /// </summary> public SourceProperty():base(){} internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "name" == name) return new StringValue(); if( 0 == namespaceId && "value" == name) return new DecimalValue(); if( 0 == namespaceId && "units" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<SourceProperty>(deep); } } /// <summary> /// <para>Defines the ChannelProperties Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:channelProperties.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>ChannelProperty &lt;inkml:channelProperty></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(ChannelProperty))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class ChannelProperties : OpenXmlCompositeElement { private const string tagName = "channelProperties"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12727; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } /// <summary> /// Initializes a new instance of the ChannelProperties class. /// </summary> public ChannelProperties():base(){} /// <summary> ///Initializes a new instance of the ChannelProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ChannelProperties(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ChannelProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ChannelProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ChannelProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ChannelProperties(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "channelProperty" == name) return new ChannelProperty(); return null; } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<ChannelProperties>(deep); } } /// <summary> /// <para>Defines the Annotation Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:annotation.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Annotation : OpenXmlLeafTextElement { private const string tagName = "annotation"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12728; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "type","encoding" }; private static byte[] attributeNamespaceIds = { 0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> type.</para> /// <para>Represents the following attribute in the schema: type </para> /// </summary> [SchemaAttr(0, "type")] public StringValue Type { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> encoding.</para> /// <para>Represents the following attribute in the schema: encoding </para> /// </summary> [SchemaAttr(0, "encoding")] public StringValue Encoding { get { return (StringValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// Initializes a new instance of the Annotation class. /// </summary> public Annotation():base(){} /// <summary> /// Initializes a new instance of the Annotation class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Annotation(string text):base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue(){ InnerText = text }; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "type" == name) return new StringValue(); if( 0 == namespaceId && "encoding" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Annotation>(deep); } } /// <summary> /// <para>Defines the AnnotationXml Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:annotationXML.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>DocumentFormat.OpenXml.EMMA.Emma &lt;emma:emma></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(DocumentFormat.OpenXml.EMMA.Emma))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class AnnotationXml : OpenXmlCompositeElement { private const string tagName = "annotationXML"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12729; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "type","encoding","href" }; private static byte[] attributeNamespaceIds = { 0,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> type.</para> /// <para>Represents the following attribute in the schema: type </para> /// </summary> [SchemaAttr(0, "type")] public StringValue Type { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> encoding.</para> /// <para>Represents the following attribute in the schema: encoding </para> /// </summary> [SchemaAttr(0, "encoding")] public StringValue Encoding { get { return (StringValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> href.</para> /// <para>Represents the following attribute in the schema: href </para> /// </summary> [SchemaAttr(0, "href")] public StringValue Href { get { return (StringValue)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// Initializes a new instance of the AnnotationXml class. /// </summary> public AnnotationXml():base(){} /// <summary> ///Initializes a new instance of the AnnotationXml class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public AnnotationXml(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the AnnotationXml class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public AnnotationXml(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the AnnotationXml class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public AnnotationXml(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 44 == namespaceId && "emma" == name) return new DocumentFormat.OpenXml.EMMA.Emma(); return null; } private static readonly string[] eleTagNames = { "emma" }; private static readonly byte[] eleNamespaceIds = { 44 }; internal override string[] ElementTagNames { get{ return eleTagNames; } } internal override byte[] ElementNamespaceIds { get{ return eleNamespaceIds; } } internal override OpenXmlCompositeType OpenXmlCompositeType { get {return OpenXmlCompositeType.OneSequence;} } /// <summary> /// <para> Emma.</para> /// <para> Represents the following element tag in the schema: emma:emma </para> /// </summary> /// <remark> /// xmlns:emma = http://www.w3.org/2003/04/emma /// </remark> public DocumentFormat.OpenXml.EMMA.Emma Emma { get { return GetElement<DocumentFormat.OpenXml.EMMA.Emma>(0); } set { SetElement(0, value); } } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "type" == name) return new StringValue(); if( 0 == namespaceId && "encoding" == name) return new StringValue(); if( 0 == namespaceId && "href" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<AnnotationXml>(deep); } } /// <summary> /// <para>Defines the BrushProperty Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:brushProperty.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>Annotation &lt;inkml:annotation></description></item> ///<item><description>AnnotationXml &lt;inkml:annotationXML></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(Annotation))] [ChildElementInfo(typeof(AnnotationXml))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class BrushProperty : OpenXmlCompositeElement { private const string tagName = "brushProperty"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12730; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "name","value","units" }; private static byte[] attributeNamespaceIds = { 0,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> name.</para> /// <para>Represents the following attribute in the schema: name </para> /// </summary> [SchemaAttr(0, "name")] public StringValue Name { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> value.</para> /// <para>Represents the following attribute in the schema: value </para> /// </summary> [SchemaAttr(0, "value")] public StringValue Value { get { return (StringValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> units.</para> /// <para>Represents the following attribute in the schema: units </para> /// </summary> [SchemaAttr(0, "units")] public StringValue Units { get { return (StringValue)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// Initializes a new instance of the BrushProperty class. /// </summary> public BrushProperty():base(){} /// <summary> ///Initializes a new instance of the BrushProperty class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public BrushProperty(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the BrushProperty class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public BrushProperty(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the BrushProperty class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public BrushProperty(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "annotation" == name) return new Annotation(); if( 43 == namespaceId && "annotationXML" == name) return new AnnotationXml(); return null; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "name" == name) return new StringValue(); if( 0 == namespaceId && "value" == name) return new StringValue(); if( 0 == namespaceId && "units" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<BrushProperty>(deep); } } /// <summary> /// <para>Defines the Canvas Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:canvas.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>TraceFormat &lt;inkml:traceFormat></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(TraceFormat))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Canvas : OpenXmlCompositeElement { private const string tagName = "canvas"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12731; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id","traceFormatRef" }; private static byte[] attributeNamespaceIds = { 1,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: xml:id </para> /// </summary> ///<remark> xmlns:xml=http://www.w3.org/XML/1998/namespace ///</remark> [SchemaAttr(1, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> traceFormatRef.</para> /// <para>Represents the following attribute in the schema: traceFormatRef </para> /// </summary> [SchemaAttr(0, "traceFormatRef")] public StringValue TraceFormatRef { get { return (StringValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// Initializes a new instance of the Canvas class. /// </summary> public Canvas():base(){} /// <summary> ///Initializes a new instance of the Canvas class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Canvas(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Canvas class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Canvas(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Canvas class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Canvas(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "traceFormat" == name) return new TraceFormat(); return null; } private static readonly string[] eleTagNames = { "traceFormat" }; private static readonly byte[] eleNamespaceIds = { 43 }; internal override string[] ElementTagNames { get{ return eleTagNames; } } internal override byte[] ElementNamespaceIds { get{ return eleNamespaceIds; } } internal override OpenXmlCompositeType OpenXmlCompositeType { get {return OpenXmlCompositeType.OneSequence;} } /// <summary> /// <para> TraceFormat.</para> /// <para> Represents the following element tag in the schema: inkml:traceFormat </para> /// </summary> /// <remark> /// xmlns:inkml = http://www.w3.org/2003/InkML /// </remark> public TraceFormat TraceFormat { get { return GetElement<TraceFormat>(0); } set { SetElement(0, value); } } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 1 == namespaceId && "id" == name) return new StringValue(); if( 0 == namespaceId && "traceFormatRef" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Canvas>(deep); } } /// <summary> /// <para>Defines the CanvasTransform Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:canvasTransform.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>Mapping &lt;inkml:mapping></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(Mapping))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class CanvasTransform : OpenXmlCompositeElement { private const string tagName = "canvasTransform"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12732; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id","invertible" }; private static byte[] attributeNamespaceIds = { 1,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: xml:id </para> /// </summary> ///<remark> xmlns:xml=http://www.w3.org/XML/1998/namespace ///</remark> [SchemaAttr(1, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> invertible.</para> /// <para>Represents the following attribute in the schema: invertible </para> /// </summary> [SchemaAttr(0, "invertible")] public BooleanValue Invertible { get { return (BooleanValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// Initializes a new instance of the CanvasTransform class. /// </summary> public CanvasTransform():base(){} /// <summary> ///Initializes a new instance of the CanvasTransform class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public CanvasTransform(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the CanvasTransform class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public CanvasTransform(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the CanvasTransform class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public CanvasTransform(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "mapping" == name) return new Mapping(); return null; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 1 == namespaceId && "id" == name) return new StringValue(); if( 0 == namespaceId && "invertible" == name) return new BooleanValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<CanvasTransform>(deep); } } /// <summary> /// <para>Defines the InkSource Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:inkSource.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>TraceFormat &lt;inkml:traceFormat></description></item> ///<item><description>SampleRate &lt;inkml:sampleRate></description></item> ///<item><description>Latency &lt;inkml:latency></description></item> ///<item><description>ActiveArea &lt;inkml:activeArea></description></item> ///<item><description>SourceProperty &lt;inkml:srcProperty></description></item> ///<item><description>ChannelProperties &lt;inkml:channelProperties></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(TraceFormat))] [ChildElementInfo(typeof(SampleRate))] [ChildElementInfo(typeof(Latency))] [ChildElementInfo(typeof(ActiveArea))] [ChildElementInfo(typeof(SourceProperty))] [ChildElementInfo(typeof(ChannelProperties))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class InkSource : OpenXmlCompositeElement { private const string tagName = "inkSource"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12733; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id","manufacturer","model","serialNo","specificationRef","description" }; private static byte[] attributeNamespaceIds = { 1,0,0,0,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: xml:id </para> /// </summary> ///<remark> xmlns:xml=http://www.w3.org/XML/1998/namespace ///</remark> [SchemaAttr(1, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> manufacturer.</para> /// <para>Represents the following attribute in the schema: manufacturer </para> /// </summary> [SchemaAttr(0, "manufacturer")] public StringValue Manufacturer { get { return (StringValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> model.</para> /// <para>Represents the following attribute in the schema: model </para> /// </summary> [SchemaAttr(0, "model")] public StringValue Model { get { return (StringValue)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// <para> serialNo.</para> /// <para>Represents the following attribute in the schema: serialNo </para> /// </summary> [SchemaAttr(0, "serialNo")] public StringValue SerialNo { get { return (StringValue)Attributes[3]; } set { Attributes[3] = value; } } /// <summary> /// <para> specificationRef.</para> /// <para>Represents the following attribute in the schema: specificationRef </para> /// </summary> [SchemaAttr(0, "specificationRef")] public StringValue SpecificationRef { get { return (StringValue)Attributes[4]; } set { Attributes[4] = value; } } /// <summary> /// <para> description.</para> /// <para>Represents the following attribute in the schema: description </para> /// </summary> [SchemaAttr(0, "description")] public StringValue Description { get { return (StringValue)Attributes[5]; } set { Attributes[5] = value; } } /// <summary> /// Initializes a new instance of the InkSource class. /// </summary> public InkSource():base(){} /// <summary> ///Initializes a new instance of the InkSource class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public InkSource(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the InkSource class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public InkSource(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the InkSource class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public InkSource(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "traceFormat" == name) return new TraceFormat(); if( 43 == namespaceId && "sampleRate" == name) return new SampleRate(); if( 43 == namespaceId && "latency" == name) return new Latency(); if( 43 == namespaceId && "activeArea" == name) return new ActiveArea(); if( 43 == namespaceId && "srcProperty" == name) return new SourceProperty(); if( 43 == namespaceId && "channelProperties" == name) return new ChannelProperties(); return null; } private static readonly string[] eleTagNames = { "traceFormat","sampleRate","latency","activeArea","srcProperty","channelProperties" }; private static readonly byte[] eleNamespaceIds = { 43,43,43,43,43,43 }; internal override string[] ElementTagNames { get{ return eleTagNames; } } internal override byte[] ElementNamespaceIds { get{ return eleNamespaceIds; } } internal override OpenXmlCompositeType OpenXmlCompositeType { get {return OpenXmlCompositeType.OneSequence;} } /// <summary> /// <para> TraceFormat.</para> /// <para> Represents the following element tag in the schema: inkml:traceFormat </para> /// </summary> /// <remark> /// xmlns:inkml = http://www.w3.org/2003/InkML /// </remark> public TraceFormat TraceFormat { get { return GetElement<TraceFormat>(0); } set { SetElement(0, value); } } /// <summary> /// <para> SampleRate.</para> /// <para> Represents the following element tag in the schema: inkml:sampleRate </para> /// </summary> /// <remark> /// xmlns:inkml = http://www.w3.org/2003/InkML /// </remark> public SampleRate SampleRate { get { return GetElement<SampleRate>(1); } set { SetElement(1, value); } } /// <summary> /// <para> Latency.</para> /// <para> Represents the following element tag in the schema: inkml:latency </para> /// </summary> /// <remark> /// xmlns:inkml = http://www.w3.org/2003/InkML /// </remark> public Latency Latency { get { return GetElement<Latency>(2); } set { SetElement(2, value); } } /// <summary> /// <para> ActiveArea.</para> /// <para> Represents the following element tag in the schema: inkml:activeArea </para> /// </summary> /// <remark> /// xmlns:inkml = http://www.w3.org/2003/InkML /// </remark> public ActiveArea ActiveArea { get { return GetElement<ActiveArea>(3); } set { SetElement(3, value); } } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 1 == namespaceId && "id" == name) return new StringValue(); if( 0 == namespaceId && "manufacturer" == name) return new StringValue(); if( 0 == namespaceId && "model" == name) return new StringValue(); if( 0 == namespaceId && "serialNo" == name) return new StringValue(); if( 0 == namespaceId && "specificationRef" == name) return new StringValue(); if( 0 == namespaceId && "description" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<InkSource>(deep); } } /// <summary> /// <para>Defines the Brush Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:brush.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>Annotation &lt;inkml:annotation></description></item> ///<item><description>AnnotationXml &lt;inkml:annotationXML></description></item> ///<item><description>BrushProperty &lt;inkml:brushProperty></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(Annotation))] [ChildElementInfo(typeof(AnnotationXml))] [ChildElementInfo(typeof(BrushProperty))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Brush : OpenXmlCompositeElement { private const string tagName = "brush"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12734; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id","brushRef" }; private static byte[] attributeNamespaceIds = { 1,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: xml:id </para> /// </summary> ///<remark> xmlns:xml=http://www.w3.org/XML/1998/namespace ///</remark> [SchemaAttr(1, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> brushRef.</para> /// <para>Represents the following attribute in the schema: brushRef </para> /// </summary> [SchemaAttr(0, "brushRef")] public StringValue BrushRef { get { return (StringValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// Initializes a new instance of the Brush class. /// </summary> public Brush():base(){} /// <summary> ///Initializes a new instance of the Brush class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Brush(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Brush class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Brush(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Brush class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Brush(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "annotation" == name) return new Annotation(); if( 43 == namespaceId && "annotationXML" == name) return new AnnotationXml(); if( 43 == namespaceId && "brushProperty" == name) return new BrushProperty(); return null; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 1 == namespaceId && "id" == name) return new StringValue(); if( 0 == namespaceId && "brushRef" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Brush>(deep); } } /// <summary> /// <para>Defines the Timestamp Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:timestamp.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Timestamp : OpenXmlLeafElement { private const string tagName = "timestamp"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12735; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id","time","timestampRef","timeString","timeOffset" }; private static byte[] attributeNamespaceIds = { 1,0,0,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: xml:id </para> /// </summary> ///<remark> xmlns:xml=http://www.w3.org/XML/1998/namespace ///</remark> [SchemaAttr(1, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> time.</para> /// <para>Represents the following attribute in the schema: time </para> /// </summary> [SchemaAttr(0, "time")] public DecimalValue Time { get { return (DecimalValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> timestampRef.</para> /// <para>Represents the following attribute in the schema: timestampRef </para> /// </summary> [SchemaAttr(0, "timestampRef")] public StringValue TimestampRef { get { return (StringValue)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// <para> timeString.</para> /// <para>Represents the following attribute in the schema: timeString </para> /// </summary> [SchemaAttr(0, "timeString")] public DateTimeValue TimeString { get { return (DateTimeValue)Attributes[3]; } set { Attributes[3] = value; } } /// <summary> /// <para> timeOffset.</para> /// <para>Represents the following attribute in the schema: timeOffset </para> /// </summary> [SchemaAttr(0, "timeOffset")] public DecimalValue TimeOffset { get { return (DecimalValue)Attributes[4]; } set { Attributes[4] = value; } } /// <summary> /// Initializes a new instance of the Timestamp class. /// </summary> public Timestamp():base(){} internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 1 == namespaceId && "id" == name) return new StringValue(); if( 0 == namespaceId && "time" == name) return new DecimalValue(); if( 0 == namespaceId && "timestampRef" == name) return new StringValue(); if( 0 == namespaceId && "timeString" == name) return new DateTimeValue(); if( 0 == namespaceId && "timeOffset" == name) return new DecimalValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Timestamp>(deep); } } /// <summary> /// <para>Defines the Trace Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:trace.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Trace : OpenXmlLeafTextElement { private const string tagName = "trace"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12736; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id","type","continuation","priorRef","contextRef","brushRef","duration","timeOffset" }; private static byte[] attributeNamespaceIds = { 1,0,0,0,0,0,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: xml:id </para> /// </summary> ///<remark> xmlns:xml=http://www.w3.org/XML/1998/namespace ///</remark> [SchemaAttr(1, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> type.</para> /// <para>Represents the following attribute in the schema: type </para> /// </summary> [SchemaAttr(0, "type")] public EnumValue<DocumentFormat.OpenXml.InkML.TraceTypeValues> Type { get { return (EnumValue<DocumentFormat.OpenXml.InkML.TraceTypeValues>)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> continuation.</para> /// <para>Represents the following attribute in the schema: continuation </para> /// </summary> [SchemaAttr(0, "continuation")] public EnumValue<DocumentFormat.OpenXml.InkML.TraceContinuationValues> Continuation { get { return (EnumValue<DocumentFormat.OpenXml.InkML.TraceContinuationValues>)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// <para> priorRef.</para> /// <para>Represents the following attribute in the schema: priorRef </para> /// </summary> [SchemaAttr(0, "priorRef")] public StringValue PriorRef { get { return (StringValue)Attributes[3]; } set { Attributes[3] = value; } } /// <summary> /// <para> contextRef.</para> /// <para>Represents the following attribute in the schema: contextRef </para> /// </summary> [SchemaAttr(0, "contextRef")] public StringValue ContextRef { get { return (StringValue)Attributes[4]; } set { Attributes[4] = value; } } /// <summary> /// <para> brushRef.</para> /// <para>Represents the following attribute in the schema: brushRef </para> /// </summary> [SchemaAttr(0, "brushRef")] public StringValue BrushRef { get { return (StringValue)Attributes[5]; } set { Attributes[5] = value; } } /// <summary> /// <para> duration.</para> /// <para>Represents the following attribute in the schema: duration </para> /// </summary> [SchemaAttr(0, "duration")] public DecimalValue Duration { get { return (DecimalValue)Attributes[6]; } set { Attributes[6] = value; } } /// <summary> /// <para> timeOffset.</para> /// <para>Represents the following attribute in the schema: timeOffset </para> /// </summary> [SchemaAttr(0, "timeOffset")] public DecimalValue TimeOffset { get { return (DecimalValue)Attributes[7]; } set { Attributes[7] = value; } } /// <summary> /// Initializes a new instance of the Trace class. /// </summary> public Trace():base(){} /// <summary> /// Initializes a new instance of the Trace class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Trace(string text):base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue(){ InnerText = text }; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 1 == namespaceId && "id" == name) return new StringValue(); if( 0 == namespaceId && "type" == name) return new EnumValue<DocumentFormat.OpenXml.InkML.TraceTypeValues>(); if( 0 == namespaceId && "continuation" == name) return new EnumValue<DocumentFormat.OpenXml.InkML.TraceContinuationValues>(); if( 0 == namespaceId && "priorRef" == name) return new StringValue(); if( 0 == namespaceId && "contextRef" == name) return new StringValue(); if( 0 == namespaceId && "brushRef" == name) return new StringValue(); if( 0 == namespaceId && "duration" == name) return new DecimalValue(); if( 0 == namespaceId && "timeOffset" == name) return new DecimalValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Trace>(deep); } } /// <summary> /// <para>Defines the TraceGroup Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:traceGroup.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>Annotation &lt;inkml:annotation></description></item> ///<item><description>AnnotationXml &lt;inkml:annotationXML></description></item> ///<item><description>Trace &lt;inkml:trace></description></item> ///<item><description>TraceGroup &lt;inkml:traceGroup></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(Annotation))] [ChildElementInfo(typeof(AnnotationXml))] [ChildElementInfo(typeof(Trace))] [ChildElementInfo(typeof(TraceGroup))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class TraceGroup : OpenXmlCompositeElement { private const string tagName = "traceGroup"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12737; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id","contextRef","brushRef" }; private static byte[] attributeNamespaceIds = { 1,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: xml:id </para> /// </summary> ///<remark> xmlns:xml=http://www.w3.org/XML/1998/namespace ///</remark> [SchemaAttr(1, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> contextRef.</para> /// <para>Represents the following attribute in the schema: contextRef </para> /// </summary> [SchemaAttr(0, "contextRef")] public StringValue ContextRef { get { return (StringValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> brushRef.</para> /// <para>Represents the following attribute in the schema: brushRef </para> /// </summary> [SchemaAttr(0, "brushRef")] public StringValue BrushRef { get { return (StringValue)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// Initializes a new instance of the TraceGroup class. /// </summary> public TraceGroup():base(){} /// <summary> ///Initializes a new instance of the TraceGroup class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public TraceGroup(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the TraceGroup class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public TraceGroup(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the TraceGroup class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public TraceGroup(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "annotation" == name) return new Annotation(); if( 43 == namespaceId && "annotationXML" == name) return new AnnotationXml(); if( 43 == namespaceId && "trace" == name) return new Trace(); if( 43 == namespaceId && "traceGroup" == name) return new TraceGroup(); return null; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 1 == namespaceId && "id" == name) return new StringValue(); if( 0 == namespaceId && "contextRef" == name) return new StringValue(); if( 0 == namespaceId && "brushRef" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<TraceGroup>(deep); } } /// <summary> /// <para>Defines the TraceView Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:traceView.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>Annotation &lt;inkml:annotation></description></item> ///<item><description>AnnotationXml &lt;inkml:annotationXML></description></item> ///<item><description>TraceView &lt;inkml:traceView></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(Annotation))] [ChildElementInfo(typeof(AnnotationXml))] [ChildElementInfo(typeof(TraceView))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class TraceView : OpenXmlCompositeElement { private const string tagName = "traceView"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12738; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id","contextRef","traceDataRef","from","to" }; private static byte[] attributeNamespaceIds = { 1,0,0,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: xml:id </para> /// </summary> ///<remark> xmlns:xml=http://www.w3.org/XML/1998/namespace ///</remark> [SchemaAttr(1, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> contextRef.</para> /// <para>Represents the following attribute in the schema: contextRef </para> /// </summary> [SchemaAttr(0, "contextRef")] public StringValue ContextRef { get { return (StringValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> traceDataRef.</para> /// <para>Represents the following attribute in the schema: traceDataRef </para> /// </summary> [SchemaAttr(0, "traceDataRef")] public StringValue TraceDataRef { get { return (StringValue)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// <para> from.</para> /// <para>Represents the following attribute in the schema: from </para> /// </summary> [SchemaAttr(0, "from")] public StringValue From { get { return (StringValue)Attributes[3]; } set { Attributes[3] = value; } } /// <summary> /// <para> to.</para> /// <para>Represents the following attribute in the schema: to </para> /// </summary> [SchemaAttr(0, "to")] public StringValue To { get { return (StringValue)Attributes[4]; } set { Attributes[4] = value; } } /// <summary> /// Initializes a new instance of the TraceView class. /// </summary> public TraceView():base(){} /// <summary> ///Initializes a new instance of the TraceView class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public TraceView(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the TraceView class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public TraceView(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the TraceView class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public TraceView(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "annotation" == name) return new Annotation(); if( 43 == namespaceId && "annotationXML" == name) return new AnnotationXml(); if( 43 == namespaceId && "traceView" == name) return new TraceView(); return null; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 1 == namespaceId && "id" == name) return new StringValue(); if( 0 == namespaceId && "contextRef" == name) return new StringValue(); if( 0 == namespaceId && "traceDataRef" == name) return new StringValue(); if( 0 == namespaceId && "from" == name) return new StringValue(); if( 0 == namespaceId && "to" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<TraceView>(deep); } } /// <summary> /// <para>Defines the Context Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:context.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>Canvas &lt;inkml:canvas></description></item> ///<item><description>CanvasTransform &lt;inkml:canvasTransform></description></item> ///<item><description>TraceFormat &lt;inkml:traceFormat></description></item> ///<item><description>InkSource &lt;inkml:inkSource></description></item> ///<item><description>Brush &lt;inkml:brush></description></item> ///<item><description>Timestamp &lt;inkml:timestamp></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(Canvas))] [ChildElementInfo(typeof(CanvasTransform))] [ChildElementInfo(typeof(TraceFormat))] [ChildElementInfo(typeof(InkSource))] [ChildElementInfo(typeof(Brush))] [ChildElementInfo(typeof(Timestamp))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Context : OpenXmlCompositeElement { private const string tagName = "context"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12739; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "id","contextRef","canvasRef","canvasTransformRef","traceFormatRef","inkSourceRef","brushRef","timestampRef" }; private static byte[] attributeNamespaceIds = { 1,0,0,0,0,0,0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> id.</para> /// <para>Represents the following attribute in the schema: xml:id </para> /// </summary> ///<remark> xmlns:xml=http://www.w3.org/XML/1998/namespace ///</remark> [SchemaAttr(1, "id")] public StringValue Id { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> contextRef.</para> /// <para>Represents the following attribute in the schema: contextRef </para> /// </summary> [SchemaAttr(0, "contextRef")] public StringValue ContextRef { get { return (StringValue)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// <para> canvasRef.</para> /// <para>Represents the following attribute in the schema: canvasRef </para> /// </summary> [SchemaAttr(0, "canvasRef")] public StringValue CanvasRef { get { return (StringValue)Attributes[2]; } set { Attributes[2] = value; } } /// <summary> /// <para> canvasTransformRef.</para> /// <para>Represents the following attribute in the schema: canvasTransformRef </para> /// </summary> [SchemaAttr(0, "canvasTransformRef")] public StringValue CanvasTransformRef { get { return (StringValue)Attributes[3]; } set { Attributes[3] = value; } } /// <summary> /// <para> traceFormatRef.</para> /// <para>Represents the following attribute in the schema: traceFormatRef </para> /// </summary> [SchemaAttr(0, "traceFormatRef")] public StringValue TraceFromatRef { get { return (StringValue)Attributes[4]; } set { Attributes[4] = value; } } /// <summary> /// <para> inkSourceRef.</para> /// <para>Represents the following attribute in the schema: inkSourceRef </para> /// </summary> [SchemaAttr(0, "inkSourceRef")] public StringValue InkSourceRef { get { return (StringValue)Attributes[5]; } set { Attributes[5] = value; } } /// <summary> /// <para> brushRef.</para> /// <para>Represents the following attribute in the schema: brushRef </para> /// </summary> [SchemaAttr(0, "brushRef")] public StringValue BrushRef { get { return (StringValue)Attributes[6]; } set { Attributes[6] = value; } } /// <summary> /// <para> timestampRef.</para> /// <para>Represents the following attribute in the schema: timestampRef </para> /// </summary> [SchemaAttr(0, "timestampRef")] public StringValue TimestampRef { get { return (StringValue)Attributes[7]; } set { Attributes[7] = value; } } /// <summary> /// Initializes a new instance of the Context class. /// </summary> public Context():base(){} /// <summary> ///Initializes a new instance of the Context class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Context(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Context class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Context(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Context class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Context(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "canvas" == name) return new Canvas(); if( 43 == namespaceId && "canvasTransform" == name) return new CanvasTransform(); if( 43 == namespaceId && "traceFormat" == name) return new TraceFormat(); if( 43 == namespaceId && "inkSource" == name) return new InkSource(); if( 43 == namespaceId && "brush" == name) return new Brush(); if( 43 == namespaceId && "timestamp" == name) return new Timestamp(); return null; } private static readonly string[] eleTagNames = { "canvas","canvasTransform","traceFormat","inkSource","brush","timestamp" }; private static readonly byte[] eleNamespaceIds = { 43,43,43,43,43,43 }; internal override string[] ElementTagNames { get{ return eleTagNames; } } internal override byte[] ElementNamespaceIds { get{ return eleNamespaceIds; } } internal override OpenXmlCompositeType OpenXmlCompositeType { get {return OpenXmlCompositeType.OneSequence;} } /// <summary> /// <para> Canvas.</para> /// <para> Represents the following element tag in the schema: inkml:canvas </para> /// </summary> /// <remark> /// xmlns:inkml = http://www.w3.org/2003/InkML /// </remark> public Canvas Canvas { get { return GetElement<Canvas>(0); } set { SetElement(0, value); } } /// <summary> /// <para> CanvasTransform.</para> /// <para> Represents the following element tag in the schema: inkml:canvasTransform </para> /// </summary> /// <remark> /// xmlns:inkml = http://www.w3.org/2003/InkML /// </remark> public CanvasTransform CanvasTransform { get { return GetElement<CanvasTransform>(1); } set { SetElement(1, value); } } /// <summary> /// <para> TraceFormat.</para> /// <para> Represents the following element tag in the schema: inkml:traceFormat </para> /// </summary> /// <remark> /// xmlns:inkml = http://www.w3.org/2003/InkML /// </remark> public TraceFormat TraceFormat { get { return GetElement<TraceFormat>(2); } set { SetElement(2, value); } } /// <summary> /// <para> InkSource.</para> /// <para> Represents the following element tag in the schema: inkml:inkSource </para> /// </summary> /// <remark> /// xmlns:inkml = http://www.w3.org/2003/InkML /// </remark> public InkSource InkSource { get { return GetElement<InkSource>(3); } set { SetElement(3, value); } } /// <summary> /// <para> Brush.</para> /// <para> Represents the following element tag in the schema: inkml:brush </para> /// </summary> /// <remark> /// xmlns:inkml = http://www.w3.org/2003/InkML /// </remark> public Brush Brush { get { return GetElement<Brush>(4); } set { SetElement(4, value); } } /// <summary> /// <para> Timestamp.</para> /// <para> Represents the following element tag in the schema: inkml:timestamp </para> /// </summary> /// <remark> /// xmlns:inkml = http://www.w3.org/2003/InkML /// </remark> public Timestamp Timestamp { get { return GetElement<Timestamp>(5); } set { SetElement(5, value); } } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 1 == namespaceId && "id" == name) return new StringValue(); if( 0 == namespaceId && "contextRef" == name) return new StringValue(); if( 0 == namespaceId && "canvasRef" == name) return new StringValue(); if( 0 == namespaceId && "canvasTransformRef" == name) return new StringValue(); if( 0 == namespaceId && "traceFormatRef" == name) return new StringValue(); if( 0 == namespaceId && "inkSourceRef" == name) return new StringValue(); if( 0 == namespaceId && "brushRef" == name) return new StringValue(); if( 0 == namespaceId && "timestampRef" == name) return new StringValue(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Context>(deep); } } /// <summary> /// <para>Defines the Definitions Class.</para> /// <para> When the object is serialized out as xml, its qualified name is inkml:definitions.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>Brush &lt;inkml:brush></description></item> ///<item><description>Canvas &lt;inkml:canvas></description></item> ///<item><description>CanvasTransform &lt;inkml:canvasTransform></description></item> ///<item><description>Context &lt;inkml:context></description></item> ///<item><description>InkSource &lt;inkml:inkSource></description></item> ///<item><description>Mapping &lt;inkml:mapping></description></item> ///<item><description>Timestamp &lt;inkml:timestamp></description></item> ///<item><description>Trace &lt;inkml:trace></description></item> ///<item><description>TraceFormat &lt;inkml:traceFormat></description></item> ///<item><description>TraceGroup &lt;inkml:traceGroup></description></item> ///<item><description>TraceView &lt;inkml:traceView></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(Brush))] [ChildElementInfo(typeof(Canvas))] [ChildElementInfo(typeof(CanvasTransform))] [ChildElementInfo(typeof(Context))] [ChildElementInfo(typeof(InkSource))] [ChildElementInfo(typeof(Mapping))] [ChildElementInfo(typeof(Timestamp))] [ChildElementInfo(typeof(Trace))] [ChildElementInfo(typeof(TraceFormat))] [ChildElementInfo(typeof(TraceGroup))] [ChildElementInfo(typeof(TraceView))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Definitions : OpenXmlCompositeElement { private const string tagName = "definitions"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 43; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12740; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } /// <summary> /// Initializes a new instance of the Definitions class. /// </summary> public Definitions():base(){} /// <summary> ///Initializes a new instance of the Definitions class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Definitions(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Definitions class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Definitions(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Definitions class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Definitions(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 43 == namespaceId && "brush" == name) return new Brush(); if( 43 == namespaceId && "canvas" == name) return new Canvas(); if( 43 == namespaceId && "canvasTransform" == name) return new CanvasTransform(); if( 43 == namespaceId && "context" == name) return new Context(); if( 43 == namespaceId && "inkSource" == name) return new InkSource(); if( 43 == namespaceId && "mapping" == name) return new Mapping(); if( 43 == namespaceId && "timestamp" == name) return new Timestamp(); if( 43 == namespaceId && "trace" == name) return new Trace(); if( 43 == namespaceId && "traceFormat" == name) return new TraceFormat(); if( 43 == namespaceId && "traceGroup" == name) return new TraceGroup(); if( 43 == namespaceId && "traceView" == name) return new TraceView(); return null; } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Definitions>(deep); } } /// <summary> /// Defines the ChannelDataTypeValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum ChannelDataTypeValues { ///<summary> ///integer. ///<para>When the item is serialized out as xml, its value is "integer".</para> ///</summary> [EnumString("integer")] Integer, ///<summary> ///decimal. ///<para>When the item is serialized out as xml, its value is "decimal".</para> ///</summary> [EnumString("decimal")] Decimal, ///<summary> ///boolean. ///<para>When the item is serialized out as xml, its value is "boolean".</para> ///</summary> [EnumString("boolean")] Boolean, } /// <summary> /// Defines the ChannelValueOrientationValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum ChannelValueOrientationValues { ///<summary> ///+ve. ///<para>When the item is serialized out as xml, its value is "+ve".</para> ///</summary> [EnumString("+ve")] PlusVe, ///<summary> ///-ve. ///<para>When the item is serialized out as xml, its value is "-ve".</para> ///</summary> [EnumString("-ve")] MinusVe, } /// <summary> /// Defines the StandardChannelPropertyNameValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum StandardChannelPropertyNameValues { ///<summary> ///threshold. ///<para>When the item is serialized out as xml, its value is "threshold".</para> ///</summary> [EnumString("threshold")] Threshold, ///<summary> ///resolution. ///<para>When the item is serialized out as xml, its value is "resolution".</para> ///</summary> [EnumString("resolution")] Resolution, ///<summary> ///quantization. ///<para>When the item is serialized out as xml, its value is "quantization".</para> ///</summary> [EnumString("quantization")] Quantization, ///<summary> ///noise. ///<para>When the item is serialized out as xml, its value is "noise".</para> ///</summary> [EnumString("noise")] Noise, ///<summary> ///accuracy. ///<para>When the item is serialized out as xml, its value is "accuracy".</para> ///</summary> [EnumString("accuracy")] Accuracy, ///<summary> ///crossCoupling. ///<para>When the item is serialized out as xml, its value is "crossCoupling".</para> ///</summary> [EnumString("crossCoupling")] CrossCoupling, ///<summary> ///skew. ///<para>When the item is serialized out as xml, its value is "skew".</para> ///</summary> [EnumString("skew")] Skew, ///<summary> ///minBandwidth. ///<para>When the item is serialized out as xml, its value is "minBandwidth".</para> ///</summary> [EnumString("minBandwidth")] MinBandwidth, ///<summary> ///peakRate. ///<para>When the item is serialized out as xml, its value is "peakRate".</para> ///</summary> [EnumString("peakRate")] PeakRate, ///<summary> ///distortion. ///<para>When the item is serialized out as xml, its value is "distortion".</para> ///</summary> [EnumString("distortion")] Distortion, } /// <summary> /// Defines the StandardBrushPropertyNameValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum StandardBrushPropertyNameValues { ///<summary> ///width. ///<para>When the item is serialized out as xml, its value is "width".</para> ///</summary> [EnumString("width")] Width, ///<summary> ///height. ///<para>When the item is serialized out as xml, its value is "height".</para> ///</summary> [EnumString("height")] Height, ///<summary> ///color. ///<para>When the item is serialized out as xml, its value is "color".</para> ///</summary> [EnumString("color")] Color, ///<summary> ///transparency. ///<para>When the item is serialized out as xml, its value is "transparency".</para> ///</summary> [EnumString("transparency")] Transparency, ///<summary> ///tip. ///<para>When the item is serialized out as xml, its value is "tip".</para> ///</summary> [EnumString("tip")] Tip, ///<summary> ///rasterOp. ///<para>When the item is serialized out as xml, its value is "rasterOp".</para> ///</summary> [EnumString("rasterOp")] RasterOp, ///<summary> ///antiAliased. ///<para>When the item is serialized out as xml, its value is "antiAliased".</para> ///</summary> [EnumString("antiAliased")] AntiAliased, ///<summary> ///fitToCurve. ///<para>When the item is serialized out as xml, its value is "fitToCurve".</para> ///</summary> [EnumString("fitToCurve")] FitToCurve, ///<summary> ///ignorePressure. ///<para>When the item is serialized out as xml, its value is "ignorePressure".</para> ///</summary> [EnumString("ignorePressure")] IgnorePressure, } /// <summary> /// Defines the StandardChannelNameValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum StandardChannelNameValues { ///<summary> ///X. ///<para>When the item is serialized out as xml, its value is "X".</para> ///</summary> [EnumString("X")] XCoordinate, ///<summary> ///Y. ///<para>When the item is serialized out as xml, its value is "Y".</para> ///</summary> [EnumString("Y")] YCoordinate, ///<summary> ///Z. ///<para>When the item is serialized out as xml, its value is "Z".</para> ///</summary> [EnumString("Z")] ZCoordinate, ///<summary> ///F. ///<para>When the item is serialized out as xml, its value is "F".</para> ///</summary> [EnumString("F")] PenTipForce, ///<summary> ///TP. ///<para>When the item is serialized out as xml, its value is "TP".</para> ///</summary> [EnumString("TP")] TangentPressure, ///<summary> ///BP. ///<para>When the item is serialized out as xml, its value is "BP".</para> ///</summary> [EnumString("BP")] ButtonPressure, ///<summary> ///S. ///<para>When the item is serialized out as xml, its value is "S".</para> ///</summary> [EnumString("S")] TipSwitchState, ///<summary> ///B1. ///<para>When the item is serialized out as xml, its value is "B1".</para> ///</summary> [EnumString("B1")] SideButton1State, ///<summary> ///B2. ///<para>When the item is serialized out as xml, its value is "B2".</para> ///</summary> [EnumString("B2")] SideButton2State, ///<summary> ///B3. ///<para>When the item is serialized out as xml, its value is "B3".</para> ///</summary> [EnumString("B3")] SideButton3State, ///<summary> ///B4. ///<para>When the item is serialized out as xml, its value is "B4".</para> ///</summary> [EnumString("B4")] SideButton4State, ///<summary> ///E. ///<para>When the item is serialized out as xml, its value is "E".</para> ///</summary> [EnumString("E")] PenInverted, ///<summary> ///OTx. ///<para>When the item is serialized out as xml, its value is "OTx".</para> ///</summary> [EnumString("OTx")] TiltAlongXAxis, ///<summary> ///OTy. ///<para>When the item is serialized out as xml, its value is "OTy".</para> ///</summary> [EnumString("OTy")] TiltAlongYAxis, ///<summary> ///OA. ///<para>When the item is serialized out as xml, its value is "OA".</para> ///</summary> [EnumString("OA")] PenAzimuthAngle, ///<summary> ///OE. ///<para>When the item is serialized out as xml, its value is "OE".</para> ///</summary> [EnumString("OE")] PenElevationAngle, ///<summary> ///OR. ///<para>When the item is serialized out as xml, its value is "OR".</para> ///</summary> [EnumString("OR")] PexAxisRotation, ///<summary> ///RP. ///<para>When the item is serialized out as xml, its value is "RP".</para> ///</summary> [EnumString("RP")] PitchRotation, ///<summary> ///RR. ///<para>When the item is serialized out as xml, its value is "RR".</para> ///</summary> [EnumString("RR")] RollRotation, ///<summary> ///RY. ///<para>When the item is serialized out as xml, its value is "RY".</para> ///</summary> [EnumString("RY")] YawRotation, ///<summary> ///C. ///<para>When the item is serialized out as xml, its value is "C".</para> ///</summary> [EnumString("C")] ColorValue, ///<summary> ///CR. ///<para>When the item is serialized out as xml, its value is "CR".</para> ///</summary> [EnumString("CR")] RedColorValue, ///<summary> ///CG. ///<para>When the item is serialized out as xml, its value is "CG".</para> ///</summary> [EnumString("CG")] GreenColorValue, ///<summary> ///CB. ///<para>When the item is serialized out as xml, its value is "CB".</para> ///</summary> [EnumString("CB")] BlueColorValue, ///<summary> ///CC. ///<para>When the item is serialized out as xml, its value is "CC".</para> ///</summary> [EnumString("CC")] CyanColorValue, ///<summary> ///CM. ///<para>When the item is serialized out as xml, its value is "CM".</para> ///</summary> [EnumString("CM")] MegentaColorValue, ///<summary> ///CY. ///<para>When the item is serialized out as xml, its value is "CY".</para> ///</summary> [EnumString("CY")] YellowColorValue, ///<summary> ///CK. ///<para>When the item is serialized out as xml, its value is "CK".</para> ///</summary> [EnumString("CK")] BlackColorValue, ///<summary> ///W. ///<para>When the item is serialized out as xml, its value is "W".</para> ///</summary> [EnumString("W")] StrokesWidth, ///<summary> ///T. ///<para>When the item is serialized out as xml, its value is "T".</para> ///</summary> [EnumString("T")] Time, ///<summary> ///SN. ///<para>When the item is serialized out as xml, its value is "SN".</para> ///</summary> [EnumString("SN")] SerialNumber, ///<summary> ///TW. ///<para>When the item is serialized out as xml, its value is "TW".</para> ///</summary> [EnumString("TW")] TouchWidth, ///<summary> ///TH. ///<para>When the item is serialized out as xml, its value is "TH".</para> ///</summary> [EnumString("TH")] TouchHeight, ///<summary> ///TC. ///<para>When the item is serialized out as xml, its value is "TC".</para> ///</summary> [EnumString("TC")] FingerTouch, } /// <summary> /// Defines the StandardLengthUnitsValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum StandardLengthUnitsValues { ///<summary> ///m. ///<para>When the item is serialized out as xml, its value is "m".</para> ///</summary> [EnumString("m")] Meter, ///<summary> ///cm. ///<para>When the item is serialized out as xml, its value is "cm".</para> ///</summary> [EnumString("cm")] Centimeter, ///<summary> ///mm. ///<para>When the item is serialized out as xml, its value is "mm".</para> ///</summary> [EnumString("mm")] Millimeter, ///<summary> ///in. ///<para>When the item is serialized out as xml, its value is "in".</para> ///</summary> [EnumString("in")] Inche, ///<summary> ///pt. ///<para>When the item is serialized out as xml, its value is "pt".</para> ///</summary> [EnumString("pt")] Point, ///<summary> ///pc. ///<para>When the item is serialized out as xml, its value is "pc".</para> ///</summary> [EnumString("pc")] Pica, ///<summary> ///em. ///<para>When the item is serialized out as xml, its value is "em".</para> ///</summary> [EnumString("em")] Em, ///<summary> ///ex. ///<para>When the item is serialized out as xml, its value is "ex".</para> ///</summary> [EnumString("ex")] Ex, } /// <summary> /// Defines the StandardPerLengthUnitsValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum StandardPerLengthUnitsValues { ///<summary> ///1/m. ///<para>When the item is serialized out as xml, its value is "1/m".</para> ///</summary> [EnumString("1/m")] PerMeter, ///<summary> ///1/cm. ///<para>When the item is serialized out as xml, its value is "1/cm".</para> ///</summary> [EnumString("1/cm")] PerCentimeter, ///<summary> ///1/mm. ///<para>When the item is serialized out as xml, its value is "1/mm".</para> ///</summary> [EnumString("1/mm")] PerMillimeter, ///<summary> ///1/in. ///<para>When the item is serialized out as xml, its value is "1/in".</para> ///</summary> [EnumString("1/in")] PerInche, ///<summary> ///1/pt. ///<para>When the item is serialized out as xml, its value is "1/pt".</para> ///</summary> [EnumString("1/pt")] PerPoint, ///<summary> ///1/pc. ///<para>When the item is serialized out as xml, its value is "1/pc".</para> ///</summary> [EnumString("1/pc")] PerPica, ///<summary> ///1/em. ///<para>When the item is serialized out as xml, its value is "1/em".</para> ///</summary> [EnumString("1/em")] PerEm, ///<summary> ///1/ex. ///<para>When the item is serialized out as xml, its value is "1/ex".</para> ///</summary> [EnumString("1/ex")] PerEx, } /// <summary> /// Defines the StandardTimeUnitsValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum StandardTimeUnitsValues { ///<summary> ///s. ///<para>When the item is serialized out as xml, its value is "s".</para> ///</summary> [EnumString("s")] Second, ///<summary> ///ms. ///<para>When the item is serialized out as xml, its value is "ms".</para> ///</summary> [EnumString("ms")] Millisecond, } /// <summary> /// Defines the StandardPerTimeUnitsValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum StandardPerTimeUnitsValues { ///<summary> ///1/s. ///<para>When the item is serialized out as xml, its value is "1/s".</para> ///</summary> [EnumString("1/s")] PerSecond, ///<summary> ///1/ms. ///<para>When the item is serialized out as xml, its value is "1/ms".</para> ///</summary> [EnumString("1/ms")] PerMillisecond, } /// <summary> /// Defines the StandardMassForceUnitsValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum StandardMassForceUnitsValues { ///<summary> ///Kg. ///<para>When the item is serialized out as xml, its value is "Kg".</para> ///</summary> [EnumString("Kg")] Kilogram, ///<summary> ///g. ///<para>When the item is serialized out as xml, its value is "g".</para> ///</summary> [EnumString("g")] Gram, ///<summary> ///mg. ///<para>When the item is serialized out as xml, its value is "mg".</para> ///</summary> [EnumString("mg")] Milligram, ///<summary> ///N. ///<para>When the item is serialized out as xml, its value is "N".</para> ///</summary> [EnumString("N")] Newton, ///<summary> ///lb. ///<para>When the item is serialized out as xml, its value is "lb".</para> ///</summary> [EnumString("lb")] Pond, } /// <summary> /// Defines the StandardPerMassForceUnitsValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum StandardPerMassForceUnitsValues { ///<summary> ///1/Kg. ///<para>When the item is serialized out as xml, its value is "1/Kg".</para> ///</summary> [EnumString("1/Kg")] PerKilogram, ///<summary> ///1/g. ///<para>When the item is serialized out as xml, its value is "1/g".</para> ///</summary> [EnumString("1/g")] PerGram, ///<summary> ///1/mg. ///<para>When the item is serialized out as xml, its value is "1/mg".</para> ///</summary> [EnumString("1/mg")] PerMilligram, ///<summary> ///1/N. ///<para>When the item is serialized out as xml, its value is "1/N".</para> ///</summary> [EnumString("1/N")] PerNewton, ///<summary> ///1/lb. ///<para>When the item is serialized out as xml, its value is "1/lb".</para> ///</summary> [EnumString("1/lb")] PerPond, } /// <summary> /// Defines the StandardAngleUnitsValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum StandardAngleUnitsValues { ///<summary> ///deg. ///<para>When the item is serialized out as xml, its value is "deg".</para> ///</summary> [EnumString("deg")] Degree, ///<summary> ///rad. ///<para>When the item is serialized out as xml, its value is "rad".</para> ///</summary> [EnumString("rad")] Radian, } /// <summary> /// Defines the StandardPerAngleUnitsValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum StandardPerAngleUnitsValues { ///<summary> ///1/deg. ///<para>When the item is serialized out as xml, its value is "1/deg".</para> ///</summary> [EnumString("1/deg")] PerDegree, ///<summary> ///1/rad. ///<para>When the item is serialized out as xml, its value is "1/rad".</para> ///</summary> [EnumString("1/rad")] PerRadian, } /// <summary> /// Defines the StandardOtherUnitsValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum StandardOtherUnitsValues { ///<summary> ///%. ///<para>When the item is serialized out as xml, its value is "%".</para> ///</summary> [EnumString("%")] Percentage, ///<summary> ///dev. ///<para>When the item is serialized out as xml, its value is "dev".</para> ///</summary> [EnumString("dev")] DeviceResolution, ///<summary> ///none. ///<para>When the item is serialized out as xml, its value is "none".</para> ///</summary> [EnumString("none")] None, } /// <summary> /// Defines the StandardPerOtherUnitsValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum StandardPerOtherUnitsValues { ///<summary> ///1/%. ///<para>When the item is serialized out as xml, its value is "1/%".</para> ///</summary> [EnumString("1/%")] PerPercentage, ///<summary> ///1/dev. ///<para>When the item is serialized out as xml, its value is "1/dev".</para> ///</summary> [EnumString("1/dev")] PerDeviceResolution, } /// <summary> /// Defines the TraceTypeValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum TraceTypeValues { ///<summary> ///penDown. ///<para>When the item is serialized out as xml, its value is "penDown".</para> ///</summary> [EnumString("penDown")] PenDown, ///<summary> ///penUp. ///<para>When the item is serialized out as xml, its value is "penUp".</para> ///</summary> [EnumString("penUp")] PenUp, ///<summary> ///indeterminate. ///<para>When the item is serialized out as xml, its value is "indeterminate".</para> ///</summary> [EnumString("indeterminate")] Indeterminate, } /// <summary> /// Defines the TraceContinuationValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum TraceContinuationValues { ///<summary> ///begin. ///<para>When the item is serialized out as xml, its value is "begin".</para> ///</summary> [EnumString("begin")] Begin, ///<summary> ///end. ///<para>When the item is serialized out as xml, its value is "end".</para> ///</summary> [EnumString("end")] End, ///<summary> ///middle. ///<para>When the item is serialized out as xml, its value is "middle".</para> ///</summary> [EnumString("middle")] Middle, } /// <summary> /// Defines the RasterOperationValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum RasterOperationValues { ///<summary> ///black. ///<para>When the item is serialized out as xml, its value is "black".</para> ///</summary> [EnumString("black")] Black, ///<summary> ///notMergePen. ///<para>When the item is serialized out as xml, its value is "notMergePen".</para> ///</summary> [EnumString("notMergePen")] NotMergePen, ///<summary> ///maskNotPen. ///<para>When the item is serialized out as xml, its value is "maskNotPen".</para> ///</summary> [EnumString("maskNotPen")] MaskNotPen, ///<summary> ///notCopyPen. ///<para>When the item is serialized out as xml, its value is "notCopyPen".</para> ///</summary> [EnumString("notCopyPen")] NotCopyPen, ///<summary> ///maskPenNot. ///<para>When the item is serialized out as xml, its value is "maskPenNot".</para> ///</summary> [EnumString("maskPenNot")] MaskPenNot, ///<summary> ///not. ///<para>When the item is serialized out as xml, its value is "not".</para> ///</summary> [EnumString("not")] Not, ///<summary> ///xOrPen. ///<para>When the item is serialized out as xml, its value is "xOrPen".</para> ///</summary> [EnumString("xOrPen")] XOrPen, ///<summary> ///notMaskPen. ///<para>When the item is serialized out as xml, its value is "notMaskPen".</para> ///</summary> [EnumString("notMaskPen")] NotMaskPen, ///<summary> ///maskPen. ///<para>When the item is serialized out as xml, its value is "maskPen".</para> ///</summary> [EnumString("maskPen")] MaskPen, ///<summary> ///notXOrPen. ///<para>When the item is serialized out as xml, its value is "notXOrPen".</para> ///</summary> [EnumString("notXOrPen")] NotXOrPen, ///<summary> ///noOperation. ///<para>When the item is serialized out as xml, its value is "noOperation".</para> ///</summary> [EnumString("noOperation")] NoOperation, ///<summary> ///mergeNotPen. ///<para>When the item is serialized out as xml, its value is "mergeNotPen".</para> ///</summary> [EnumString("mergeNotPen")] MergeNotPen, ///<summary> ///copyPen. ///<para>When the item is serialized out as xml, its value is "copyPen".</para> ///</summary> [EnumString("copyPen")] CopyPen, ///<summary> ///mergePenNot. ///<para>When the item is serialized out as xml, its value is "mergePenNot".</para> ///</summary> [EnumString("mergePenNot")] MergePenNot, ///<summary> ///mergePen. ///<para>When the item is serialized out as xml, its value is "mergePen".</para> ///</summary> [EnumString("mergePen")] MergePen, ///<summary> ///white. ///<para>When the item is serialized out as xml, its value is "white".</para> ///</summary> [EnumString("white")] White, } /// <summary> /// Defines the PenTipShapeValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum PenTipShapeValues { ///<summary> ///ellipse. ///<para>When the item is serialized out as xml, its value is "ellipse".</para> ///</summary> [EnumString("ellipse")] Ellipse, ///<summary> ///rectangle. ///<para>When the item is serialized out as xml, its value is "rectangle".</para> ///</summary> [EnumString("rectangle")] Rectangle, ///<summary> ///drop. ///<para>When the item is serialized out as xml, its value is "drop".</para> ///</summary> [EnumString("drop")] Drop, } /// <summary> /// Defines the MappingTypeValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum MappingTypeValues { ///<summary> ///identity. ///<para>When the item is serialized out as xml, its value is "identity".</para> ///</summary> [EnumString("identity")] Identity, ///<summary> ///lookup. ///<para>When the item is serialized out as xml, its value is "lookup".</para> ///</summary> [EnumString("lookup")] Lookup, ///<summary> ///affine. ///<para>When the item is serialized out as xml, its value is "affine".</para> ///</summary> [EnumString("affine")] Affine, ///<summary> ///mathml. ///<para>When the item is serialized out as xml, its value is "mathml".</para> ///</summary> [EnumString("mathml")] MathML, ///<summary> ///product. ///<para>When the item is serialized out as xml, its value is "product".</para> ///</summary> [EnumString("product")] Product, ///<summary> ///unknown. ///<para>When the item is serialized out as xml, its value is "unknown".</para> ///</summary> [EnumString("unknown")] Unknown, } /// <summary> /// Defines the TableApplyValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum TableApplyValues { ///<summary> ///absolute. ///<para>When the item is serialized out as xml, its value is "absolute".</para> ///</summary> [EnumString("absolute")] Absolute, ///<summary> ///relative. ///<para>When the item is serialized out as xml, its value is "relative".</para> ///</summary> [EnumString("relative")] Relative, } /// <summary> /// Defines the TableInterpolationValues enumeration. /// </summary> [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public enum TableInterpolationValues { ///<summary> ///floor. ///<para>When the item is serialized out as xml, its value is "floor".</para> ///</summary> [EnumString("floor")] Floor, ///<summary> ///middle. ///<para>When the item is serialized out as xml, its value is "middle".</para> ///</summary> [EnumString("middle")] Middle, ///<summary> ///ceiling. ///<para>When the item is serialized out as xml, its value is "ceiling".</para> ///</summary> [EnumString("ceiling")] Ceiling, ///<summary> ///linear. ///<para>When the item is serialized out as xml, its value is "linear".</para> ///</summary> [EnumString("linear")] Linear, ///<summary> ///cubic. ///<para>When the item is serialized out as xml, its value is "cubic".</para> ///</summary> [EnumString("cubic")] Cubic, } }
28.156602
184
0.626945
[ "MIT" ]
coderIML/Open-XML-SDK.net
src/DocumentFormat.OpenXml/GeneratedCode/www_w3_org_2003_InkML.g.cs
167,393
C#
using Microsoft.Xna.Framework; using System; using System.Collections.Generic; namespace MagratheaCore.Environment { public class StarDome { #region Constants private const int NumberOfStars = 2000; private const float Radius = 10; #endregion #region Properties public List<Star> Stars { get; private set; } #endregion #region Constructors public StarDome(Random random) { CalculateContents(random); } #endregion #region Private methods private void CalculateContents(Random random) { Stars = new List<Star>(); for (int i = 0; i < NumberOfStars; i++) { float altitudeParameter = (float)(2*random.NextDouble() - 1); float azimuthAngle = (float)(2*Math.PI*random.NextDouble()); float azimuthMultiplier = (float)Math.Sqrt(1 - altitudeParameter*altitudeParameter); Vector3 domePosition = new Vector3((float)(azimuthMultiplier*Math.Sin(azimuthAngle)), altitudeParameter, (float)(-azimuthMultiplier*Math.Cos(azimuthAngle)))*Radius; float colourValue = (float)(0.1f + 0.4f*random.NextDouble()); Star star = new Star(domePosition, new Color(colourValue, colourValue, colourValue)); Stars.Add(star); } } #endregion } }
22.333333
168
0.710614
[ "MIT" ]
george7378/magrathea
MagratheaCore/Environment/StarDome.cs
1,208
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs.Script.BindingExtensions; using Microsoft.Azure.WebJobs.Script.Config; using Microsoft.Azure.WebJobs.Script.ExtensionBundle; using Microsoft.Azure.WebJobs.Script.Models; using Microsoft.Azure.WebJobs.Script.Properties; using Microsoft.Azure.WebJobs.Script.WebHost.Models; using Microsoft.Azure.WebJobs.Script.WebHost.Security.Authorization.Policies; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Microsoft.Azure.WebJobs.Script.WebHost.Controllers { [Authorize(Policy = PolicyNames.AdminAuthLevel)] public class ExtensionsController : Controller { private readonly IExtensionsManager _extensionsManager; private readonly ScriptSettingsManager _settingsManager; private readonly IExtensionBundleManager _extensionBundleManager; private readonly IEnvironment _environment; private readonly IOptions<ScriptApplicationHostOptions> _applicationHostOptions; public ExtensionsController(IExtensionsManager extensionsManager, ScriptSettingsManager settingsManager, IExtensionBundleManager extensionBundleManager, IEnvironment environment, IOptions<ScriptApplicationHostOptions> applicationHostOptions) { _extensionsManager = extensionsManager ?? throw new ArgumentNullException(nameof(extensionsManager)); _settingsManager = settingsManager ?? throw new ArgumentNullException(nameof(settingsManager)); _extensionBundleManager = extensionBundleManager ?? throw new ArgumentNullException(nameof(extensionBundleManager)); _applicationHostOptions = applicationHostOptions ?? throw new ArgumentNullException(nameof(applicationHostOptions)); _environment = environment; } [HttpGet] [Route("admin/host/extensions")] public async Task<IActionResult> Get() { IEnumerable<ExtensionPackageReference> extensions = await _extensionsManager.GetExtensions(); var extensionsContent = new { extensions = extensions }; var result = ApiModelUtility.CreateApiModel(extensionsContent, Request); return Ok(result); } [HttpPost] [Route("admin/host/extensions")] public Task<IActionResult> Post([FromBody]ExtensionPackageReferenceWithActions package) => InstallExtension(package); [HttpPut("{id}")] [Route("admin/host/extensions")] public Task<IActionResult> Put(int id, [FromBody]ExtensionPackageReferenceWithActions package) => InstallExtension(package); [HttpDelete] [Route("admin/host/extensions/{id}")] public async Task<IActionResult> Delete(string id) { if (_extensionBundleManager.IsExtensionBundleConfigured()) { return BadRequest(Resources.ExtensionBundleBadRequestDelete); } if (!_environment.IsPersistentFileSystemAvailable()) { return BadRequest(Resources.ErrorDeletingExtension); } // TODO: Check if we have an active job var job = await CreateJob(new ExtensionPackageReference() { Id = id, Version = string.Empty }); await _extensionsManager.DeleteExtensions(id) .ContinueWith(t => ProcessJobTaskResult(t, job.Id)); var apiModel = ApiModelUtility.CreateApiModel(job, Request, $"jobs/{job.Id}"); string action = $"{Request.Scheme}://{Request.Host.ToUriComponent()}{Url.Action(nameof(GetJobs), "Extensions", new { id = job.Id })}{Request.QueryString}"; return Accepted(action, apiModel); } [HttpGet] [Route("admin/host/extensions/jobs/{id}")] public async Task<IActionResult> GetJobs(string id) { ExtensionsRestoreJob job = await GetJob(id); if (job == null) { return NotFound(); } var apiModel = ApiModelUtility.CreateApiModel(job, Request); return Ok(apiModel); } [HttpGet] [Route("admin/host/extensions/jobs")] public async Task<IActionResult> GetJobs() { IEnumerable<ExtensionsRestoreJob> jobs = await GetInProgressJobs(); var jobContent = new { jobs }; var result = ApiModelUtility.CreateApiModel(jobContent, Request); return Ok(result); } public async Task<IActionResult> InstallExtension(ExtensionPackageReferenceWithActions package, bool verifyConflict = true) { if (package == null) { return BadRequest(); } if (_extensionBundleManager.IsExtensionBundleConfigured()) { return BadRequest(Resources.ExtensionBundleBadRequestInstall); } if (!_environment.IsPersistentFileSystemAvailable()) { return BadRequest(Resources.ErrorInstallingExtension); } if (verifyConflict) { // If a different version of this extension is already installed, conflict: var extensions = await _extensionsManager.GetExtensions(); if (extensions.Any(e => e.Id.Equals(package.Id) && !e.Version.Equals(package.Version))) { return StatusCode(StatusCodes.Status409Conflict); } } ExtensionsRestoreJob job = await CreateJob(package); string jobId = job.Id; Enum.TryParse(package.PostInstallActions, true, out ExtensionPostInstallActions postInstallActions); var addTask = _extensionsManager.AddExtensions(package) .ContinueWith(t => ProcessJobTaskResult(t, jobId, postInstallActions)); var apiModel = ApiModelUtility.CreateApiModel(job, Request, $"jobs/{job.Id}"); string action = $"{Request.Scheme}://{Request.Host.ToUriComponent()}{Url.Action(nameof(GetJobs), "Extensions", new { id = job.Id })}{Request.QueryString}"; return Accepted(action, apiModel); } private async Task ProcessJobTaskResult(Task jobTask, string jobId, ExtensionPostInstallActions postInstallActions = ExtensionPostInstallActions.None) { ExtensionsRestoreJob job = await GetJob(jobId); if (job == null) { return; } if (jobTask.IsFaulted) { job.Status = ExtensionsRestoreStatus.Failed; job.Error = jobTask.Exception.InnerException?.Message; } else { job.Status = ExtensionsRestoreStatus.Succeeded; } job.EndTime = DateTimeOffset.Now; if (postInstallActions.HasFlag(ExtensionPostInstallActions.BringAppOnline)) { await FileMonitoringService.SetAppOfflineState(_applicationHostOptions.Value.ScriptPath, false); } await SaveJob(job); } private async Task<ExtensionsRestoreJob> CreateJob(ExtensionPackageReference package) { var job = new ExtensionsRestoreJob() { Properties = new Dictionary<string, string>() { { "id", package.Id }, { "version", package.Version } } }; await SaveJob(job); return job; } private async Task SaveJob(ExtensionsRestoreJob job) { string jobPath = Path.Combine(GetJobBasePath(), $"{job.Id}.json"); Directory.CreateDirectory(Path.GetDirectoryName(jobPath)); await FileUtility.WriteAsync(jobPath, JsonConvert.SerializeObject(job)); } private string GetJobBasePath() { string home = _settingsManager.GetSetting(EnvironmentSettingNames.AzureWebsiteHomePath); string basePath = null; if (!string.IsNullOrEmpty(home)) { basePath = Path.Combine(home, "data", "Functions", "extensions"); } else { basePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".azurefunctions", "extensions"); } FileUtility.EnsureDirectoryExists(basePath); return basePath; } private async Task<ExtensionsRestoreJob> GetJob(string jobId) { string path = Path.Combine(GetJobBasePath(), $"{jobId}.json"); if (System.IO.File.Exists(path)) { string json = await FileUtility.ReadAsync(path); return JsonConvert.DeserializeObject<ExtensionsRestoreJob>(json); } return null; } private async Task<IEnumerable<ExtensionsRestoreJob>> GetInProgressJobs() { var jobPaths = await FileUtility.GetFilesAsync(GetJobBasePath(), "*.json"); List<ExtensionsRestoreJob> jobs = new List<ExtensionsRestoreJob>(); foreach (var jobPath in jobPaths) { if (System.IO.File.Exists(jobPath)) { string json = await FileUtility.ReadAsync(jobPath); var job = JsonConvert.DeserializeObject<ExtensionsRestoreJob>(json); if (job.Status == ExtensionsRestoreStatus.Started) { jobs.Add(job); } } } return jobs; } } }
38.254753
249
0.621012
[ "Apache-2.0", "MIT" ]
AnatoliB/azure-functions-host
src/WebJobs.Script.WebHost/Controllers/ExtensionsController.cs
10,063
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.DotNet.RemoteExecutor; using Xunit; public class Outside { public class Inside { public void GenericMethod<T>() { } public void TwoGenericMethod<T, U>() { } } public void GenericMethod<T>() { } public void TwoGenericMethod<T, U>() { } } public class Outside<T> { public class Inside<U> { public void GenericMethod<V>() { } public void TwoGenericMethod<V, W>() { } } public void GenericMethod<U>() { } public void TwoGenericMethod<U, V>() { } } namespace System.Tests { [ActiveIssue("https://github.com/dotnet/runtime/issues/34328", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public partial class TypeTests { private static readonly IList<Type> NonArrayBaseTypes; static TypeTests() { NonArrayBaseTypes = new List<Type>() { typeof(int), typeof(void), typeof(int*), typeof(Outside), typeof(Outside<int>), typeof(Outside<>).GetTypeInfo().GenericTypeParameters[0], new object().GetType().GetType() }; if (PlatformDetection.IsWindows) { NonArrayBaseTypes.Add(Type.GetTypeFromCLSID(default(Guid))); } } [Fact] public void FilterName_Get_ReturnsExpected() { Assert.NotNull(Type.FilterName); Assert.Same(Type.FilterName, Type.FilterName); Assert.NotSame(Type.FilterName, Type.FilterNameIgnoreCase); } [Theory] [InlineData("FilterName_Invoke_DelegateFiltersExpectedMembers", true)] [InlineData(" FilterName_Invoke_DelegateFiltersExpectedMembers ", true)] [InlineData("*", true)] [InlineData(" * ", true)] [InlineData(" Filter* ", true)] [InlineData("FilterName_Invoke_DelegateFiltersExpectedMembe*", true)] [InlineData("FilterName_Invoke_DelegateFiltersExpectedMember*", true)] [InlineData("filterName_Invoke_DelegateFiltersExpectedMembers", false)] [InlineData("FilterName_Invoke_DelegateFiltersExpectedMemberss*", false)] [InlineData("FilterName", false)] [InlineData("*FilterName", false)] [InlineData("", false)] [InlineData(" ", false)] public void FilterName_Invoke_DelegateFiltersExpectedMembers(string filterCriteria, bool expected) { MethodInfo mi = typeof(TypeTests).GetMethod(nameof(FilterName_Invoke_DelegateFiltersExpectedMembers)); Assert.Equal(expected, Type.FilterName(mi, filterCriteria)); } [Fact] public void FilterName_InvalidFilterCriteria_ThrowsInvalidFilterCriteriaException() { MethodInfo mi = typeof(TypeTests).GetMethod(nameof(FilterName_Invoke_DelegateFiltersExpectedMembers)); Assert.Throws<InvalidFilterCriteriaException>(() => Type.FilterName(mi, null)); Assert.Throws<InvalidFilterCriteriaException>(() => Type.FilterName(mi, new object())); } [Fact] public void FilterNameIgnoreCase_Get_ReturnsExpected() { Assert.NotNull(Type.FilterNameIgnoreCase); Assert.Same(Type.FilterNameIgnoreCase, Type.FilterNameIgnoreCase); Assert.NotSame(Type.FilterNameIgnoreCase, Type.FilterName); } [Theory] [InlineData("FilterNameIgnoreCase_Invoke_DelegateFiltersExpectedMembers", true)] [InlineData("filternameignorecase_invoke_delegatefiltersexpectedmembers", true)] [InlineData(" filterNameIgnoreCase_Invoke_DelegateFiltersexpectedMembers ", true)] [InlineData("*", true)] [InlineData(" * ", true)] [InlineData(" fIlTeR* ", true)] [InlineData("FilterNameIgnoreCase_invoke_delegateFiltersExpectedMembe*", true)] [InlineData("FilterNameIgnoreCase_invoke_delegateFiltersExpectedMember*", true)] [InlineData("filterName_Invoke_DelegateFiltersExpectedMembers", false)] [InlineData("filterNameIgnoreCase_Invoke_DelegateFiltersExpectedMemberss", false)] [InlineData("FilterNameIgnoreCase_Invoke_DelegateFiltersExpectedMemberss*", false)] [InlineData("filterNameIgnoreCase", false)] [InlineData("*FilterNameIgnoreCase", false)] [InlineData("", false)] [InlineData(" ", false)] public void FilterNameIgnoreCase_Invoke_DelegateFiltersExpectedMembers(string filterCriteria, bool expected) { MethodInfo mi = typeof(TypeTests).GetMethod(nameof(FilterNameIgnoreCase_Invoke_DelegateFiltersExpectedMembers)); Assert.Equal(expected, Type.FilterNameIgnoreCase(mi, filterCriteria)); } [Fact] public void FilterNameIgnoreCase_InvalidFilterCriteria_ThrowsInvalidFilterCriteriaException() { MethodInfo mi = typeof(TypeTests).GetMethod(nameof(FilterName_Invoke_DelegateFiltersExpectedMembers)); Assert.Throws<InvalidFilterCriteriaException>(() => Type.FilterNameIgnoreCase(mi, null)); Assert.Throws<InvalidFilterCriteriaException>(() => Type.FilterNameIgnoreCase(mi, new object())); } public static IEnumerable<object[]> FindMembers_TestData() { yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterName, "HelloWorld", 0 }; yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterName, "FilterName_Invoke_DelegateFiltersExpectedMembers", 1 }; yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterName, "FilterName_Invoke_Delegate*", 1 }; yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterName, "filterName_Invoke_Delegate*", 0 }; yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterNameIgnoreCase, "HelloWorld", 0 }; yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterNameIgnoreCase, "FilterName_Invoke_DelegateFiltersExpectedMembers", 1 }; yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterNameIgnoreCase, "FilterName_Invoke_Delegate*", 1 }; yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterNameIgnoreCase, "filterName_Invoke_Delegate*", 1 }; } [Theory] [MemberData(nameof(FindMembers_TestData))] public void FindMembers_Invoke_ReturnsExpected(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria, int expectedLength) { Assert.Equal(expectedLength, typeof(TypeTests).FindMembers(memberType, bindingAttr, filter, filterCriteria).Length); } [Theory] [InlineData(typeof(int), typeof(int))] [InlineData(typeof(int[]), typeof(int[]))] [InlineData(typeof(Outside<int>), typeof(Outside<int>))] public void TypeHandle(Type t1, Type t2) { RuntimeTypeHandle r1 = t1.TypeHandle; RuntimeTypeHandle r2 = t2.TypeHandle; Assert.Equal(r1, r2); Assert.Equal(t1, Type.GetTypeFromHandle(r1)); Assert.Equal(t1, Type.GetTypeFromHandle(r2)); } [Fact] public void GetTypeFromDefaultHandle() { Assert.Null(Type.GetTypeFromHandle(default(RuntimeTypeHandle))); } [Theory] [InlineData(typeof(int[]), 1)] [InlineData(typeof(int[,,]), 3)] public void GetArrayRank_Get_ReturnsExpected(Type t, int expected) { Assert.Equal(expected, t.GetArrayRank()); } [Theory] [InlineData(typeof(int))] [InlineData(typeof(IList<int>))] [InlineData(typeof(IList<>))] public void GetArrayRank_NonArrayType_ThrowsArgumentException(Type t) { AssertExtensions.Throws<ArgumentException>(null, () => t.GetArrayRank()); } [Theory] [InlineData(typeof(int), typeof(int[]))] public void MakeArrayType_Invoke_ReturnsExpected(Type t, Type tArrayExpected) { Type tArray = t.MakeArrayType(); Assert.Equal(tArrayExpected, tArray); Assert.Equal(t, tArray.GetElementType()); Assert.True(tArray.IsArray); Assert.True(tArray.HasElementType); string s1 = t.ToString(); string s2 = tArray.ToString(); Assert.Equal(s2, s1 + "[]"); } [Theory] [InlineData(typeof(int))] public void MakeByRefType_Invoke_ReturnsExpected(Type t) { Type tRef1 = t.MakeByRefType(); Type tRef2 = t.MakeByRefType(); Assert.Equal(tRef1, tRef2); Assert.True(tRef1.IsByRef); Assert.True(tRef1.HasElementType); Assert.Equal(t, tRef1.GetElementType()); string s1 = t.ToString(); string s2 = tRef1.ToString(); Assert.Equal(s2, s1 + "&"); } [Theory] [InlineData("System.Nullable`1[System.Int32]", typeof(int?))] [InlineData("System.Int32*", typeof(int*))] [InlineData("System.Int32**", typeof(int**))] [InlineData("Outside`1", typeof(Outside<>))] [InlineData("Outside`1+Inside`1", typeof(Outside<>.Inside<>))] [InlineData("Outside[]", typeof(Outside[]))] [InlineData("Outside[,,]", typeof(Outside[,,]))] [InlineData("Outside[][]", typeof(Outside[][]))] [InlineData("Outside`1[System.Nullable`1[System.Boolean]]", typeof(Outside<bool?>))] public void GetTypeByName_ValidType_ReturnsExpected(string typeName, Type expectedType) { Assert.Equal(expectedType, Type.GetType(typeName, throwOnError: false, ignoreCase: false)); Assert.Equal(expectedType, Type.GetType(typeName.ToLower(), throwOnError: false, ignoreCase: true)); } [Theory] [InlineData("system.nullable`1[system.int32]", typeof(TypeLoadException), false)] [InlineData("System.NonExistingType", typeof(TypeLoadException), false)] [InlineData("", typeof(TypeLoadException), false)] [InlineData("System.Int32[,*,]", typeof(ArgumentException), false)] [InlineData("Outside`2", typeof(TypeLoadException), false)] [InlineData("Outside`1[System.Boolean, System.Int32]", typeof(ArgumentException), true)] public void GetTypeByName_Invalid(string typeName, Type expectedException, bool alwaysThrowsException) { if (!alwaysThrowsException) { Assert.Null(Type.GetType(typeName, throwOnError: false, ignoreCase: false)); } Assert.Throws(expectedException, () => Type.GetType(typeName, throwOnError: true, ignoreCase: false)); } [Fact] public void GetTypeByName_InvokeViaReflection_Success() { MethodInfo method = typeof(Type).GetMethod("GetType", new[] { typeof(string) }); object result = method.Invoke(null, new object[] { "System.Tests.TypeTests" }); Assert.Equal(typeof(TypeTests), result); } [Fact] public void Delimiter() { Assert.Equal('.', Type.Delimiter); } [Theory] [InlineData(typeof(bool), TypeCode.Boolean)] [InlineData(typeof(byte), TypeCode.Byte)] [InlineData(typeof(char), TypeCode.Char)] [InlineData(typeof(DateTime), TypeCode.DateTime)] [InlineData(typeof(decimal), TypeCode.Decimal)] [InlineData(typeof(double), TypeCode.Double)] [InlineData(null, TypeCode.Empty)] [InlineData(typeof(short), TypeCode.Int16)] [InlineData(typeof(int), TypeCode.Int32)] [InlineData(typeof(long), TypeCode.Int64)] [InlineData(typeof(object), TypeCode.Object)] [InlineData(typeof(System.Nullable), TypeCode.Object)] [InlineData(typeof(Nullable<int>), TypeCode.Object)] [InlineData(typeof(Dictionary<,>), TypeCode.Object)] [InlineData(typeof(Exception), TypeCode.Object)] [InlineData(typeof(sbyte), TypeCode.SByte)] [InlineData(typeof(float), TypeCode.Single)] [InlineData(typeof(string), TypeCode.String)] [InlineData(typeof(ushort), TypeCode.UInt16)] [InlineData(typeof(uint), TypeCode.UInt32)] [InlineData(typeof(ulong), TypeCode.UInt64)] public void GetTypeCode_ValidType_ReturnsExpected(Type t, TypeCode typeCode) { Assert.Equal(typeCode, Type.GetTypeCode(t)); } [Fact] public void ReflectionOnlyGetType() { Assert.Throws<PlatformNotSupportedException>(() => Type.ReflectionOnlyGetType(null, true, false)); Assert.Throws<PlatformNotSupportedException>(() => Type.ReflectionOnlyGetType("", true, true)); Assert.Throws<PlatformNotSupportedException>(() => Type.ReflectionOnlyGetType("System.Tests.TypeTests", false, true)); } [Fact] public void IsSZArray_FalseForNonArrayTypes() { foreach (Type type in NonArrayBaseTypes) { Assert.False(type.IsSZArray); } } [Fact] public void IsSZArray_TrueForSZArrayTypes() { foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType())) { Assert.True(type.IsSZArray); } } [Fact] public void IsSZArray_FalseForVariableBoundArrayTypes() { foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(1))) { Assert.False(type.IsSZArray); } foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(2))) { Assert.False(type.IsSZArray); } } [Fact] public void IsSZArray_FalseForNonArrayByRefType() { Assert.False(typeof(int).MakeByRefType().IsSZArray); } [Fact] public void IsSZArray_FalseForByRefSZArrayType() { Assert.False(typeof(int[]).MakeByRefType().IsSZArray); } [Fact] public void IsSZArray_FalseForByRefVariableArrayType() { Assert.False(typeof(int[,]).MakeByRefType().IsSZArray); } [Fact] public void IsVariableBoundArray_FalseForNonArrayTypes() { foreach (Type type in NonArrayBaseTypes) { Assert.False(type.IsVariableBoundArray); } } [Fact] public void IsVariableBoundArray_FalseForSZArrayTypes() { foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType())) { Assert.False(type.IsVariableBoundArray); } } [Fact] public void IsVariableBoundArray_TrueForVariableBoundArrayTypes() { foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(1))) { Assert.True(type.IsVariableBoundArray); } foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(2))) { Assert.True(type.IsVariableBoundArray); } } [Fact] public void IsVariableBoundArray_FalseForNonArrayByRefType() { Assert.False(typeof(int).MakeByRefType().IsVariableBoundArray); } [Fact] public void IsVariableBoundArray_FalseForByRefSZArrayType() { Assert.False(typeof(int[]).MakeByRefType().IsVariableBoundArray); } [Fact] public void IsVariableBoundArray_FalseForByRefVariableArrayType() { Assert.False(typeof(int[,]).MakeByRefType().IsVariableBoundArray); } [Theory] [MemberData(nameof(DefinedTypes))] public void IsTypeDefinition_True(Type type) { Assert.True(type.IsTypeDefinition); } [Theory] [MemberData(nameof(NotDefinedTypes))] public void IsTypeDefinition_False(Type type) { Assert.False(type.IsTypeDefinition); } // In the unlikely event we ever add new values to the CorElementType enumeration, CoreCLR will probably miss it because of the way IsTypeDefinition // works. It's likely that such a type will live in the core assembly so to improve our chances of catching this situation, test IsTypeDefinition // on every type exposed out of that assembly. // // Skipping this on .NET Native because: // - We really don't want to opt in all the metadata in System.Private.CoreLib // - The .NET Native implementation of IsTypeDefinition is not the one that works by enumerating selected values off CorElementType. // It has much less need of a test like this. [Fact] public void IsTypeDefinition_AllDefinedTypesInCoreAssembly() { foreach (Type type in typeof(object).Assembly.DefinedTypes) { Assert.True(type.IsTypeDefinition, "IsTypeDefinition expected to be true for type " + type); } } public static IEnumerable<object[]> DefinedTypes { get { yield return new object[] { typeof(void) }; yield return new object[] { typeof(int) }; yield return new object[] { typeof(Outside) }; yield return new object[] { typeof(Outside.Inside) }; yield return new object[] { typeof(Outside<>) }; yield return new object[] { typeof(IEnumerable<>) }; yield return new object[] { 3.GetType().GetType() }; // This yields a reflection-blocked type on .NET Native - which is implemented separately if (PlatformDetection.IsWindows) yield return new object[] { Type.GetTypeFromCLSID(default(Guid)) }; } } public static IEnumerable<object[]> NotDefinedTypes { get { Type theT = typeof(Outside<>).GetTypeInfo().GenericTypeParameters[0]; yield return new object[] { typeof(int[]) }; yield return new object[] { theT.MakeArrayType(1) }; // Using an open type as element type gets around .NET Native nonsupport of rank-1 multidim arrays yield return new object[] { typeof(int[,]) }; yield return new object[] { typeof(int).MakeByRefType() }; yield return new object[] { typeof(int).MakePointerType() }; yield return new object[] { typeof(Outside<int>) }; yield return new object[] { typeof(Outside<int>.Inside<int>) }; yield return new object[] { theT }; } } [Theory] [MemberData(nameof(IsByRefLikeTestData))] public static void TestIsByRefLike(Type type, bool expected) { Assert.Equal(expected, type.IsByRefLike); } public static IEnumerable<object[]> IsByRefLikeTestData { get { Type theT = typeof(Outside<>).GetTypeInfo().GenericTypeParameters[0]; yield return new object[] { typeof(ArgIterator), true }; yield return new object[] { typeof(ByRefLikeStruct), true }; yield return new object[] { typeof(RegularStruct), false }; yield return new object[] { typeof(RuntimeArgumentHandle), true }; yield return new object[] { typeof(Span<>), true }; yield return new object[] { typeof(Span<>).MakeGenericType(theT), true }; yield return new object[] { typeof(Span<int>), true }; yield return new object[] { typeof(Span<int>).MakeByRefType(), false }; yield return new object[] { typeof(Span<int>).MakePointerType(), false }; yield return new object[] { typeof(TypedReference), true }; yield return new object[] { theT, false }; yield return new object[] { typeof(int[]), false }; yield return new object[] { typeof(int[,]), false }; yield return new object[] { typeof(object), false }; if (PlatformDetection.IsWindows) // GetTypeFromCLSID is Windows only { yield return new object[] { Type.GetTypeFromCLSID(default(Guid)), false }; } } } private ref struct ByRefLikeStruct { public ByRefLikeStruct(int dummy) { S = default(Span<int>); } public Span<int> S; } private struct RegularStruct { } [Theory] [MemberData(nameof(IsGenericParameterTestData))] public static void TestIsGenericParameter(Type type, bool isGenericParameter, bool isGenericTypeParameter, bool isGenericMethodParameter) { Assert.Equal(isGenericParameter, type.IsGenericParameter); Assert.Equal(isGenericTypeParameter, type.IsGenericTypeParameter); Assert.Equal(isGenericMethodParameter, type.IsGenericMethodParameter); } public static IEnumerable<object[]> IsGenericParameterTestData { get { yield return new object[] { typeof(void), false, false, false }; yield return new object[] { typeof(int), false, false, false }; yield return new object[] { typeof(int[]), false, false, false }; yield return new object[] { typeof(int).MakeArrayType(1), false, false, false }; yield return new object[] { typeof(int[,]), false, false, false }; yield return new object[] { typeof(int).MakeByRefType(), false, false, false }; yield return new object[] { typeof(int).MakePointerType(), false, false, false }; yield return new object[] { typeof(DummyGenericClassForTypeTests<>), false, false, false }; yield return new object[] { typeof(DummyGenericClassForTypeTests<int>), false, false, false }; if (PlatformDetection.IsWindows) // GetTypeFromCLSID is Windows only { yield return new object[] { Type.GetTypeFromCLSID(default(Guid)), false, false, false }; } Type theT = typeof(Outside<>).GetTypeInfo().GenericTypeParameters[0]; yield return new object[] { theT, true, true, false }; Type theM = typeof(TypeTests).GetMethod(nameof(GenericMethod), BindingFlags.NonPublic | BindingFlags.Static).GetGenericArguments()[0]; yield return new object[] { theM, true, false, true }; } } private static void GenericMethod<M>() { } } public class TypeTestsExtended { public class ContextBoundClass : ContextBoundObject { public string Value = "The Value property."; } static string s_testAssemblyPath = Path.Combine(Environment.CurrentDirectory, "TestLoadAssembly.dll"); static string testtype = "System.Collections.Generic.Dictionary`2[[Program, Foo], [Program, Foo]]"; private static Func<AssemblyName, Assembly> assemblyloader = (aName) => aName.Name == "TestLoadAssembly" ? Assembly.LoadFrom(@".\TestLoadAssembly.dll") : null; private static Func<Assembly, string, bool, Type> typeloader = (assem, name, ignore) => assem == null ? Type.GetType(name, false, ignore) : assem.GetType(name, false, ignore); [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void GetTypeByName() { RemoteInvokeOptions options = new RemoteInvokeOptions(); RemoteExecutor.Invoke(() => { string test1 = testtype; Type t1 = Type.GetType(test1, (aName) => aName.Name == "Foo" ? Assembly.LoadFrom(s_testAssemblyPath) : null, typeloader, true ); Assert.NotNull(t1); string test2 = "System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [Program, TestLoadAssembly]]"; Type t2 = Type.GetType(test2, assemblyloader, typeloader, true); Assert.NotNull(t2); Assert.Equal(t1, t2); }, options).Dispose(); } [ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] [InlineData("System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [Program2, TestLoadAssembly]]")] [InlineData("")] public void GetTypeByName_NoSuchType_ThrowsTypeLoadException(string typeName) { RemoteExecutor.Invoke(marshalledTypeName => { Assert.Throws<TypeLoadException>(() => Type.GetType(marshalledTypeName, assemblyloader, typeloader, true)); Assert.Null(Type.GetType(marshalledTypeName, assemblyloader, typeloader, false)); }, typeName).Dispose(); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void GetTypeByNameCaseSensitiveTypeloadFailure() { RemoteInvokeOptions options = new RemoteInvokeOptions(); RemoteExecutor.Invoke(() => { //Type load failure due to case sensitive search of type Ptogram string test3 = "System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [program, TestLoadAssembly]]"; Assert.Throws<TypeLoadException>(() => Type.GetType(test3, assemblyloader, typeloader, true, false //case sensitive )); //non throwing version Type t2 = Type.GetType(test3, assemblyloader, typeloader, false, //no throw false ); Assert.Null(t2); }, options).Dispose(); } [Fact] public void IsContextful() { Assert.True(!typeof(TypeTestsExtended).IsContextful); Assert.True(!typeof(ContextBoundClass).IsContextful); } #region GetInterfaceMap tests public static IEnumerable<object[]> GetInterfaceMap_TestData() { yield return new object[] { typeof(ISimpleInterface), typeof(SimpleType), new Tuple<MethodInfo, MethodInfo>[] { new Tuple<MethodInfo, MethodInfo>(typeof(ISimpleInterface).GetMethod("Method"), typeof(SimpleType).GetMethod("Method")), new Tuple<MethodInfo, MethodInfo>(typeof(ISimpleInterface).GetMethod("GenericMethod"), typeof(SimpleType).GetMethod("GenericMethod")) } }; yield return new object[] { typeof(IGenericInterface<object>), typeof(DerivedType), new Tuple<MethodInfo, MethodInfo>[] { new Tuple<MethodInfo, MethodInfo>(typeof(IGenericInterface<object>).GetMethod("Method"), typeof(DerivedType).GetMethod("Method", new Type[] { typeof(object) })), } }; yield return new object[] { typeof(IGenericInterface<string>), typeof(DerivedType), new Tuple<MethodInfo, MethodInfo>[] { new Tuple<MethodInfo, MethodInfo>(typeof(IGenericInterface<string>).GetMethod("Method"), typeof(DerivedType).GetMethod("Method", new Type[] { typeof(string) })), } }; } [Theory] [MemberData(nameof(GetInterfaceMap_TestData))] // Android-only, change to TestPlatforms.Android once arcade dependency is updated [ActiveIssue("https://github.com/dotnet/runtime/issues/36653", TestRuntimes.Mono)] public void GetInterfaceMap(Type interfaceType, Type classType, Tuple<MethodInfo, MethodInfo>[] expectedMap) { InterfaceMapping actualMapping = classType.GetInterfaceMap(interfaceType); Assert.Equal(interfaceType, actualMapping.InterfaceType); Assert.Equal(classType, actualMapping.TargetType); Assert.Equal(expectedMap.Length, actualMapping.InterfaceMethods.Length); Assert.Equal(expectedMap.Length, actualMapping.TargetMethods.Length); for (int i = 0; i < expectedMap.Length; i++) { Assert.Contains(expectedMap[i].Item1, actualMapping.InterfaceMethods); int index = Array.IndexOf(actualMapping.InterfaceMethods, expectedMap[i].Item1); Assert.Equal(expectedMap[i].Item2, actualMapping.TargetMethods[index]); } } interface ISimpleInterface { void Method(); void GenericMethod<T>(); } class SimpleType : ISimpleInterface { public void Method() { } public void GenericMethod<T>() { } } interface IGenericInterface<T> { void Method(T arg); } class GenericBaseType<T> : IGenericInterface<T> { public void Method(T arg) { } } class DerivedType : GenericBaseType<object>, IGenericInterface<string> { public void Method(string arg) { } } #endregion } public class NonGenericClass { } public class NonGenericSubClassOfNonGeneric : NonGenericClass { } public class GenericClass<T> { } public class NonGenericSubClassOfGeneric : GenericClass<string> { } public class GenericClass<T, U> { } public abstract class AbstractClass { } public struct NonGenericStruct { } public ref struct RefStruct { } public struct GenericStruct<T> { } public struct GenericStruct<T, U> { } public interface NonGenericInterface { } public interface GenericInterface<T> { } public interface GenericInterface<T, U> { } } internal class DummyGenericClassForTypeTests<T> { }
41.708497
188
0.602595
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Runtime/tests/System/Type/TypeTests.cs
31,907
C#