Exemplo n.º 1
0
        public override VisitorCollection SelectVisitors(int userID, int pageNumber, int pageSize, out int totalCount)
        {
            totalCount = 0;
            VisitorCollection visitors = new VisitorCollection();

            using (SqlQuery query = new SqlQuery())
            {
                query.Pager.PageNumber  = pageNumber;
                query.Pager.PageSize    = pageSize;
                query.Pager.SelectCount = true;
                query.Pager.SortField   = "CreateDate";
                query.Pager.TableName   = "bx_UserVisitors";
                query.Pager.Condition   = "UserID = @UserID";

                query.CreateParameter <int>("@UserID", userID, SqlDbType.Int);

                using (XSqlDataReader reader = query.ExecuteReader())
                {
                    visitors = new VisitorCollection(reader);

                    if (reader.NextResult())
                    {
                        while (reader.Read())
                        {
                            totalCount = reader.Get <int>(0);
                        }
                    }
                }
            }

            return(visitors);
        }
Exemplo n.º 2
0
        public override VisitorCollection GetSpaceVisitors(int spaceOwnerID, int pageSize, int pageNumber)
        {
            using (SqlQuery query = new SqlQuery())
            {
                query.Pager.PageNumber  = pageNumber;
                query.Pager.PageSize    = pageSize;
                query.Pager.SelectCount = true;
                query.Pager.SortField   = "CreateDate";
                query.Pager.PrimaryKey  = "[ID]";
                query.Pager.TableName   = "bx_Visitors";
                query.Pager.Condition   = "UserID = @UserID";
                query.Pager.IsDesc      = true;

                query.CreateParameter <int>("@UserID", spaceOwnerID, SqlDbType.Int);

                using (XSqlDataReader reader = query.ExecuteReader())
                {
                    VisitorCollection visitors = new VisitorCollection(reader);

                    if (reader.NextResult())
                    {
                        if (reader.Read())
                        {
                            visitors.TotalRecords = reader.Get <int>(0);
                        }
                    }

                    return(visitors);
                }
            }
        }
        public void GetOpenApiSchemas_Result_Should_Contain_Schema_For_Function_Classes()
        {
            var namingStrategy    = new DefaultNamingStrategy();
            var filter            = new RouteConstraintFilter();
            var acceptor          = new OpenApiSchemaAcceptor();
            var documentHelper    = new DocumentHelper(filter, acceptor);
            var visitorCollection = VisitorCollection.CreateInstance();

            var methods = typeof(FakeFunctions).GetMethods().ToList();

            var schemas = documentHelper.GetOpenApiSchemas(methods, namingStrategy, visitorCollection);

            schemas.Should().NotBeNull();
            schemas.Count.Should().Be(6);

            schemas.Should().ContainKey("FakeClassModel");

            schemas["FakeClassModel"].Properties.Count.Should().Be(2);
            schemas["FakeClassModel"].Type.Should().Be("object");

            schemas.Should().ContainKey("FakeOtherClassModel");

            schemas["FakeOtherClassModel"].Properties.Count.Should().Be(2);
            schemas["FakeOtherClassModel"].Type.Should().Be("object");

            schemas["FakeClassModel"].Properties.Count.Should().Be(2);
            schemas["FakeClassModel"].Type.Should().Be("object");

            schemas.Should().ContainKey("FakeListModel");

            schemas["FakeListModel"].Properties.Count.Should().Be(1);
            schemas["FakeListModel"].Type.Should().Be("object");

            schemas.Should().ContainKey("FakeStringModel");
            schemas["FakeStringModel"].Properties.Count.Should().Be(2);
            schemas["FakeStringModel"].Type.Should().Be("object");

            schemas.Should().ContainKey("FakeGenericModel_FakeClassModel");

            schemas["FakeGenericModel_FakeClassModel"].Properties.Count.Should().Be(2);
            schemas["FakeGenericModel_FakeClassModel"].Type.Should().Be("object");
            schemas["FakeGenericModel_FakeClassModel"].Properties.Should().ContainKey("Name");
            schemas["FakeGenericModel_FakeClassModel"].Properties.Should().ContainKey("Value");
            schemas["FakeGenericModel_FakeClassModel"].Properties["Value"].Properties.Should().ContainKey("Number");
            schemas["FakeGenericModel_FakeClassModel"].Properties["Value"].Properties.Should().ContainKey("Text");

            schemas.Should().ContainKey("FakeGenericModel_FakeOtherClassModel");

            schemas["FakeGenericModel_FakeOtherClassModel"].Properties.Count.Should().Be(2);
            schemas["FakeGenericModel_FakeOtherClassModel"].Type.Should().Be("object");
            schemas["FakeGenericModel_FakeOtherClassModel"].Properties.Should().ContainKey("Name");
            schemas["FakeGenericModel_FakeOtherClassModel"].Properties.Should().ContainKey("Value");
            schemas["FakeGenericModel_FakeOtherClassModel"].Properties["Value"].Properties.Should().ContainKey("FirstName");
            schemas["FakeGenericModel_FakeOtherClassModel"].Properties["Value"].Properties.Should().ContainKey("LastName");
        }
Exemplo n.º 4
0
        private VisitorCollection GetVisitorCollection()
        {
            var visitors = typeof(IVisitor).Assembly
                           .GetTypes()
                           .Where(p => p.Name.EndsWith("Visitor") && p.IsClass && !p.IsAbstract)
                           .Select(p => (IVisitor)Activator.CreateInstance(p))
                           .ToList();
            var collection = new VisitorCollection(visitors);

            return(collection);
        }
Exemplo n.º 5
0
        public void Given_That_When_AddVisitors_Invoked_Then_It_Should_Return_Result()
        {
            var field      = typeof(Document).GetField("_collection", BindingFlags.Instance | BindingFlags.NonPublic);
            var collection = new VisitorCollection();
            var helper     = new Mock <IDocumentHelper>();
            var doc        = new Document(helper.Object);

            var result = doc.AddVisitors(collection);

            field.GetValue(result).Should().NotBeNull();
            field.GetValue(result).Should().BeOfType <VisitorCollection>();
        }
Exemplo n.º 6
0
        public static VisitorCollection ConvertVisitorStorageToDomainModel(Visitors visitorStorageModel)
        {
            VisitorCollection collection = new VisitorCollection();

            collection.ContactPerson      = visitorStorageModel.ContactPerson;
            collection.ContactPersonEmail = visitorStorageModel.ContactPersonEmail;
            collection.From         = visitorStorageModel.From;
            collection.MobileNumber = visitorStorageModel.MobileNumber;
            collection.Purpose      = visitorStorageModel.Purpose;
            collection.VisitorImage = "http://172.25.29.35:808/PlayerImages/" + visitorStorageModel.VisitorImage + "";
            collection.VisitorName  = visitorStorageModel.VisitorName;
            collection.VisitTime    = visitorStorageModel.VisitTime;
            return(collection);
        }
        /// <summary>
        /// Converts <see cref="OpenApiPayloadAttribute"/> to <see cref="OpenApiMediaType"/>.
        /// </summary>
        /// <typeparam name="T">Type of payload attribute inheriting <see cref="OpenApiPayloadAttribute"/>.</typeparam>
        /// <param name="attribute">OpenApi payload attribute.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance to create the JSON schema from .NET Types.</param>
        /// <param name="collection"><see cref="VisitorCollection"/> instance.</param>
        /// <returns><see cref="OpenApiMediaType"/> instance.</returns>
        public static OpenApiMediaType ToOpenApiMediaType <T>(this T attribute, NamingStrategy namingStrategy = null, VisitorCollection collection = null) where T : OpenApiPayloadAttribute
        {
            attribute.ThrowIfNullOrDefault();

            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            if (collection.IsNullOrDefault())
            {
                collection = VisitorCollection.CreateInstance();
            }

            var type = attribute.BodyType;

            // Generate schema based on the type.
            var schema = collection.PayloadVisit(type, namingStrategy);

            // Add deprecated attribute.
            if (attribute is OpenApiRequestBodyAttribute)
            {
                schema.Deprecated = (attribute as OpenApiRequestBodyAttribute).Deprecated;
            }
            if (attribute is OpenApiResponseWithBodyAttribute)
            {
                schema.Deprecated = (attribute as OpenApiResponseWithBodyAttribute).Deprecated;
            }

            // For array and dictionary object, the reference has already been added by the visitor.
            if (type.IsReferentialType() && !type.IsOpenApiNullable() && !type.IsOpenApiArray() && !type.IsOpenApiDictionary())
            {
                var reference = new OpenApiReference()
                {
                    Type = ReferenceType.Schema,
                    Id   = attribute.BodyType.GetOpenApiReferenceId(isDictionary: false, isList: false, namingStrategy)
                };

                schema.Reference = reference;
            }

            var mediaType = new OpenApiMediaType()
            {
                Schema = schema
            };

            return(mediaType);
        }
Exemplo n.º 8
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            var context = new HotelContext();

            IUserRepository        userRepository        = new UserRepository(context);
            IManagerRepository     managerRepository     = new ManagerRepository(context);
            IVisitorRepository     visitorRepository     = new VisitorRepository(context);
            IManagerInfoRepository managerInfoRepository = new ManagerInfoRepository(context);
            IVisitorInfoRepository visitorInfoRepository = new VisitorInfoRepository(context);
            IRoomRepository        roomRepository        = new RoomRepository(context);
            IBookingRepository     bookingRepository     = new BookingRepository(context);

            UserCollection        userCollection        = new UserCollection(userRepository);
            ManagerCollection     managerCollection     = new ManagerCollection(managerRepository);
            VisitorCollection     visitorCollection     = new VisitorCollection(visitorRepository);
            ManagerInfoCollection managerInfoCollection = new ManagerInfoCollection(managerInfoRepository);
            VisitorInfoCollection visitorInfoCollection = new VisitorInfoCollection(visitorInfoRepository);
            RoomCollection        roomCollection        = new RoomCollection(roomRepository);
            BookingCollection     bookingCollection     = new BookingCollection(bookingRepository);

            IHotelSystem hotel = new HotelSystem(userCollection, managerCollection, visitorCollection,
                                                 managerInfoCollection, visitorInfoCollection, roomCollection, bookingCollection);

            if (hotel.GetUser("root") is null)
            {
                hotel.AddUser(new Manager
                {
                    Login       = "******",
                    Password    = "******",
                    Salary      = 123,
                    ManagerInfo = new ManagerInfo {
                        Name = "lola", Surname = "brown", Email = "www@fw", StartDate = new DateTime(1999, 12, 12)
                    }
                });
            }

            Window mainWindow = new MainWindow();

            IDialogService dialogService = new DialogService.DialogService(mainWindow);

            dialogService.Register <RoomAboutDialogWindowModel, RoomAboutDialogWindow>();
            dialogService.Register <RoomBookingsDialogWindowModel, RoomBookingsDialogWindow>();
            dialogService.Register <AddBookingDialogWindowModel, AddBookingDialogWindow>();

            MainController mainController = new MainController(hotel, mainWindow, dialogService);

            mainController.LoadLoginDashboard();
        }
Exemplo n.º 9
0
        /// <summary>
        /// Function to sort visitors.
        /// </summary>
        /// <param name="visitors">List of visitors</param>        
        /// <returns>IEnumerable for Visitor</returns>
        public static VisitorCollection Sort(this VisitorCollection visitors)
        {
            var visitorCollection = new VisitorCollection();

            var v = from visitor in visitors
                    orderby visitor.PersonalDetail.LastName,
                            visitor.PersonalDetail.FirstName
                    select visitor;

            foreach (var visitor in v)
            {
                visitorCollection.Add(visitor);
            }

            return visitorCollection;
        }
Exemplo n.º 10
0
        /// <summary>
        /// Function to retrieve matching visitors.
        /// </summary>
        /// <param name="visitors">List of visitors</param>
        /// <param name="personIdentityList">List of person identities</param>
        /// <returns>IEnumerable for Visitor</returns>
        public static VisitorCollection RetrieveMatchingVisitors(this VisitorCollection visitors, IList<PersonIdentity> personIdentityList)
        {
            var visitorCollection = new VisitorCollection();

            var v = from visitor in visitors
                    join personIdentity in personIdentityList
                    on visitor.MapToPersonBase().PersonId equals personIdentity.PersonId
                    where personIdentity.PersonType == PersonType.Visitor
                    select visitor;

            foreach (var visitor in v)
            {
                visitorCollection.Add(visitor);
            }

            return visitorCollection;
        }
Exemplo n.º 11
0
        public void LastVisitorList(int userID, int count, LastVisitorHeadFootTemplate head, LastVisitorListItemTemplate item)
        {
            bool hasItems = true;

            VisitorCollection visitors = SpaceBO.Instance.GetVisitors(userID, count);

            if (visitors.Count == 0)
            {
                hasItems = false;
            }

            head(0, hasItems);

            foreach (Visitor visitor in visitors)
            {
                item(visitor);
            }
        }
Exemplo n.º 12
0
        public void LastVisitorList(int pageNumber, int pageSize, LastVisitorHeadFootTemplate head, LastVisitorHeadFootTemplate foot, LastVisitorListItemTemplate item)
        {
            int  totalCount;
            bool hasItems = true;
            int  userID   = UserBO.Instance.GetCurrentUserID();
            VisitorCollection visitors = SpaceBO.Instance.GetVisitors(userID, pageNumber, pageSize, out totalCount);

            if (totalCount == 0)
            {
                hasItems = false;
            }
            head(totalCount, hasItems);

            foreach (Visitor visitor in visitors)
            {
                item(visitor);
            }

            foot(totalCount, hasItems);
        }
Exemplo n.º 13
0
 /// <summary>
 /// Visitors the mapper.
 /// </summary>
 /// <param name="visitorCollection">The visitor.</param>
 /// <param name="visitor">The p.</param>
 public static void VisitorMapper(VisitorCollection visitorCollection, PersonBase visitor)
 {
     var visitorMember = new Visitor();
     if (visitor != null && visitorCollection != null)
     {
         visitorMember.VisitorId = visitor.PersonId;
         visitorMember.PersonalDetail = visitor.PersonalDetail;
         visitorMember.Photo = visitor.Photo;
         visitorMember.SecurityPhotoAddress = visitor.SecurityPhotoAddress;
         visitorMember.IsOnboard = visitor.IsOnboard;
         visitorMember.AreAllMessagesGotAcknowledged = visitor.AreAllMessagesGotAcknowledged;
         visitorMember.LastDateTime = visitor.LastDateTime;
         visitorMember.LastEvent = visitor.LastEvent;
         visitorMember.HasAlert = visitor.HasAlert;
         visitorMember.HasMessage = visitor.HasMessage;
         visitorMember.CardNumber = visitor.CardNumber;
         visitorMember.AssignAlerts(visitor.Alerts);
         visitorMember.AssignMessages(visitor.Messages);
         visitorMember.AllowOnboardAlert = visitor.AllowOnboardAlert;
         visitorCollection.Add(visitorMember);
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// 返回指定用户的最近访问者数
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public VisitorCollection GetVisitors(int userID, int count)
        {
            if (userID <= 0)
            {
                ThrowError(new InvalidParamError("userID"));
                return(new VisitorCollection());
            }

            string key = string.Format(cacheKey_List_Space, userID);

            VisitorCollection visitors = new VisitorCollection();

            if (CacheUtil.TryGetValue <VisitorCollection>(key, out visitors))
            {
                return(visitors);
            }

            visitors = SpaceDao.Instance.SelectVisitors(userID, count);
            CacheUtil.Set <VisitorCollection>(key, visitors);

            return(visitors);
        }
Exemplo n.º 15
0
 /// <summary>
 /// Assigns the visitors.
 /// </summary>
 /// <param name="visitorCollection">The visitor collection.</param>
 /// <returns>Instance of Person</returns>
 public Person AssignVisitors(VisitorCollection visitorCollection)
 {
     this.visitors = visitorCollection;
     return this;
 }
        /// <summary>
        /// Maps the visitor information.
        /// </summary>
        /// <param name="visitors">The visitors.</param>
        /// <param name="personsStatusHistory">The persons status history.</param>
        /// <param name="personStatusList">The person status list.</param>
        private static void MapVisitorInformation(VisitorCollection visitors, ListResult<PersonStatusHistory> personsStatusHistory, List<PersonStatus> personStatusList)
        {
            foreach (var visitor in visitors)
            {
                var item = personStatusList.FirstOrDefault(a => a.PersonId.ToString(CultureInfo.CurrentCulture).Equals(visitor.VisitorId));
                var personStatusHistory = new PersonStatusHistory();
                personStatusHistory.PersonId = visitor.VisitorId;
                personStatusHistory.FirstName = visitor.PersonalDetail.FirstName;
                personStatusHistory.MiddleName = visitor.PersonalDetail.MiddleName;
                personStatusHistory.LastName = visitor.PersonalDetail.LastName;
                personStatusHistory.Gender = visitor.PersonalDetail.Gender;
                personStatusHistory.Age = visitor.PersonalDetail.Age ?? 0;
                personStatusHistory.LastEvent = item != null ? item.Status : visitor.LastEvent;
                ////personStatusHistory.LastDateTime = item != null ? item.StatusChangedDate : visitor.LastDateTime;
                personStatusHistory.PersonTypeId = CommonConstants.VisitorTypeId;

                personsStatusHistory.Items.Add(personStatusHistory);
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Maps the visitor personal detail.
        /// </summary>
        /// <param name="dataReader">The data reader.</param>
        /// <returns>Visitor collection</returns>
        private static async Task<VisitorCollection> RetrieveVisitorPersonalDetail(SqlDataReader dataReader)
        {
            var visitors = new VisitorCollection();

            if (dataReader != null)
            {
                while (await dataReader.ReadAsync())
                {
                    var visitor = new Visitor();
                    visitor.VisitorId = dataReader.Int32Field(VisitorId).ToString();
                    visitor.PersonalDetail = new PersonalDetail();
                    visitor.VisitorInfo = new VisitorInfo();
                    visitor.PersonalDetail.Age = dataReader.Int16NullableField(Age);
                    visitor.PersonalDetail.AnniversaryDate = dataReader.DateTimeNullableField(AnniversaryDate);
                    visitor.PersonalDetail.BirthCountryId = dataReader.Int32NullableField(BirthCountryId).ToString();
                    visitor.PersonalDetail.Birthdate = dataReader.DateTimeNullableField(BirthDate);
                    visitor.PersonalDetail.CitizenshipCountryId = dataReader.Int32NullableField(CitizenshipCountryId).ToString();
                    visitor.PersonalDetail.FirstName = dataReader.StringField(FirstName);
                    visitor.PersonalDetail.Gender = dataReader.StringField(Gender);
                    visitor.PersonalDetail.LastName = dataReader.StringField(LastName);
                    visitor.PersonalDetail.MaritalStatus = dataReader.StringField(MaritalStatus);
                    visitor.PersonalDetail.MiddleName = dataReader.StringField(MiddleName);
                    visitor.PersonalDetail.Nickname = dataReader.StringField(NickName);
                    visitor.PersonalDetail.Occupation = dataReader.StringField(Occupation);
                    visitor.PersonalDetail.DocumentNumber = dataReader.StringField(DocumentNumber);
                    visitor.PersonalDetail.Suffix = dataReader.StringField(Suffix);
                    visitor.PersonalDetail.Title = dataReader.StringField(Title);
                    visitor.PersonalDetail.DepartmentName = dataReader.StringField(Department);
                    visitor.PersonalDetail.DepartmentPOC = dataReader.StringField(Contact);
                    visitor.VisitorInfo.CompanyName = dataReader.StringField(Company);
                    visitor.PersonalDetail.DocumentNumber = dataReader.StringField(DocumentNumber);
                    visitor.PersonalDetail.DocumentType = dataReader.StringField(DocumentType);
                    ////visitor.VisitorInfo.ContactNumber = dataReader.StringField(ContactPhoneNumber);
                    visitor.VisitorInfo.CompanyContactNumber = dataReader.StringField(ContactPhoneNumber);
                    visitor.PersonalDetail.DocumentTypeId = dataReader.Int16Field(DocumentTypeId).ToString();
                    visitors.Add(visitor);
                }
            }

            return visitors;
        }
Exemplo n.º 18
0
        /// <summary>
        /// Maps the visitors.
        /// </summary>
        /// <param name="dataReader">The data reader.</param>
        /// <returns>The visitor collection</returns>
        private static async Task<VisitorCollection> MapVisitors(SqlDataReader dataReader)
        {
            var visitors = new VisitorCollection();
            if (dataReader != null)
            {
                while (await dataReader.ReadAsync())
                {
                    var visitor = new Visitor
                    {
                        HasAlert = dataReader.BooleanNullableField(HasAlert).HasValue ? dataReader.BooleanNullableField(HasAlert).Value : false,
                        HasMessage = dataReader.BooleanNullableField(HasMessage).HasValue ? dataReader.BooleanNullableField(HasMessage).Value : false,
                        LastDateTime = dataReader.DateTimeNullableField(LastDateTime),
                        LastEvent = dataReader.StringField(LastEvent),
                        SecurityPhotoAddress = dataReader.StringField(SecurityPhotoAddress),
                        VisitorId = dataReader.Int32Field(VisitorId).ToString(),
                        VisitorTypeId = dataReader.ByteField(VisitorTypeId).ToString(),
                        VisitorType = dataReader.StringField(VisitorType),
                        VisitPurpose = dataReader.StringField(VisitPurpose)
                    };

                    byte[] bytes = await visitor.SecurityPhotoAddress.ImageAddressToByteArray();
                    visitor.Photo = bytes.ToBitmapSource();
                    visitor.AssignPhotoByteArray(new Collection<byte>(bytes));
                    visitors.Add(visitor);
                }
            }

            return visitors;
        }
Exemplo n.º 19
0
        /// <summary>
        /// Maps the visitor personal detail.
        /// </summary>
        /// <param name="person">The person.</param>
        /// <param name="visitorPersonalDetailList">The visitor personal detail list.</param>
        /// <param name="visitorAlerts">The visitor alerts.</param>
        /// <param name="visitorAlertMessages">The visitor alert messages.</param>
        /// <param name="visitorPersonMessages">The visitor person messages.</param>
        /// <param name="visitorMessages">The visitor messages.</param>
        /// <param name="visitorAccessCards">The visitor access cards.</param>
        private static void MapVisitorDetail(Person person, VisitorCollection visitorPersonalDetailList, IDictionary<string, AlertCollection> visitorAlerts, IDictionary<string, Collection<Message>> visitorAlertMessages, IDictionary<string, PersonMessageCollection> visitorPersonMessages, IDictionary<string, Collection<Message>> visitorMessages, IDictionary<string, AccessCardCollection> visitorAccessCards)
        {
            person.Visitors.Iterate(a =>
            {
                var visitorPersonalDetail = visitorPersonalDetailList.Where(b => a.VisitorId.Equals(b.VisitorId)).FirstOrDefault();
                if (visitorPersonalDetail != null)
                {
                    a.PersonalDetail = visitorPersonalDetail.PersonalDetail;
                    a.VisitorInfo = visitorPersonalDetail.VisitorInfo;
                }

                var alertCollection = visitorAlerts.ContainsKey(a.VisitorId) ? visitorAlerts[a.VisitorId] : null;
                alertCollection.Iterate(b => b.Message = visitorAlertMessages.ContainsKey(b.AlertId) ? visitorAlertMessages[b.AlertId].FirstOrDefault() : null);
                if (alertCollection != null)
                {
                    a.AssignAlerts(alertCollection);
                }

                var messageCollection = visitorPersonMessages.ContainsKey(a.VisitorId) ? visitorPersonMessages[a.VisitorId] : null;
                messageCollection.Iterate(b => b.Message = visitorMessages.ContainsKey(b.AlertId) ? visitorMessages[b.AlertId].FirstOrDefault() : null);
                if (messageCollection != null)
                {
                    a.AssignMessages(messageCollection);
                }

                var accessCards = visitorAccessCards.ContainsKey(a.VisitorId) ? visitorAccessCards[a.VisitorId] : null;
                if (accessCards != null)
                {
                    a.AssignVisitorAccessCard(accessCards);
                }
            });
        }
Exemplo n.º 20
0
        /// <summary>
        /// Converts <see cref="OpenApiResponseWithBodyAttribute"/> to <see cref="OpenApiResponse"/>.
        /// </summary>
        /// <param name="attribute"><see cref="OpenApiResponseWithBodyAttribute"/> instance.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance to create the JSON schema from .NET Types.</param>
        /// <param name="collection"><see cref="VisitorCollection"/> instance.</param>
        /// <returns><see cref="OpenApiResponse"/> instance.</returns>
        public static OpenApiResponse ToOpenApiResponse(this OpenApiResponseWithBodyAttribute attribute, NamingStrategy namingStrategy = null, VisitorCollection collection = null)
        {
            attribute.ThrowIfNullOrDefault();

            var description = string.IsNullOrWhiteSpace(attribute.Description)
                                  ? $"Payload of {attribute.BodyType.GetOpenApiDescription()}"
                                  : attribute.Description;
            var mediaType = attribute.ToOpenApiMediaType <OpenApiResponseWithBodyAttribute>(namingStrategy, collection);
            var content   = new Dictionary <string, OpenApiMediaType>()
            {
                { attribute.ContentType, mediaType }
            };
            var response = new OpenApiResponse()
            {
                Description = description,
                Content     = content
            };

            if (!string.IsNullOrWhiteSpace(attribute.Summary))
            {
                var summary = new OpenApiString(attribute.Summary);

                response.Extensions.Add("x-ms-summary", summary);
            }

            return(response);
        }
        /// <summary>
        /// Converts <see cref="OpenApiResponseWithBodyAttribute"/> to <see cref="OpenApiResponse"/>.
        /// </summary>
        /// <param name="attribute"><see cref="OpenApiResponseWithBodyAttribute"/> instance.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance to create the JSON schema from .NET Types.</param>
        /// <param name="collection"><see cref="VisitorCollection"/> instance.</param>
        /// <param name="version">OpenAPI spec version.</param>
        /// <returns><see cref="OpenApiResponse"/> instance.</returns>
        public static OpenApiResponse ToOpenApiResponse(this OpenApiResponseWithBodyAttribute attribute, NamingStrategy namingStrategy = null, VisitorCollection collection = null, OpenApiVersionType version = OpenApiVersionType.V2)
        {
            attribute.ThrowIfNullOrDefault();

            var description = string.IsNullOrWhiteSpace(attribute.Description)
                                  ? $"Payload of {attribute.BodyType.GetOpenApiDescription()}"
                                  : attribute.Description;
            var mediaType = attribute.ToOpenApiMediaType <OpenApiResponseWithBodyAttribute>(namingStrategy, collection, version);
            var content   = new Dictionary <string, OpenApiMediaType>()
            {
                { attribute.ContentType, mediaType }
            };
            var response = new OpenApiResponse()
            {
                Description = description,
                Content     = content,
            };

            if (attribute.CustomHeaderType.HasInterface <IOpenApiCustomResponseHeader>())
            {
                var header = Activator.CreateInstance(attribute.CustomHeaderType) as IOpenApiCustomResponseHeader;

                response.Headers = header.Headers;
            }

            if (!string.IsNullOrWhiteSpace(attribute.Summary))
            {
                var summary = new OpenApiString(attribute.Summary);

                response.Extensions.Add("x-ms-summary", summary);
            }

            return(response);
        }
        /// <inheritdoc />
        public Dictionary <string, OpenApiSchema> GetOpenApiSchemas(List <MethodInfo> elements, NamingStrategy namingStrategy, VisitorCollection collection)
        {
            var requests = elements.SelectMany(p => p.GetCustomAttributes <OpenApiRequestBodyAttribute>(inherit: false))
                           .Select(p => p.BodyType);
            var responses = elements.SelectMany(p => p.GetCustomAttributes <OpenApiResponseWithBodyAttribute>(inherit: false))
                            .Select(p => p.BodyType);
            var types = requests.Union(responses)
                        .Select(p => p.IsOpenApiArray() || p.IsOpenApiDictionary() ? p.GetOpenApiSubType() : p)
                        .Distinct()
                        .Where(p => !p.IsSimpleType())
                        .Where(p => p != typeof(JObject))
                        .Where(p => p != typeof(JToken))
                        .Where(p => !typeof(Array).IsAssignableFrom(p))
                        .ToList();

            var rootSchemas = new Dictionary <string, OpenApiSchema>();
            var schemas     = new Dictionary <string, OpenApiSchema>();

            this._acceptor.Types       = types.ToDictionary(p => p.GetOpenApiTypeName(namingStrategy), p => p);
            this._acceptor.RootSchemas = rootSchemas;
            this._acceptor.Schemas     = schemas;

            this._acceptor.Accept(collection, namingStrategy);

            var union = schemas.Concat(rootSchemas.Where(p => !schemas.Keys.Contains(p.Key)))
                        .Distinct()
                        .OrderBy(p => p.Key)
                        .ToDictionary(p => p.Key,
                                      p =>
            {
                // Title was intentionally added for schema key.
                // It's not necessary when it's added to the root schema.
                // Therefore, it's removed.
                p.Value.Title = null;
                return(p.Value);
            });

            return(union);
        }
        /// <inheritdoc />
        public OpenApiRequestBody GetOpenApiRequestBody(MethodInfo element, NamingStrategy namingStrategy, VisitorCollection collection)
        {
            var attributes = element.GetCustomAttributes <OpenApiRequestBodyAttribute>(inherit: false);

            if (!attributes.Any())
            {
                return(null);
            }

            var contents = attributes.ToDictionary(p => p.ContentType, p => p.ToOpenApiMediaType(namingStrategy, collection));

            if (contents.Any())
            {
                return(new OpenApiRequestBody()
                {
                    Content = contents,
                    Required = attributes.First().Required
                });
            }

            return(null);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Retrieves the visitors.
        /// </summary>
        /// <param name="filter">The filter.</param>
        /// <returns>
        /// Visitor task
        /// </returns>
        public async Task<ListResult<Visitor>> ListAsync(VisitorSearchParameters filter)
        {
            DepthResolver.Initialize<VisitorDepths>();
            var result = new ListResult<Visitor>();

            var visitorSearch = new VisitorListRequestSearchParameters
            {
                PageNumber = filter.PageNumber.RetrievePageNumber(),
                MaxResults = filter.MaxResults.RetrieveMaxResults(),
                LastNameContains = filter.LastNameContains,
                VisitorIds = filter.VisitorIds,
                StartDate = string.IsNullOrEmpty(filter.StartDate) ? null : Convert.ToDateTime(filter.StartDate, CultureInfo.InvariantCulture).ToString("yyyy-MM-ddTHH:mm:ss"),
                EndDate = string.IsNullOrEmpty(filter.EndDate) ? null : Convert.ToDateTime(filter.EndDate, CultureInfo.InvariantCulture).ToString("yyyy-MM-ddTHH:mm:ss"),
                OrderBy = filter.OrderBy,
                Depths = (VisitorDepths)DepthResolver.Resolve(filter.ModifiedParts, VisitorDepths.Visitor),
                Citizenship = filter.Citizenship,
                Birthdate = filter.Birthdate,
                VisitorTypeId = filter.VisitorTypeId,
                VisitPurposeId = filter.VisitPurposeId,
                DocumentNumber = filter.DocumentNumber,
                DocumentTypeId = filter.DocumentTypeId,
                ModifiedParts = filter.ModifiedParts,
                ShipTime = filter.ShipTime
            };

            ListResult<Entities.PersonStatus> visitorStatusDetails = null;

            if (!string.IsNullOrEmpty(filter.Status))
            {
                visitorSearch.PageNumber = 1;
                visitorSearch.MaxResults = int.MaxValue;
                visitorStatusDetails = await this.personStatusRepository.ListPersonStatus(PersonTypeId, StatusTypeId, filter.Status, null, visitorSearch.ShipTime, this.applicationSettings.ShipId, null, visitorSearch.PageNumber, visitorSearch.MaxResults);

                if (visitorStatusDetails.Items.Count == 0)
                {
                    return result;
                }

                var visitorStatusList = visitorStatusDetails.Items.Where(v => v.StatusChangedDate.Date == Convert.ToDateTime(visitorSearch.ShipTime).Date).ToList();

                if (visitorStatusList != null && visitorStatusList.Count > 0)
                {
                    visitorSearch.VisitorIds = visitorStatusList.RetrieveIds(a => a.PersonId);
                }
                else
                {
                    return result;
                }
            }

            var visitorData = !string.IsNullOrEmpty(visitorSearch.ShipTime) ? await this.visitorRepository.RetrieveVisitors(visitorSearch.VisitorIds, visitorSearch.LastNameContains, visitorSearch.Citizenship, visitorSearch.Birthdate, null, visitorSearch.DocumentTypeId, visitorSearch.DocumentNumber, visitorSearch.VisitorTypeId, visitorSearch.VisitPurposeId, visitorSearch.ShipTime, visitorSearch.PageNumber, visitorSearch.MaxResults, visitorSearch.Depths, visitorSearch.OrderBy) : await this.visitorRepository.RetrieveVisitorListAsync(visitorSearch.VisitorIds, visitorSearch.LastNameContains, visitorSearch.Citizenship, visitorSearch.DocumentTypeId, visitorSearch.DocumentNumber, string.IsNullOrEmpty(visitorSearch.Birthdate) ? default(DateTime?) : Convert.ToDateTime(visitorSearch.Birthdate, CultureInfo.InvariantCulture), visitorSearch.StartDate, visitorSearch.EndDate, null, visitorSearch.VisitorTypeId, visitorSearch.VisitPurposeId, visitorSearch.PageNumber, visitorSearch.MaxResults, visitorSearch.ModifiedParts, visitorSearch.OrderBy);

            if (visitorData != null)
            {
                if (visitorData.Items.Count > 0 && !string.IsNullOrEmpty(visitorSearch.ShipTime))
                {
                    var personIds = visitorData.Items.RetrieveIds(a => a.VisitorId) + CommaSeparator;

                    var onboardVisitorDetailsTask = visitorStatusDetails ?? await this.personStatusRepository.ListPersonStatus(PersonTypeId, StatusTypeId, null, personIds, visitorSearch.ShipTime, this.applicationSettings.ShipId, null, 1, int.MaxValue);

                    if (onboardVisitorDetailsTask != null && onboardVisitorDetailsTask.Items != null && onboardVisitorDetailsTask.Items.Count > 0)
                    {
                        foreach (var onboardVisitor in onboardVisitorDetailsTask.Items)
                        {
                            foreach (var visitor in visitorData.Items)
                            {
                                if (visitor.VisitorId == onboardVisitor.PersonId)
                                {
                                    if (onboardVisitor.Status.Equals("true", StringComparison.OrdinalIgnoreCase))
                                    {
                                        foreach (var visit in visitor.Visits)
                                        {
                                            visit.LastOnboardDate = onboardVisitor.StatusChangedDate;
                                        }
                                    }
                                    else
                                    {
                                        foreach (var visit in visitor.Visits)
                                        {
                                            visit.LastOffBoardDate = onboardVisitor.StatusChangedDate;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                var visitors = new VisitorCollection();

                foreach (Entities.Visitor visitor in visitorData.Items)
                {
                    visitors.Add(MapVisitorData(visitor));
                }

                result.AssignItems(visitors);
                result.TotalResults = visitorStatusDetails != null ? visitorData.Items.Count : visitorData.TotalResults;
            }

            return result;
        }
        /// <summary>
        /// Gets the list of <see cref="OpenApiParameter"/> instances.
        /// </summary>
        /// <param name="helper"><see cref="IDocumentHelper"/> instance.</param>
        /// <param name="element"><see cref="MethodInfo"/> instance.</param>
        /// <param name="trigger"><see cref="HttpTriggerAttribute"/> instance.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance to create the JSON schema from .NET Types.</param>
        /// <param name="collection"><see cref="VisitorCollection"/> instance to process parameters.</param>
        /// <param name="version"><see cref="OpenApiVersionType"/> value.</param>
        /// <returns>List of <see cref="OpenApiParameter"/> instance.</returns>
        public static List <OpenApiParameter> GetOpenApiParameters(this IDocumentHelper helper, MethodInfo element, HttpTriggerAttribute trigger, NamingStrategy namingStrategy, VisitorCollection collection, OpenApiVersionType version)
        {
            var parameters = element.GetCustomAttributes <OpenApiParameterAttribute>(inherit: false)
                             .Where(p => p.Deprecated == false)
                             .Select(p => p.ToOpenApiParameter(namingStrategy, collection))
                             .ToList();

            // This is the interim solution to resolve:
            // https://github.com/Azure/azure-functions-openapi-extension/issues/365
            //
            // It will be removed when the following issue is resolved:
            // https://github.com/microsoft/OpenAPI.NET/issues/747
            if (version == OpenApiVersionType.V3)
            {
                return(parameters);
            }

            var attributes = element.GetCustomAttributes <OpenApiRequestBodyAttribute>(inherit: false);

            if (!attributes.Any())
            {
                return(parameters);
            }

            var contents = attributes.Where(p => p.Deprecated == false)
                           .Where(p => p.ContentType == "application/x-www-form-urlencoded" || p.ContentType == "multipart/form-data")
                           .Select(p => p.ToOpenApiMediaType(namingStrategy, collection, version));

            if (!contents.Any())
            {
                return(parameters);
            }

            var @ref    = contents.First().Schema.Reference;
            var schemas = helper.GetOpenApiSchemas(new[] { element }.ToList(), namingStrategy, collection);
            var schema  = schemas.SingleOrDefault(p => p.Key == @ref.Id);

            if (schema.IsNullOrDefault())
            {
                return(parameters);
            }

            var properties = schema.Value.Properties;

            foreach (var property in properties)
            {
                var value = property.Value;
                if ((value.Type == "string" && value.Format == "binary") || (value.Type == "string" && value.Format == "base64"))
                {
                    value.Type   = "file";
                    value.Format = null;
                }

                var parameter = new OpenApiParameter()
                {
                    Name        = property.Key,
                    Description = $"[formData]{value.Description}",
                    Required    = bool.TryParse($"{value.Required}", out var result) ? result : false,
                    Deprecated  = value.Deprecated,
                    Schema      = value,
                };

                parameters.Add(parameter);
            }

            // // TODO: Should this be forcibly provided?
            // // This needs to be provided separately.
            // if (trigger.AuthLevel != AuthorizationLevel.Anonymous)
            // {
            //     parameters.AddOpenApiParameter<string>("code", @in: ParameterLocation.Query, required: false);
            // }

            return(parameters);
        }
        private void SetUpPartyManagerData()
        {
            this.person = new Person();
            CrewmemberCollection crewMembers = new CrewmemberCollection();
            var personDetail = new PersonalDetail { CitizenshipCountryId = string.Empty, FirstName = string.Empty, LastName = string.Empty, MiddleName = string.Empty, Title = string.Empty, PreferredName = string.Empty, MaritalStatus = string.Empty, Nickname = string.Empty, Occupation = string.Empty, DocumentNumber = string.Empty, Suffix = string.Empty };
            crewMembers.Add(new Crewmember { CrewmemberId = string.Empty, CrewmemberTypeId = "1", SecurityPhotoAddress = string.Empty, ChargeId = string.Empty, EmployeeNo = string.Empty, LastEvent = string.Empty, PersonalDetail = personDetail });
            this.person.AssignCrewmembers(crewMembers);

            GuestCollection guests = new GuestCollection();
            var checkInDetail = new CheckInDetail
            {
                ApplicationId = string.Empty,
                LocationId = "1",
                LocationTypeId = "1",
                MachineName = "Machine",
                Station = "station",
                UserId = "user"
            };
            var cruiseDetail = new GuestCruiseDetail
            {
                BeaconId = string.Empty,
                CheckInDetail = checkInDetail,
                LoyaltyLevelTypeId = "1",
                ReservationId = "1",
                Stateroom = stateroom,
                ReservationStatusId = "0000089",
                StateroomCategoryTypeId = "aaasad"
            };
            guests.Add(new Guest
            {
                GuestId = PersonId,
                PersonalDetail = personDetail,
                Age = 0,
                CruiseDetail = cruiseDetail,
                SecurityPhotoAddress = string.Empty,
            });

            VisitorCollection visitors = new VisitorCollection();
            visitors.Add(new Visitor
            {
                VisitorId = "0003",
                PersonalDetail = personDetail,
                SecurityPhotoAddress = string.Empty,
            });

            this.person.AssignGuests(guests);
            this.person.AssignVisitors(visitors);
        }
Exemplo n.º 27
0
 /// <summary>
 /// Function to retrieve photo of Visitor.
 /// </summary>
 /// <param name="visitor">Instance of Crewmember</param>
 private static void RetrieveVisitorPhoto(Visitor visitor)
 {
     Observable.ToAsync(() =>
     {
         var person = new Person();
         var visitorCollection = new VisitorCollection();
         visitorCollection.Add(visitor);
         person.AssignVisitors(visitorCollection);
         DIContainer.Instance.Resolve<PhotoService>().RetrievePhotos(person);
     })().Subscribe(r => { }, ex => { });
 }
        /// <inheritdoc />
        public List <OpenApiParameter> GetOpenApiParameters(MethodInfo element, HttpTriggerAttribute trigger, NamingStrategy namingStrategy, VisitorCollection collection)
        {
            var parameters = element.GetCustomAttributes <OpenApiParameterAttribute>(inherit: false)
                             .Select(p => p.ToOpenApiParameter(namingStrategy, collection))
                             .ToList();

            // TODO: Should this be forcibly provided?
            // This needs to be provided separately.
            if (trigger.AuthLevel != AuthorizationLevel.Anonymous)
            {
                parameters.AddOpenApiParameter <string>("code", @in: ParameterLocation.Query, required: false);
            }

            return(parameters);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Setups the data.
        /// </summary>
        private void SetupData()
        {
            Domain.Dependencies.Register();
            DataAccess.Dependencies.Register();

            this.workstationMock = new Mock<Workstation>();
            DIContainer.Instance.RegisterInstance<Workstation>(this.workstationMock.Object);
            Workstation ws = DIContainer.Instance.Resolve<Workstation>();

            ws.Port = new Port { PortId = "1" };
            ws.Ship = new Ship { ShipId = "5" };
            ws.GangwayLocation = new GangwayLocation { LocationId = "1" };
            ws.GangwayServiceBaseAddress = "http://Localhost/";
            ws.ConfigurationServiceBaseAddress = "http://Localhost/";
            ws.AuthenticationServiceBaseAddress = "http://Localhost/";
            ws.AuthorizationServiceBaseAddress = "http://Localhost/";
            ws.ConnectionMode = ConnectionMode.Online;
            var intCollection = new Collection<int>();
            intCollection.Add(0);
            var brand = new Brand { BrandId = "3", Name = "Carnival Breeze", MediaItemAddress = "http://172.26.248.122/ImagingMediaService/MediaItems/23" };
            var voyageList = new List<Voyage>();
            var voyage = new Voyage { DebarkPortId = "1", EmbarkPortId = "1", DestinationId = "1", MediaItemAddress = "http://172.26.248.122/", VoyageId = "31", Name = "Carnival Voyage", IsActive = true, ShipId = "5", Number = "ccl", DebarkDate = new DateTime(2015, 3, 3), EmbarkDate = new DateTime(2015, 3, 2) };
            voyageList.Add(voyage);
            ws.AssignVoyageList(voyageList);

            ////this.repository = new Mock<IRepository>();
            ////this.embarkationStatisticsRepositoryMock = new Mock<EmbarkationStatisticsRepository>();
            this.personServiceRepositoryMock = new Mock<PersonServiceRepository>();
            this.referenceDataRepositoryMock = new Mock<ReferenceDataRepository>();
            ////this.photoCaptureRepositoryMock = new Mock<PhotoCaptureRepository>();
            ////this.shipTimeRepositoryMock = new Mock<ShipTimeRepository>();
            ////this.referenceDataRepositoryMock = new Mock<ReferenceDataRepository>();
            ////this.gangwayEventRepositoryMock = new Mock<GangwayEventRepository>();
            ////this.guestClient = new Mock<IGuestClient>();
            ////this.personClient = new Mock<IPersonsClient>();
            ////DIContainer.Instance.RegisterInstance<IGuestClient>(this.guestClient.Object);
            ////DIContainer.Instance.RegisterInstance<IPersonsClient>(this.personClient.Object);

            ////DIContainer.Instance.RegisterInstance<IRepository>(this.repository.Object);
            DIContainer.Instance.RegisterInstance<ReferenceDataRepository>(this.referenceDataRepositoryMock.Object);
            ////DIContainer.Instance.RegisterInstance<EmbarkationStatisticsRepository>(this.embarkationStatisticsRepositoryMock.Object);
            ////DIContainer.Instance.RegisterInstance<GangwayEventRepository>(this.gangwayEventRepositoryMock.Object);
            ////DIContainer.Instance.RegisterInstance<PhotoCaptureRepository>(this.photoCaptureRepositoryMock.Object);
            DIContainer.Instance.RegisterInstance<PersonServiceRepository>(this.personServiceRepositoryMock.Object);
            ////DIContainer.Instance.RegisterInstance<ShipTimeRepository>(this.shipTimeRepositoryMock.Object);

            var cruiseDetails = new GuestCruiseDetail { BeaconId = string.Empty, BerthNumber = string.Empty, IdentificationId = string.Empty, LoyaltyLevelTypeId = string.Empty, ReservationId = string.Empty, Stateroom = "0000" };
            var personDetail = new PersonalDetail { CitizenshipCountryId = string.Empty, FirstName = string.Empty, LastName = string.Empty, MiddleName = string.Empty, Title = string.Empty, PreferredName = string.Empty, MaritalStatus = string.Empty, Nickname = string.Empty, Occupation = string.Empty, DocumentNumber = string.Empty, Suffix = string.Empty, DocumentTypeId = "1" };

            this.person = new Person { TotalResults = 1 };
            CrewmemberCollection crewMembers = new CrewmemberCollection();
            crewMembers.Add(new Crewmember { CrewmemberId = string.Empty, CrewmemberTypeId = "1", SecurityPhotoAddress = string.Empty, ChargeId = string.Empty, EmployeeNo = string.Empty, LastEvent = string.Empty, PersonalDetail = personDetail });
            person.AssignCrewmembers(crewMembers);

            GuestCollection guests = new GuestCollection();
            var checkInDetail = new CheckInDetail
            {
                ApplicationId = string.Empty,
                LocationId = "1",
                LocationTypeId = "1",
                MachineName = "Machine",
                Station = "station",
                UserId = "user"
            };
            var cruiseDetail = new GuestCruiseDetail
            {
                BeaconId = string.Empty,
                CheckInDetail = checkInDetail,
                LoyaltyLevelTypeId = "1",
                ReservationId = "1",
                Stateroom = "00000",
                ReservationStatusId = "0000089",
                StateroomCategoryTypeId = "aaasad"
            };
            guests.Add(new Guest
            {
                GuestId = "0001",
                PersonalDetail = personDetail,
                Age = 0,
                CruiseDetail = cruiseDetail,
                SecurityPhotoAddress = string.Empty,
            });

            VisitorCollection visitors = new VisitorCollection();
            visitors.Add(new Visitor
            {
                VisitorId = "0003",
                PersonalDetail = personDetail,
                SecurityPhotoAddress = string.Empty,
            });
            this.person.AssignGuests(guests);
            this.person.AssignVisitors(visitors);
            this.personTypes = new List<PersonType>();
            personTypes.Add(PersonType.Guest);
            this.personServiceRepositoryMock.Setup(data => data.RetrievePersonsBySearchText(It.IsNotNull<string>(), It.IsAny<string>(), It.IsAny<IList<PersonType>>(), It.IsAny<SearchType>(), It.IsAny<string>(), It.IsAny<string>(), 0, 0, It.IsAny<string>(), It.IsAny<string>())).Returns(Task.FromResult(this.person));
            var documentTypes = new DocumentTypeCollection();
            documentTypes.Add(new DocumentType { CountryId = "232", Code = "USA", DocumentTypeId = "1", Name = "Passport" });
            var referencedata = new ReferenceData();
            referencedata.AssignDocumentTypes(documentTypes);
            this.referenceDataRepositoryMock.Setup(data => data.RetrieveReferenceDataAsync()).Returns(Task.FromResult(referencedata));
            ////this.personClient.Setup(data => data.RetrievePersonsAsync("5", "ab", null, null, "0001", null, null, "Guest", null, null, null, null, null, 0, 0)).Returns(RetrieveData());
        }
        /// <inheritdoc />
        public OpenApiResponses GetOpenApiResponses(MethodInfo element, NamingStrategy namingStrategy, VisitorCollection collection)
        {
            var responsesWithBody = element.GetCustomAttributes <OpenApiResponseWithBodyAttribute>(inherit: false)
                                    .Select(p => new { StatusCode = p.StatusCode, Response = p.ToOpenApiResponse(namingStrategy) });

            var responsesWithoutBody = element.GetCustomAttributes <OpenApiResponseWithoutBodyAttribute>(inherit: false)
                                       .Select(p => new { StatusCode = p.StatusCode, Response = p.ToOpenApiResponse(namingStrategy) });

            var responses = responsesWithBody.Concat(responsesWithoutBody)
                            .ToDictionary(p => ((int)p.StatusCode).ToString(), p => p.Response)
                            .ToOpenApiResponses();

            return(responses);
        }
 public void Init()
 {
     this._visitorCollection = new VisitorCollection();
     this._visitor           = new DateTimeTypeVisitor(this._visitorCollection);
     this._strategy          = new CamelCaseNamingStrategy();
 }
Exemplo n.º 32
0
        /// <inheritdoc />
        public virtual VisitorCollection GetVisitorCollection()
        {
            var collection = VisitorCollection.CreateInstance();

            return(collection);
        }
Exemplo n.º 33
0
        public override VisitorCollection GetSpaceVisitors(int spaceOwnerID, int pageSize, int pageNumber)
        {
            using (SqlQuery query = new SqlQuery())
            {
                query.Pager.PageNumber = pageNumber;
                query.Pager.PageSize = pageSize;
                query.Pager.SelectCount = true;
                query.Pager.SortField = "CreateDate";
                query.Pager.PrimaryKey = "[ID]";
                query.Pager.TableName = "bx_Visitors";
                query.Pager.Condition = "UserID = @UserID";
                query.Pager.IsDesc = true;

                query.CreateParameter<int>("@UserID", spaceOwnerID, SqlDbType.Int);

                using (XSqlDataReader reader = query.ExecuteReader())
                {
                    VisitorCollection visitors = new VisitorCollection(reader);

                    if (reader.NextResult())
                    {
                        if (reader.Read())
                            visitors.TotalRecords = reader.Get<int>(0);
                    }

                    return visitors;
                }
            }
        }
Exemplo n.º 34
0
 public void Init()
 {
     this._visitorCollection = new VisitorCollection();
     this._visitor           = new RecursiveObjectTypeVisitor(this._visitorCollection);
     this._strategy          = new CamelCaseNamingStrategy();
 }
Exemplo n.º 35
0
        /// <summary>
        /// Converts <see cref="OpenApiPayloadAttribute"/> to <see cref="OpenApiMediaType"/>.
        /// </summary>
        /// <typeparam name="T">Type of payload attribute inheriting <see cref="OpenApiPayloadAttribute"/>.</typeparam>
        /// <param name="attribute">OpenApi payload attribute.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance to create the JSON schema from .NET Types.</param>
        /// <param name="collection"><see cref="VisitorCollection"/> instance.</param>
        /// <param name="version">OpenAPI spec version.</param>
        /// <returns><see cref="OpenApiMediaType"/> instance.</returns>
        public static OpenApiMediaType ToOpenApiMediaType <T>(this T attribute, NamingStrategy namingStrategy = null, VisitorCollection collection = null, OpenApiVersionType version = OpenApiVersionType.V2) where T : OpenApiPayloadAttribute
        {
            attribute.ThrowIfNullOrDefault();

            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            if (collection.IsNullOrDefault())
            {
                collection = VisitorCollection.CreateInstance();
            }

            var type = attribute.BodyType;

            // Generate schema based on the type.
            var schema = collection.PayloadVisit(type, namingStrategy);

            // Add deprecated attribute.
            if (attribute is OpenApiRequestBodyAttribute)
            {
                schema.Deprecated = (attribute as OpenApiRequestBodyAttribute).Deprecated;
            }
            if (attribute is OpenApiResponseWithBodyAttribute)
            {
                schema.Deprecated = (attribute as OpenApiResponseWithBodyAttribute).Deprecated;
            }

            // For array and dictionary object, the reference has already been added by the visitor.
            if (type.IsReferentialType() && !type.IsOpenApiNullable() && !type.IsOpenApiArray() && !type.IsOpenApiDictionary())
            {
                var reference = new OpenApiReference()
                {
                    Type = ReferenceType.Schema,
                    Id   = attribute.BodyType.GetOpenApiReferenceId(isDictionary: false, isList: false, namingStrategy)
                };

                schema.Reference = reference;
            }

            var mediaType = new OpenApiMediaType()
            {
                Schema = schema
            };

            if (attribute.Example.IsNullOrDefault())
            {
                return(mediaType);
            }

            if (!attribute.Example.HasInterface("IOpenApiExample`1"))
            {
                return(mediaType);
            }

            var example  = (dynamic)Activator.CreateInstance(attribute.Example);
            var examples = (IDictionary <string, OpenApiExample>)example.Build(namingStrategy).Examples;

            mediaType.Examples = examples;
            if (version == OpenApiVersionType.V2)
            {
                mediaType.Example = examples.First().Value.Value;
            }

            return(mediaType);
        }
Exemplo n.º 36
0
        /// <summary>
        /// Converts <see cref="OpenApiParameterAttribute"/> to <see cref="OpenApiParameter"/>.
        /// </summary>
        /// <param name="attribute"><see cref="OpenApiParameterAttribute"/> instance.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance.</param>
        /// <param name="collection"><see cref="VisitorCollection"/> instance.</param>
        /// <returns><see cref="OpenApiParameter"/> instance.</returns>
        public static OpenApiParameter ToOpenApiParameter(this OpenApiParameterAttribute attribute, NamingStrategy namingStrategy = null, VisitorCollection collection = null)
        {
            attribute.ThrowIfNullOrDefault();

            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            if (collection.IsNullOrDefault())
            {
                collection = VisitorCollection.CreateInstance();
            }

            var type = attribute.Type;

            var schema = collection.ParameterVisit(type, namingStrategy);

            var parameter = new OpenApiParameter()
            {
                Name        = attribute.Name,
                Description = attribute.Description,
                Required    = attribute.Required,
                In          = attribute.In,
                Schema      = schema
            };

            if (type.IsOpenApiArray())
            {
                if (attribute.In == ParameterLocation.Path)
                {
                    parameter.Style   = ParameterStyle.Simple;
                    parameter.Explode = false;
                }

                if (attribute.In == ParameterLocation.Query)
                {
                    parameter.Style = attribute.CollectionDelimiter == OpenApiParameterCollectionDelimiterType.Comma
                                      ? ParameterStyle.Form
                                      : (attribute.CollectionDelimiter == OpenApiParameterCollectionDelimiterType.Space
                                         ? ParameterStyle.SpaceDelimited
                                         : ParameterStyle.PipeDelimited);
                    parameter.Explode = attribute.CollectionDelimiter == OpenApiParameterCollectionDelimiterType.Comma
                                        ? attribute.Explode
                                        : false;
                }
            }

            if (!string.IsNullOrWhiteSpace(attribute.Summary))
            {
                var summary = new OpenApiString(attribute.Summary);

                parameter.Extensions.Add("x-ms-summary", summary);
            }

            if (attribute.Visibility != OpenApiVisibilityType.Undefined)
            {
                var visibility = new OpenApiString(attribute.Visibility.ToDisplayName());

                parameter.Extensions.Add("x-ms-visibility", visibility);
            }

            return(parameter);
        }
 public FakeTypeVisitor(VisitorCollection visitorCollection)
     : base(visitorCollection)
 {
 }
Exemplo n.º 38
0
        /// <summary>
        /// Generates the OpenAPI document.
        /// </summary>
        /// <param name="project">Project path.</param>
        /// <param name="configuration">Copile configuration.</param>
        /// <param name="version">OpenAPI version.</param>
        /// <param name="format">OpenAPI output format.</param>
        /// <param name="output">Output path.</param>
        /// <param name="console">Value indicating whether to render the document on console or not.</param>
        public void Generate(
            [Option('p', Description = "Project path. Default is current directory")] string project  = ".",
            [Option('c', Description = "Configuration. Default is 'Debug'")] string configuration     = "Debug",
            [Option('t', Description = "Target framework. Default is 'netcoreapp2.1'")] string target = "netcoreapp2.1",
            [Option('v', Description = "OpenAPI spec version. Value can be either 'v2' or 'v3'. Default is 'v2'")] OpenApiVersionType version      = OpenApiVersionType.V2,
            [Option('f', Description = "OpenAPI output format. Value can be either 'json' or 'yaml'. Default is 'yaml'")] OpenApiFormatType format = OpenApiFormatType.Json,
            [Option('o', Description = "Generated OpenAPI output location. Default is 'output'")] string output = "output",
            bool console = false)
        {
            var pi = default(ProjectInfo);

            try
            {
                pi = new ProjectInfo(project, configuration, target);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);

                return;
            }

            var req = new Mock <HttpRequest>();

            req.SetupGet(p => p.Scheme).Returns("http");
            req.SetupGet(p => p.Host).Returns(new HostString("localhost", 7071));

            var filter         = new RouteConstraintFilter();
            var acceptor       = new OpenApiSchemaAcceptor();
            var namingStrategy = new CamelCaseNamingStrategy();
            var collection     = VisitorCollection.CreateInstance();
            var helper         = new DocumentHelper(filter, acceptor);
            var document       = new Document(helper);

            var swagger = default(string);

            try
            {
                swagger = document.InitialiseDocument()
                          .AddMetadata(pi.OpenApiInfo)
                          .AddServer(req.Object, pi.HostJsonHttpSettings.RoutePrefix)
                          .AddNamingStrategy(namingStrategy)
                          .AddVisitors(collection)
                          .Build(pi.CompiledDllPath)
                          .RenderAsync(version.ToOpenApiSpecVersion(), format.ToOpenApiFormat())
                          .Result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            if (console)
            {
                Console.WriteLine(swagger);
            }

            var outputpath = Path.IsPathFullyQualified(output)
                                 ? output
                                 : $"{pi.CompiledPath}{directorySeparator}{output}";

            if (!Directory.Exists(outputpath))
            {
                Directory.CreateDirectory(outputpath);
            }

            File.WriteAllText($"{outputpath}{directorySeparator}swagger.{format.ToDisplayName()}", swagger, Encoding.UTF8);
        }
        /// <summary>
        /// Gets or sets the visitor party.
        /// </summary>
        /// <returns>Returns visitorCollection</returns>
        private VisitorCollection RetrieveVisitorParty()
        {
            var visitorCollection = new VisitorCollection();
            var visitor = this.RecentPersons.Where(l => l.PersonType.Equals(PersonType.Visitor)).ToList();
            visitor.Iterate(v => PersonMapper.VisitorMapper(visitorCollection, v));

            return visitorCollection;
        }
Exemplo n.º 40
0
        public override VisitorCollection SelectVisitors(int userID, int pageNumber, int pageSize, out int totalCount)
        {
            totalCount = 0;
            VisitorCollection visitors = new VisitorCollection();

            using (SqlQuery query = new SqlQuery())
            {
                query.Pager.PageNumber = pageNumber;
                query.Pager.PageSize = pageSize;
                query.Pager.SelectCount = true;
                query.Pager.SortField = "CreateDate";
                query.Pager.TableName = "bx_UserVisitors";
                query.Pager.Condition = "UserID = @UserID";

                query.CreateParameter<int>("@UserID", userID, SqlDbType.Int);

                using (XSqlDataReader reader = query.ExecuteReader())
                {
                    visitors = new VisitorCollection(reader);

                    if (reader.NextResult())
                    {
                        while (reader.Read())
                            totalCount = reader.Get<int>(0);
                    }
                }
            }

            return visitors;
        }
Exemplo n.º 41
0
        /// <inheritdoc />
        public IDocument AddVisitors(VisitorCollection collection)
        {
            this._collection = GenericExtensions.ThrowIfNullOrDefault(collection);

            return(this);
        }
 public void Init()
 {
     this._visitorCollection = VisitorCollection.CreateInstance();
     this._visitor           = new DictionaryObjectTypeVisitor(this._visitorCollection);
     this._strategy          = new CamelCaseNamingStrategy();
 }
        /// <inheritdoc />
        public IDocument AddVisitors(VisitorCollection collection)
        {
            this._collection = collection.ThrowIfNullOrDefault();

            return(this);
        }