public ActionResult Fortunes(string providerName)
        {
            List<Fortune> fortunes = new List<Fortune>();

            using (EntityFramework db = new EntityFramework(providerName))
            {
                fortunes.AddRange(db.Fortunes);
            }

            fortunes.Add(new Fortune { ID = 0, Message = "Additional fortune added at request time." });
            fortunes.Sort();

            return View("Fortunes", fortunes);
        }
        public ActionResult Index(string providerName, int? queries)
        {
            List<World> worlds = new List<World>(queries ?? 1);

            using (EntityFramework db = new EntityFramework(providerName))
            {
                Random random = new Random();

                for (int i = 0; i < worlds.Capacity; i++)
                {
                    int randomID = random.Next(0, 10000) + 1;
                    worlds.Add(db.Worlds.Find(randomID));
                }
            }

            return queries != null ? Json(worlds, JsonRequestBehavior.AllowGet)
                                   : Json(worlds[0], JsonRequestBehavior.AllowGet);
        }
 public static DocumentationEntityType ToDocumentationEntityType(this EntityType type, EntityFramework entityFramework)
 {
     return(new DocumentationEntityType(entityFramework, type));
 }
Ejemplo n.º 4
0
        private EntityFramework CreateEntityFrameworkFromDocs()
        {
            EntityFramework edmx = new EntityFramework();

            if (!string.IsNullOrEmpty(options.SourceMetadataPath))
            {
                try
                {
                    if (!System.IO.File.Exists(options.SourceMetadataPath))
                    {
                        throw new System.IO.FileNotFoundException($"Unable to locate source file: {options.SourceMetadataPath}");
                    }

                    using (System.IO.FileStream stream = new System.IO.FileStream(options.SourceMetadataPath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    {
                        if (options.Formats.HasFlag(MetadataFormat.EdmxInput))
                        {
                            edmx = ODataParser.Deserialize <EntityFramework>(stream);
                        }
                        else if (options.Formats.HasFlag(MetadataFormat.SchemaInput))
                        {
                            var schema = ODataParser.Deserialize <Schema>(stream);
                            edmx = new EntityFramework();
                            edmx.DataServices.Schemas.Add(schema);
                        }
                        else
                        {
                            throw new InvalidOperationException("Source file was specified but no format for source file was provided.");
                        }
                    }
                    if (options.Namespaces != null && options.Namespaces.Any())
                    {
                        var schemas = edmx.DataServices.Schemas.ToArray();
                        foreach (var s in schemas)
                        {
                            if (!options.Namespaces.Contains(s.Namespace))
                            {
                                edmx.DataServices.Schemas.Remove(s);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Unable to deserialize source template file: {ex.Message}");
                    if (ex.InnerException != null)
                    {
                        Console.WriteLine($"{ex.InnerException.Message}");
                    }
                    return(null);
                }
            }

            bool generateNewElements = !options.SkipMetadataGeneration;

            // Add resources
            if (Documents.Files.Any())
            {
                foreach (var resource in Documents.Resources)
                {
                    var targetSchema = FindOrCreateSchemaForNamespace(resource.Name.NamespaceOnly(), edmx, generateNewElements: generateNewElements);
                    if (targetSchema != null)
                    {
                        AddResourceToSchema(targetSchema, resource, edmx, generateNewElements: generateNewElements);
                    }
                }

                // Figure out the EntityCollection
                this.BuildEntityContainer(edmx, options.BaseUrl);

                // Add actions to the collection
                this.ProcessRestRequestPaths(edmx, options.BaseUrl);
            }

            return(edmx);
        }
Ejemplo n.º 5
0
        private void ParseInstanceAnnotations(IEnumerable <ParameterDefinition> annotations, ResourceDefinition containedResource, EntityFramework edmx)
        {
            foreach (var prop in annotations)
            {
                var qualifiedName = prop.Name.Substring(1);
                var ns            = qualifiedName.NamespaceOnly();
                var localName     = qualifiedName.TypeOnly();

                Term term = new Term {
                    Name = localName, AppliesTo = containedResource.Name, Type = prop.Type.ODataResourceName()
                };
                if (!string.IsNullOrEmpty(prop.Description))
                {
                    term.Annotations.Add(new Annotation {
                        Term = Term.LongDescriptionTerm, String = prop.Description
                    });
                }

                var targetSchema = FindOrCreateSchemaForNamespace(ns, edmx, overrideNamespaceFilter: true);
                if (null != targetSchema)
                {
                    targetSchema.Terms.Add(term);
                }
            }
        }
Ejemplo n.º 6
0
        private static void MergePropertiesIntoSchema <TProp>(string typeName, List <TProp> schemaProps, IEnumerable <ParameterDefinition> docProps, EntityFramework edmx, bool generateNewElements)
            where TProp : Property, new()
        {
            var documentedProperties = docProps.ToDictionary(x => x.Name, x => x);

            foreach (var schemaProp in schemaProps)
            {
                ParameterDefinition documentedVersion = null;
                if (documentedProperties.TryGetValue(schemaProp.Name, out documentedVersion))
                {
                    // Compare / update schema with data from documentation
                    var docProp = ConvertParameterToProperty <Property>(typeName, documentedVersion);
                    LogIfDifferent(schemaProp.Nullable, docProp.Nullable, $"Type {typeName}: Property {docProp.Name} has a different nullable value than documentation.");
                    LogIfDifferent(schemaProp.TargetEntityType, docProp.TargetEntityType, $"Type {typeName}: Property {docProp.Name} has a different target entity type than documentation.");
                    LogIfDifferent(schemaProp.Type, docProp.Type, $"Type {typeName}: Property {docProp.Name} has a different Type value than documentation ({schemaProp.Type},{docProp.Type}).");
                    LogIfDifferent(schemaProp.Unicode, docProp.Unicode, $"Type {typeName}: Property {docProp.Name} has a different unicode value than documentation ({schemaProp.Unicode},{docProp.Unicode}).");
                    documentedProperties.Remove(documentedVersion.Name);

                    AddDescriptionAnnotation(typeName, schemaProp, documentedVersion);
                }
                else
                {
                    // Log out that this property wasn't in the documentation
                    Console.WriteLine($"UndocumentedProperty: {typeName} defines {schemaProp.Name} in the schema but has no matching documentation.");
                }
            }

            if (generateNewElements)
            {
                foreach (var newPropDef in documentedProperties.Values)
                {
                    // Create new properties based on the documentation
                    var newProp = ConvertParameterToProperty <TProp>(typeName, newPropDef);
                    schemaProps.Add(newProp);
                }
            }
        }
Ejemplo n.º 7
0
        public override async Task PublishToFolderAsync(string outputFolder)
        {
            string outputFilenameSuffix = "";

            // Step 1: Generate an EntityFramework OM from the documentation and/or template file
            EntityFramework framework = CreateEntityFrameworkFromDocs();

            if (null == framework)
            {
                return;
            }

            if (!string.IsNullOrEmpty(options.MergeWithMetadataPath))
            {
                EntityFramework secondFramework = CreateEntityFrameworkFromDocs(options.MergeWithMetadataPath, generateFromDocs: false);
                framework             = framework.MergeWith(secondFramework);
                outputFilenameSuffix += "-merged";
            }

            // Step 1a: Apply an transformations that may be defined in the documentation
            if (!string.IsNullOrEmpty(options.TransformOutput))
            {
                PublishSchemaChangesConfigFile transformations = DocSet.TryLoadConfigurationFiles <PublishSchemaChangesConfigFile>(options.DocumentationSetPath).Where(x => x.SchemaChanges.TransformationName == options.TransformOutput).FirstOrDefault();
                if (null == transformations)
                {
                    throw new KeyNotFoundException($"Unable to locate a transformation set named {options.TransformOutput}. Aborting.");
                }

                string[] versionsToPublish = options.Version?.Split(new char[] { ',', ' ' });
                framework.ApplyTransformation(transformations.SchemaChanges, versionsToPublish);
                if (!string.IsNullOrEmpty(options.Version))
                {
                    outputFilenameSuffix += $"-{options.Version}";
                }
            }

            if (options.Sort)
            {
                // Sorts the objects in collections, so that we have consistent output regardless of input
                framework.SortObjectGraph();
            }

            if (options.ValidateSchema)
            {
                framework.ValidateSchemaTypes();
            }

            // Step 2: Generate XML representation of EDMX
            string xmlData = null;

            if (options.Formats.HasFlag(MetadataFormat.EdmxOutput))
            {
                xmlData = ODataParser.Serialize <EntityFramework>(framework, options.AttributesOnNewLines);
            }
            else if (options.Formats.HasFlag(MetadataFormat.SchemaOutput))
            {
                xmlData = ODataParser.Serialize <Schema>(framework.DataServices.Schemas.First(), options.AttributesOnNewLines);
            }

            // Step 3: Write the XML to disk

            var outputFullName = GenerateOutputFileFullName(options.SourceMetadataPath, outputFolder, outputFilenameSuffix);

            Console.WriteLine($"Publishing metadata to {outputFullName}");

            using (var writer = System.IO.File.CreateText(outputFullName))
            {
                await writer.WriteAsync(xmlData);

                await writer.FlushAsync();

                writer.Close();
            }
        }
Ejemplo n.º 8
0
 public DocumentationNavigationProperty(EntityFramework entityFramework, EntityType entityType, NavigationProperty property)
     : base(entityFramework, entityType, property)
 {
 }
        private static void CreateTotalSumRow(PdfPTable table, decimal totalSum, EntityFramework.Data.Dates date)
        {
            PdfPCell totalSumPhrase = new PdfPCell(new Phrase("Total Sum for " + String.Format(DatesFormattingString, date.Date) + ":"));
            totalSumPhrase.Colspan = 4;
            totalSumPhrase.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
            table.AddCell(totalSumPhrase);

            PdfPCell totalSumValue = new PdfPCell(new Phrase(String.Format(ValuesFormattingString, totalSum), defaultBoldFont));
            totalSumValue.HorizontalAlignment = 2;
            table.AddCell(totalSumValue);
        }
Ejemplo n.º 10
0
 public virtual void ApplyTransformation(BaseModifications value, EntityFramework edmx, string[] versions)
 {
     TransformationHelper.ApplyTransformation(this, value, edmx, versions);
 }
 public static void ApplyTransformationToCollection <T_mod, T_target>(Dictionary <string, T_mod> modifications, List <T_target> targets, EntityFramework edmx, string[] versions)
     where T_target : ITransformable, new()
     where T_mod : BaseModifications
 {
     foreach (var mod in modifications)
     {
         var filteredTargets = targets.Where(x => x.ElementIdentifier.Equals(mod.Key)).ToArray();
         if (filteredTargets.Any())
         {
             foreach (var target in filteredTargets)
             {
                 if (mod.Value.Remove)
                 {
                     targets.Remove(target);
                 }
                 else if (versions != null && mod.Value.AvailableInVersions != null && !IsVersionMatch(versions, mod.Value.AvailableInVersions))
                 {
                     targets.Remove(target);
                 }
                 else
                 {
                     target.ApplyTransformation(mod.Value, edmx, versions);
                 }
             }
         }
         else if (!mod.Value.Remove && (versions == null || mod.Value.AvailableInVersions == null || IsVersionMatch(versions, mod.Value.AvailableInVersions)))
         {
             // Create the target and apply properties
             var target = new T_target();
             target.ElementIdentifier = mod.Key;
             target.ApplyTransformation(mod.Value, edmx, versions);
             targets.Add(target);
         }
         else
         {
             // Hmm, we probably missed something that we expected to find.
             Console.WriteLine($"Unable to locate {mod.Key}.");
         }
     }
 }
        public static List <Annotation> GetAnnotationsForProperty(this Property targetProperty, ComplexType complexType, EntityFramework entityFramework)
        {
            string targetType      = entityFramework.LookupIdentifierForType(complexType);
            var    targetNamespace = targetType.NamespaceOnly();
            var    schema          = entityFramework.DataServices.Schemas.FirstOrDefault(s => s.Namespace == targetNamespace);

            if (schema != null)
            {
                string target      = $"{targetType}/{targetProperty.Name}";
                var    annotations = schema.Annotations.FirstOrDefault(a => a.Target == target);
                if (annotations != null)
                {
                    return(annotations.AnnotationList);
                }
            }
            return(new List <Annotation>());
        }
 public static DocumentationProperty ToDocumentationProperty(this Property property, EntityFramework entityFramework, ComplexType complexType)
 {
     return(new DocumentationProperty(entityFramework, complexType, property));
 }
 public static DocumentationNavigationProperty ToDocumentationNavigationProperty(this NavigationProperty property, EntityFramework entityFramework, EntityType entityType)
 {
     return(new DocumentationNavigationProperty(entityFramework, entityType, property));
 }
Ejemplo n.º 15
0
 public List <TB_USERS> GetAllUsers()
 {
     return(EntityFramework.Set <TB_USERS>().ToList());
 }
Ejemplo n.º 16
0
        // GET: Feed
        public async Task <ActionResult> Home()
        {
            var authenticateResult = await HttpContext.GetOwinContext().Authentication.AuthenticateAsync("ExternalCookie");

            if (Session["Tweets"] is null || (DateTime)Session["TwitterTimer"] < DateTime.Now.Subtract(new TimeSpan(0, 2, 0)))
            {
                //grab user access token and secret from claim
                var oauthToken  = authenticateResult.Identity.Claims.FirstOrDefault(x => x.Type == ("urn:twitter:access_token")).Value;
                var oauthSecret = authenticateResult.Identity.Claims.FirstOrDefault(x => x.Type == ("urn:twitter:access_token_secret")).Value;

                string Key    = WebConfigurationManager.AppSettings["TwitterKey"];
                string Secret = WebConfigurationManager.AppSettings["TwitterSecret"];

                RateLimit.RateLimitTrackerMode = RateLimitTrackerMode.TrackAndAwait;

                //access Twitter API and get user's current  home timeline
                Auth.SetUserCredentials(Key, Secret, oauthToken, oauthSecret);
                var twitterUser = Tweetinvi.User.GetAuthenticatedUser();

                // Get more control over the request with a HomeTimelineParameters
                var homeTimelineParameter = new HomeTimelineParameters
                {
                    MaximumNumberOfTweetsToRetrieve = 100
                };
                Session["Tweets"]       = (twitterUser.GetHomeTimeline(homeTimelineParameter)).ToArray();
                Session["TwitterTimer"] = DateTime.Now;
            }

            var userTimeline = Session["Tweets"] as Tweetinvi.Models.ITweet[];

            using (var context = new EntityFramework())
            {
                //get the current userID
                long user = Convert.ToInt64(authenticateResult.Identity.Claims.FirstOrDefault(x => x.Type == "urn:twitter:userid").Value);

                HttpClient    client     = new HttpClient();
                StringBuilder sourceText = new StringBuilder();

                //get the current topics the user follows
                FeedModel feed = new FeedModel
                {
                    FollowedTopics = ((from category in context.Set <Category>()
                                       where (
                                           (from subcat in context.User_Category
                                            where subcat.UserID.Equals(user)
                                            select subcat.CategoryID)
                                           .ToList())
                                       .Contains(category.ID)
                                       select category.CID)
                                      .ToList().Select(x => new Category {
                        CID = x
                    })).ToList(),
                    FollowedSources = ((from source in context.Set <Publisher>()
                                        where (
                                            (from subcat in context.User_Publisher
                                             where subcat.UserID.Equals(user)
                                             select subcat.PublisherID)
                                            .ToList())
                                        .Contains(source.PID)
                                        select new { source.PID, source.Name })
                                       .ToList().Select(x => new Publisher {
                        PID = x.PID, Name = x.Name
                    })).ToList(),
                    Bookmarked_Articles = (from bookmark in context.Set <Bookmarked_Article>()
                                           where bookmark.UserID == user
                                           select new { bookmark.Title })
                                          .ToList().Select(x => new Bookmarked_Article {
                        Title = x.Title
                    }).ToList()
                };
                feed.Articles = new List <Bookmarked_Article>();

                foreach (var source in feed.FollowedSources)
                {
                    sourceText.Append(String.Format("{0},", source.PID));
                }

                //grab 100 headlines based on the users interests
                string             newsRequest = String.Format("https://newsapi.org/v2/top-headlines?sources={0}&pagesize=100&apiKey=8919f2f78e174c058c8e9745f90524fa", sourceText.ToString());
                HttpRequestMessage request     = new HttpRequestMessage(HttpMethod.Get, newsRequest);
                var result = await client.SendAsync(request);

                int articleCount = 0;
                if (result.IsSuccessStatusCode)
                {
                    var articleJSON = JObject.Parse(result.Content.ReadAsStringAsync().Result);

                    foreach (var article in articleJSON["articles"])
                    {
                        feed.Articles.Add(
                            new Bookmarked_Article
                        {
                            AID           = articleCount,
                            SourceName    = (string)article["source"]["id"],
                            Author        = (string)article["author"],
                            Title         = (string)article["title"],
                            Description   = (string)article["description"],
                            URL           = (string)article["url"],
                            URlToImage    = (string)article["urlToImage"],
                            PublishedDate = (DateTime)article["publishedAt"]
                        });
                        articleCount++;
                    }
                }

                sourceText.Clear();

                //grab 100 articles based on user interests
                foreach (var cat in feed.FollowedTopics)
                {
                    string categoryRequest = String.Format("https://newsapi.org/v2/top-headlines?country=us&language=us&category={0}&pagesize=100&apiKey=8919f2f78e174c058c8e9745f90524fa", cat.CID.ToString());
                    request = new HttpRequestMessage(HttpMethod.Get, categoryRequest);
                    result  = await client.SendAsync(request);

                    if (result.IsSuccessStatusCode)
                    {
                        var articleJSON = JObject.Parse(result.Content.ReadAsStringAsync().Result);
                        foreach (var article in articleJSON["articles"])
                        {
                            feed.Articles.Add(
                                new Bookmarked_Article
                            {
                                AID           = articleCount,
                                SourceName    = (string)article["source"]["name"],
                                Author        = (string)article["author"],
                                Title         = (string)article["title"],
                                Description   = (string)article["description"],
                                URL           = (string)article["url"],
                                URlToImage    = (string)article["urlToImage"],
                                PublishedDate = (DateTime)article["publishedAt"]
                            });
                            articleCount++;
                        }
                    }
                }

                //save list of articles to cache
                Session["Articles"] = feed.Articles;

                //shuffle order of articles
                feed.Articles = feed.Articles.OrderBy(x => Guid.NewGuid()).ToList();

                //aggregate news articles and tweets into content block objects
                List <ContentBlock> contentBlocks = new List <ContentBlock>();
                for (int i = 0; i < userTimeline.Length && i < feed.Articles.Count; i += 6)
                {
                    try
                    {
                        var _artList = new List <Bookmarked_Article>()
                        {
                            feed.Articles[i], feed.Articles[i + 1]
                        };
                        var _twList = new List <Tweetinvi.Models.ITweet>()
                        {
                            userTimeline[i], userTimeline[i + 1], userTimeline[i + 2], userTimeline[i + 3], userTimeline[i + 4], userTimeline[i + 5]
                        };

                        contentBlocks.Add(
                            new ContentBlock
                        {
                            Articles = _artList,
                            Tweets   = _twList
                        });
                    }
                    catch { break; }
                }
                feed.MixedFeed = contentBlocks;

                return(View(feed));
            }
        }
        private static void CreateTableRow(EntityFramework.Data.Sales sale, PdfPTable table)
        {
            table.AddCell(sale.Products.Name);

            PdfPCell quantity = new PdfPCell(new Phrase(sale.Quantity.ToString() + " " + sale.Products.Measurements.Name));
            quantity.HorizontalAlignment = 1;
            table.AddCell(quantity);

            PdfPCell unitPrice = new PdfPCell(new Phrase(String.Format(ValuesFormattingString, sale.UnitPrice)));
            unitPrice.HorizontalAlignment = 1;
            table.AddCell(unitPrice);

            table.AddCell(sale.Supermarkets.Name);

            PdfPCell sum = new PdfPCell(new Phrase(String.Format(ValuesFormattingString, sale.Sum)));
            sum.HorizontalAlignment = 2;
            table.AddCell(sum);
        }
        private static void InvokeApplyTransformationToCollection(IDictionary mods, IList target, EntityFramework edmx, string[] versions)
        {
            Type T_mod    = mods.GetType().GetGenericArguments()[1];   // Get the type used for the value
            Type T_target = target.GetType().GetGenericArguments()[0]; // Get the type used by the list

            var method = typeof(TransformationHelper).GetMethod("ApplyTransformationToCollection", BindingFlags.Static | BindingFlags.Public);

            method = method.MakeGenericMethod(T_mod, T_target);
            method.Invoke(null, new object[] { mods, target, edmx, versions });
        }
        private static void CreateSubtableHeader(EntityFramework.Data.Dates date, PdfPTable table)
        {
            PdfPCell dateOfSubtable = new PdfPCell(new Phrase(String.Format(DatesFormattingString, date.Date)));
            dateOfSubtable.Colspan = 5;
            dateOfSubtable.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
            dateOfSubtable.BackgroundColor = backgroundColor;
            table.AddCell(dateOfSubtable);

            PdfPCell product = new PdfPCell(new Phrase("Product", defaultBoldFont));
            product.BackgroundColor = backgroundColor;
            table.AddCell(product);

            PdfPCell quantity = new PdfPCell(new Phrase("Quantity", defaultBoldFont));
            quantity.BackgroundColor = backgroundColor;
            table.AddCell(quantity);

            PdfPCell unitPrice = new PdfPCell(new Phrase("Unit Price", defaultBoldFont));
            unitPrice.BackgroundColor = backgroundColor;
            table.AddCell(unitPrice);

            PdfPCell location = new PdfPCell(new Phrase("Location", defaultBoldFont));
            location.BackgroundColor = backgroundColor;
            table.AddCell(location);

            PdfPCell sum = new PdfPCell(new Phrase("Sum", defaultBoldFont));
            sum.BackgroundColor = backgroundColor;
            table.AddCell(sum);
        }
        public static void ApplyTransformationToCollection <T_mod, T_target>(Dictionary <string, T_mod> modifications, List <T_target> targets, EntityFramework edmx, string[] versions)
            where T_target : ITransformable, new()
            where T_mod : BaseModifications
        {
            foreach (var mod in modifications)
            {
                T_target[] filteredTargets = null;
                if (mod.Key.EndsWith("*"))
                {
                    filteredTargets = targets.Where(x => x.ElementIdentifier.StartsWith(mod.Key.Substring(0, mod.Key.Length - 1))).ToArray();
                }
                else
                {
                    filteredTargets = targets.Where(x => x.ElementIdentifier.Equals(mod.Key)).ToArray();
                }

                if (filteredTargets.Any())
                {
                    foreach (var target in filteredTargets)
                    {
                        if (mod.Value.Remove)
                        {
                            Console.WriteLine($"Removed {mod.Key} from output.");
                            targets.Remove(target);
                        }
                        else if (versions != null && mod.Value.AvailableInVersions != null && !IsVersionMatch(versions, mod.Value.AvailableInVersions))
                        {
                            Console.WriteLine($"Removed {mod.Key} from output because of version mis-match.");
                            targets.Remove(target);
                        }
                        else
                        {
                            target.ApplyTransformation(mod.Value, edmx, versions);
                        }
                    }
                }
                else if (!mod.Value.Remove && (versions == null || mod.Value.AvailableInVersions == null || IsVersionMatch(versions, mod.Value.AvailableInVersions)))
                {
                    if (!mod.Value.Add)
                    {
                        Console.WriteLine($"Transformation indicates {mod.Key} should be added, but missing required \"add\": true modification property.");
                    }
                    else
                    {
                        // Create the target and apply properties
                        var target = new T_target();
                        target.ElementIdentifier = mod.Key;
                        target.ApplyTransformation(mod.Value, edmx, versions);
                        targets.Add(target);
                    }
                }
                else
                {
                    // Hmm, we probably missed something that we expected to find.
                    Console.WriteLine($"Unable to locate {mod.Key}.");
                }
            }
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            char input;

            AutoMapperConfiguration.Configure();
            do
            {
                ShowMenu();

                input = Console.ReadLine().First();
                switch (input)
                {
                case 'Q':
                    break;

                case 'T':
                    List <TestResult> testResults = new List <TestResult>();

                    Console.WriteLine("# of Test Runs:");
                    NumRuns = int.Parse(Console.ReadLine());

                    //Gather Details for Test
                    Console.WriteLine("# of Sports per Run: ");
                    NumSports = int.Parse(Console.ReadLine());

                    Console.WriteLine("# of Teams per Sport: ");
                    NumTeams = int.Parse(Console.ReadLine());

                    Console.WriteLine("# of Players per Team: ");
                    NumPlayers = int.Parse(Console.ReadLine());


                    List <SportDTO>  sports  = TestData.Generator.GenerateSports(NumSports);
                    List <TeamDTO>   teams   = new List <TeamDTO>();
                    List <PlayerDTO> players = new List <PlayerDTO>();
                    foreach (var sport in sports)
                    {
                        var newTeams = TestData.Generator.GenerateTeams(sport.Id, NumTeams);
                        teams.AddRange(newTeams);
                        foreach (var team in newTeams)
                        {
                            var newPlayers = TestData.Generator.GeneratePlayers(team.Id, NumPlayers);
                            players.AddRange(newPlayers);
                        }
                    }

                    Database.Reset();
                    Database.Load(sports, teams, players);

                    for (int i = 0; i < NumRuns; i++)
                    {
                        EntityFramework efTest = new EntityFramework();
                        testResults.AddRange(RunTests(i, Framework.EntityFramework, efTest));

                        EntityFrameworkCore efCoreTest = new EntityFrameworkCore();
                        testResults.AddRange(RunTests(i, Framework.EntityFrameworkCore, efCoreTest));

                        ADONET adoTest = new ADONET();
                        testResults.AddRange(RunTests(i, Framework.ADONET, adoTest));

                        ADONetReader adoReaderTest = new ADONetReader();
                        testResults.AddRange(RunTests(i, Framework.ADONetDr, adoReaderTest));

                        DataAccess.Dapper dapperTest = new DataAccess.Dapper();
                        testResults.AddRange(RunTests(i, Framework.Dapper, dapperTest));
                    }
                    ProcessResults(testResults);

                    break;
                }
            }while (input != 'Q');
        }
        public static void ApplyTransformation(ITransformable target, BaseModifications modifications, EntityFramework edmx, string[] versions, HandlePropertyModification alternativeHandler = null)
        {
            // For eacn property on the modifications instance, if there is a matching property on target
            // then we copy the value from modification to target, if the modification value is not null
            var modificationProperties = modifications.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
                                         .Where(x => x.DeclaringType != typeof(BaseModifications));
            var targetProperties = target.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).ToDictionary(x => x.Name, x => x);

            foreach (var modsProp in modificationProperties)
            {
                var modsValue = modsProp.GetValue(modifications);
                if (null == modsValue)
                {
                    continue;
                }

                if (null != alternativeHandler && alternativeHandler(modsProp.Name, modsValue))
                {
                    continue;
                }

                Type modificationType;
                if (modsProp.IsModificationDictionary(out modificationType))
                {
                    PropertyInfo targetProp;
                    if (targetProperties.TryGetValue(modsProp.Name, out targetProp))
                    {
                        var targetValue = targetProp.GetValue(target);
                        InvokeApplyTransformationToCollection((IDictionary)modsValue, (IList)targetValue, edmx, versions);
                    }
                    else
                    {
                        Console.WriteLine($"Failed to locate a target property named '{modsProp.Name}' on '{target.GetType().Name}'.");
                    }
                }
                else if (modsProp.IsSimpleType())
                {
                    PropertyInfo targetProp;
                    if (targetProperties.TryGetValue(modsProp.Name, out targetProp))
                    {
                        targetProp.SetValue(target, modsValue);
                    }
                    else
                    {
                        Console.WriteLine($"Failed to locate a target property named '{modsProp.Name}' on '{target.GetType().Name}'.");
                    }
                }
                else
                {
                    // See if the object we're pointing at can be transformed
                    PropertyInfo targetProp;
                    if (targetProperties.TryGetValue(modsProp.Name, out targetProp))
                    {
                        object targetPropertyValue = targetProp.GetValue(target);
                        if (null == targetPropertyValue)
                        {
                            // Create a new default instance of this class, since we're trying to set properties on it
                            targetPropertyValue = CreateNewInstanceOfType(targetProp.PropertyType);
                            // Store the newly created instance back on the target object
                            targetProp.SetValue(target, targetPropertyValue);
                        }

                        ITransformable transformableTargetProperty = targetPropertyValue as ITransformable;
                        if (null != transformableTargetProperty)
                        {
                            transformableTargetProperty.ApplyTransformation((BaseModifications)modsValue, edmx, versions);
                            continue;
                        }
                    }
                    //Unsupported
                    throw new NotSupportedException();
                }
            }
        }
Ejemplo n.º 23
0
        private void AddDocPropertiesToSchemaResource(ComplexType schemaType, ResourceDefinition docResource, EntityFramework edmx, bool generateNewElements)
        {
            var docProps = (from p in docResource.Parameters
                            where !p.IsNavigatable && !p.Name.StartsWith("@")
                            select p).ToList();

            MergePropertiesIntoSchema(schemaType.Name, schemaType.Properties, docProps, edmx, generateNewElements);

            var schemaEntity = schemaType as EntityType;

            if (null != schemaEntity)
            {
                var docNavigationProps = (from p in docResource.Parameters where p.IsNavigatable && !p.Name.StartsWith("@") select p);
                MergePropertiesIntoSchema(schemaEntity.Name, schemaEntity.NavigationProperties, docNavigationProps, edmx, generateNewElements);
            }

            var docInstanceAnnotations = (from p in docResource.Parameters where p.Name != null && p.Name.StartsWith("@") select p);

            MergeInstanceAnnotationsAndRecordTerms(schemaType.Name, docInstanceAnnotations, docResource, edmx, generateNewElements);
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Returns a GameObject that has the associated Entity ID and matches the specified type.
 /// </summary>
 public static T ById <T>(uint id) where T : GameObject
 {
     return(EntityFramework.GetEntity(id) as T);
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Sets up the level ready for the round to begin.
        /// </summary>
        public void Setup()
        {
            spawnPoints        = new List <SpawnPoint>();
            constructionPoints = new List <ConstructionPointController>();
            units = new List <Unit>();

            // Set the camera
            var camera = Env.EntitySystem.FindEntityByName(cameraName);

            if (camera != null)
            {
                var host = SceneObject.Instantiate(null);
                Camera.Current = host.AddComponent <Camera>();
                Camera.Current.OnPlayerEntityAssigned += (arg) =>
                {
                    arg.HostEntity.Position = camera.GetPos();
                    arg.HostEntity.Rotation = camera.GetRotation();
                    Env.Console.ExecuteString("gamezero_cam_fov 45");
                };
            }
            else
            {
                Global.gEnv.pLog.LogError("Level Manager: Camera is missing from the level. Make sure there is a Camera named " + cameraName);
            }

            // Find the Base reference entity
            PlayerBase = EntityFramework.GetEntity <Base>();
            if (PlayerBase != null)
            {
                PlayerBase.Setup();
            }
            else
            {
                Global.gEnv.pLog.LogError("Level Manager: Player Base is missing from the level. Make sure their is an entity named " + playerBaseName);
            }

            // Find construction point reference entities
            EntityFramework.GetEntities <ConstructionPoint>().ForEach(x =>
            {
                // Create construction point
                var cell = new ConstructionPointController(x.NativeEntity.GetPos(), x.NativeEntity.GetRotation(), 4, x);
                constructionPoints.Add(cell);

                // Register callback for a Unit is added or removed. We need a reference so we can update the unit with the position of each enemy.
                cell.OnUnitPlaced  += AddUnit;
                cell.OnUnitRemoved += RemoveUnit;
            });

            // Find spawn point reference entities
            var spawnsInLevel = EntityFramework.GetEntities <SpawnPoint>();

            if (spawnsInLevel.Count == 0)
            {
                Log.Warning("Failed to find any spawn points");
            }
            else
            {
                spawnsInLevel.ForEach(x =>
                {
                    // Create spawn point
                    Path path = null;

                    if (PlayerBase != null)
                    {
                        path = new Path(x.NativeEntity.GetPos(), PlayerBase.Position);
                    }

                    var instance = new SpawnPoint(path);
                    spawnPoints.Add(instance);

                    // Register callback for when an enemy is spawned and despawned
                    instance.OnEnemySpawned   += AddUnit;
                    instance.OnEnemyDespawned += RemoveUnit;
                });
            }

            // Create a grid, if the level requires one
            var gridEntity = Env.EntitySystem.FindEntityByName("Grid");

            if (gridEntity != null)
            {
                new Grid(16, 16, 2);
            }
        }
 public BaseValueWebsiteDescription(EntityFramework.WebsiteData.BaseValueWebsiteData data)
 {
     Valor = data.Valor;
     Name = data.Name;
 }
Ejemplo n.º 27
0
 public DocumentationEntityType(EntityFramework entityFramework, EntityType entity)
     : base(entityFramework, entity)
 {
     this.IsEntity             = true;
     this.NavigationProperties = entity.NavigationProperties.Select(p => p.ToDocumentationNavigationProperty(entityFramework, entity)).ToList().AsReadOnly();
 }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            char input;

            AutoMapperConfiguration.Configure();
            do
            {
                ShowMenu();

                input = Console.ReadLine().First();
                switch (input)
                {
                case 'Q':
                    break;

                case 'C':
                    EntityFramework createEfTest = new EntityFramework();
                    createEfTest.CreateDatabase();
                    break;

                case 'T':
                    List <TestResult> testResults = new List <TestResult>();

                    Console.WriteLine("# of Test Runs:");
                    NumRuns = int.Parse(Console.ReadLine());

                    //Gather Details for Test
                    Console.WriteLine("# of Sports per Run: ");
                    NumSports = int.Parse(Console.ReadLine());

                    Console.WriteLine("# of Teams per Sport: ");
                    NumTeams = int.Parse(Console.ReadLine());

                    Console.WriteLine("# of Players per Team: ");
                    NumPlayers = int.Parse(Console.ReadLine());

                    for (int i = 0; i < NumRuns; i++)
                    {
                        EntityFramework efTest = new EntityFramework();
                        testResults.AddRange(RunInsertTest(i, Framework.EntityFramework, efTest));

                        ADONET adoTest = new ADONET();
                        testResults.AddRange(RunInsertTest(i, Framework.ADONET, adoTest));

                        //DataAccess.Dapper dapperTest = new DataAccess.Dapper();
                        //testResults.AddRange(RunTests(i, Framework.Dapper, dapperTest));
                    }

                    for (int i = 0; i < NumRuns; i++)
                    {
                        EntityFramework efTest = new EntityFramework();
                        testResults.AddRange(RunTests(i, Framework.EntityFramework, efTest));

                        ADONET adoTest = new ADONET();
                        testResults.AddRange(RunTests(i, Framework.ADONET, adoTest));

                        //DataAccess.Dapper dapperTest = new DataAccess.Dapper();
                        //testResults.AddRange(RunTests(i, Framework.Dapper, dapperTest));
                    }
                    ProcessResults(testResults);

                    break;
                }
            }while (input != 'Q');
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Walks the requestPath through the resources / entities defined in the edmx and resolves
        /// the type of request represented by the path
        /// </summary>
        /// <param name="requestPath"></param>
        /// <param name="requestMethod"></param>
        /// <param name="edmx"></param>
        /// <returns></returns>
        private static ODataTargetInfo ParseRequestTargetType(string requestPath, MethodCollection requestMethodCollection, EntityFramework edmx)
        {
            string[] requestParts = requestPath.Substring(1).Split(new char[] { '/' });

            EntityContainer entryPoint = (from s in edmx.DataServices.Schemas
                                          where s.EntityContainers.Count > 0
                                          select s.EntityContainers.FirstOrDefault()).SingleOrDefault();

            if (entryPoint == null)
            {
                throw new InvalidOperationException("Couldn't locate an EntityContainer to begin target resolution");
            }

            IODataNavigable currentObject  = entryPoint;
            IODataNavigable previousObject = null;

            for (int i = 0; i < requestParts.Length; i++)
            {
                string          uriPart    = requestParts[i];
                IODataNavigable nextObject = null;
                if (uriPart == "{var}")
                {
                    try
                    {
                        nextObject = currentObject.NavigateByEntityTypeKey(edmx);
                    }
                    catch (Exception ex)
                    {
                        throw new NotSupportedException("Unable to navigation into EntityType by key: " + currentObject.TypeIdentifier + " (" + ex.Message + ")");
                    }
                }
                else
                {
                    nextObject = currentObject.NavigateByUriComponent(uriPart, edmx);
                }

                if (nextObject == null && i == requestParts.Length - 1)
                {
                    // The last component wasn't known already, so that means we have a new thing.
                    // We assume that if the uriPart doesnt' have a namespace that this is a navigation property that isn't documented.

                    // TODO: We may need to be smarter about this if we allow actions without namespaces. If that's the case, we could look at the request
                    // method to figure out of this appears to be an action (POST?) or a navigationProperty (GET?)

                    return(new ODataTargetInfo
                    {
                        Name = uriPart,
                        Classification = uriPart.HasNamespace() ? ODataTargetClassification.Unknown : ODataTargetClassification.NavigationProperty,
                        QualifiedType = edmx.LookupIdentifierForType(currentObject)
                    });
                }
                else if (nextObject == null)
                {
                    throw new InvalidOperationException(
                              string.Format("Uri path requires navigating into unknown object hierarchy: missing property '{0}' on '{1}'", uriPart, currentObject.TypeIdentifier));
                }
                previousObject = currentObject;
                currentObject  = nextObject;
            }

            var response = new ODataTargetInfo
            {
                Name          = requestParts.Last(),
                QualifiedType = edmx.LookupIdentifierForType(currentObject)
            };

            if (currentObject is EntityType)
            {
                response.Classification = ODataTargetClassification.EntityType;
            }
            else if (currentObject is EntityContainer)
            {
                response.Classification = ODataTargetClassification.EntityContainer;
            }
            else if (currentObject is ODataSimpleType)
            {
                response.Classification = ODataTargetClassification.SimpleType;
            }
            else if (currentObject is ODataCollection)
            {
                if (previousObject != entryPoint)
                {
                    response.Classification = ODataTargetClassification.NavigationProperty;
                    response.QualifiedType  = edmx.LookupIdentifierForType(previousObject);
                }
                else
                {
                    response.Classification = ODataTargetClassification.EntitySet;
                }
            }
            else if (currentObject is ComplexType)
            {
                throw new NotSupportedException(string.Format("Encountered a ComplexType. This is probably a doc bug where type '{0}' should be defined with keyProperty to be an EntityType", currentObject.TypeIdentifier));
            }
            else
            {
                throw new NotSupportedException(string.Format("Unhandled object type: {0}", currentObject.GetType().Name));
            }

            return(response);
        }
 public static string GetTypeNameMarkdown(this Property property, EntityFramework entityFramework)
 {
     return(GetTypeNameMarkdown(property.Type, entityFramework));
 }