public ConfigureFubuMVC()
        {
            // This line turns on the basic diagnostics and request tracing
            IncludeDiagnostics(true);

            Actions
                .IncludeTypesNamed(x => x.EndsWith("Projection"))
                .IncludeTypesNamed(x => x.EndsWith("CommandHandler"));

            var httpVerbs = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { "GET", "POST", "DELETE", "PUT" };
            httpVerbs.Each(verb => Routes.ConstrainToHttpMethod(action => action.Method.Name.Equals(verb, StringComparison.InvariantCultureIgnoreCase), verb));
            httpVerbs.Each(verb => Routes.IgnoreMethodsNamed(verb));

            Routes
                .IgnoreMethodSuffix("Html")
                .RootAtAssemblyNamespace()
                .UrlPolicy<ProjectionUrlPolicy>()
                .UrlPolicy<CommandHandlerUrlPolicy>()
                .HomeIs<CreateFormProjection>(x => x.Get());

            this.UseRazor();

            // Match views to action methods by matching
            // on model type, view name, and namespace
            Views.TryToAttachWithDefaultConventions();
        }
        public void RepositoryCRUDTest()
        {
            string testName = nameof(RepositoryCRUDTest);

            _repos.Each(testName, (tn, repo) =>
            {
                StartMessage(tn, repo);
                string name = 5.RandomLetters();
                Parent p    = new Parent();
                p.Name      = name;

                p = repo.Save(p);
                Expect.IsGreaterThan(p.Id, 0, "Id wasn't set");

                Parent retrieved = repo.Retrieve <Parent>(p.Id);
                Expect.AreEqual(name, p.Name);
                Expect.AreEqual(name, retrieved.Name);
                Expect.AreEqual(p.Id, retrieved.Id);
                Expect.AreEqual(p.Uuid, retrieved.Uuid);

                string newName = 8.RandomLetters();
                retrieved.Name = newName;
                repo.Save(retrieved);

                Parent again = repo.Retrieve <Parent>(p.Uuid);
                Expect.AreEqual(newName, again.Name);

                repo.Delete(again);

                Parent shouldBeNull = repo.Retrieve <Parent>(p.Id);
                Expect.IsNull(shouldBeNull);

                EndMessage(tn);
            });
        }
        public virtual bool SignOn(ICharacter character)
        {
            lock (Locker)
            {
                var name = character.Name;
                if (!CharacterDictionary.TryAdd(name, character))
                {
                    return(false);
                }

                Collections.Each(x => x.SignOn(name));
                return(true);
            }
        }
Exemple #4
0
 public void HoldPOs()
 {
     _pos.Each(p =>
     {
         Hold hold = new Hold()
         {
             ReasonCode  = p.GetHoldReason().ReasonCode,
             PONumber    = Convert.ToInt32(p.Number),
             HoldDate    = DateTime.Now,
             ReleaseDate = DateTime.Now.AddDays(2)
         };
         hold.AddAsync();
     });
 }
        public static GitReleaseNotes SinceVersion(string packageId, string gitRepoPath, int major, int minor = 0, int patch = 0)
        {
            string version = $"{major}.{minor}.{patch}";

            if (!_logCache.ContainsKey(packageId) || !_logCache[packageId].ContainsKey(version))
            {
                lock (_logCacheLock)
                {
                    HashSet <GitLog> logsSinceLast = GitLog.SinceVersion(gitRepoPath, major, minor, patch);
                    GitReleaseNotes  result        = new GitReleaseNotes(version, packageId);
                    logsSinceLast.Each(gl =>
                    {
                        string prefix = $"{packageId}:";
                        if (gl.Subject.StartsWith(prefix))
                        {
                            result.AddBullet(gl.Subject.TruncateFront(prefix.Length), gl.AbbreviatedCommitHash);
                        }
                    });

                    _logCache.AddMissing(packageId, new Dictionary <string, GitReleaseNotes>());
                    _logCache[packageId].AddMissing(version, result);
                }
            }
            return(_logCache[packageId][version]);
        }
Exemple #6
0
        /// <summary>
        ///     Calculates the compatible protocols between a source device and a target device by their ids.
        /// </summary>
        public IEnumerable <Protocol> GetCompatibeProtocols(Guid sourceDeviceId, Guid targetDeviceId)
        {
            // TODO: optimize
            Device sourceDevice = _deviceService.GetById(sourceDeviceId);
            Device targetDevice = _deviceService.GetById(targetDeviceId);

            if (sourceDevice == null || targetDevice == null)
            {
                return(Enumerable.Empty <Protocol>());
            }

            HashSet <Guid> sourceProtocols = sourceDevice.Services.GetModel().Services.
                                             GetInterfaces().Where(m => m.ProtocolId.HasValue).Select(m => m.ProtocolId.Value).ToHashSet();

            HashSet <Guid> unionOfProtocols = targetDevice.Services.GetModel().Services
                                              .GetInterfaces().Where(m => m.ProtocolId.HasValue).Select(m => m.ProtocolId.Value).ToHashSet();

            // union of results
            sourceProtocols.Each(m =>
            {
                if (!unionOfProtocols.Contains(m))
                {
                    unionOfProtocols.Remove(m);
                }
            });

            if (_logger.IsDebugEnabled)
            {
                _logger.Debug("Found {0} compatible protocols", sourceProtocols.Count);
            }

            return(_protocolService.GetByIds(unionOfProtocols.ToList()));
        }
        public void UpdateShouldntResetId()
        {
            string testName = MethodBase.GetCurrentMethod().Name;

            _repos.Each(testName, (tn, repo) =>
            {
                repo.AddType(typeof(TestDto));
                string name1  = 8.RandomLetters();
                string name2  = 8.RandomLetters();
                TestDto value = new TestDto {
                    Name = name1
                };
                Expect.IsTrue(value.Id == 0, "Id should have been 0");
                repo.Save(value);
                Expect.IsNotNullOrEmpty(value.Uuid, "Uuid didn't get set");
                long id     = value.Id;
                string uuid = value.Uuid;
                Message.PrintLine("The id is {0}", id);
                Message.PrintLine("The Uuid is {0}", uuid);
                Expect.IsTrue(value.Id > 0, "Id should have been greater than 0");
                TestDto retrieved = repo.Retrieve <TestDto>(id);
                Expect.AreEqual(name1, retrieved.Name);
                retrieved.Name = name2;
                repo.Save(retrieved);
                Expect.AreEqual(id, retrieved.Id);
                Expect.AreEqual(uuid, retrieved.Uuid);

                retrieved = repo.Retrieve <TestDto>(id);
                Expect.AreEqual(id, retrieved.Id, "The id changed");
                Expect.AreEqual(uuid, retrieved.Uuid);
                Expect.AreEqual(name2, retrieved.Name);

                Pass("{0}:{1}"._Format((string)tn, repo.GetType().Name));
            });
        }
 private static void OutputWasIs(HashSet <OldToNewIdMapping> wasIs)
 {
     wasIs.Each(otnim =>
     {
         OutLineFormat("Type: {0}, Uuid: {1}, OldId: {2}, NewId: {3}", otnim.DaoType.Name, otnim.Uuid, otnim.OldId, otnim.NewId);
     });
 }
Exemple #9
0
        public override void didUpdateWidget(StatefulWidget _oldWidget)
        {
            base.didUpdateWidget(_oldWidget);
            AnimatedSwitcher oldWidget = _oldWidget as AnimatedSwitcher;

            if (widget.transitionBuilder != oldWidget.transitionBuilder)
            {
                _outgoingEntries.Each(_updateTransitionForEntry);
                if (_currentEntry != null)
                {
                    _updateTransitionForEntry(_currentEntry);
                }

                _markChildWidgetCacheAsDirty();
            }

            bool hasNewChild = widget.child != null;
            bool hasOldChild = _currentEntry != null;

            if (hasNewChild != hasOldChild ||
                hasNewChild && !Widget.canUpdate(widget.child, _currentEntry.widgetChild))
            {
                _childNumber += 1;
                _addEntryForNewChild(animate: true);
            }
            else if (_currentEntry != null)
            {
                D.assert(hasOldChild && hasNewChild);
                D.assert(Widget.canUpdate(widget.child, _currentEntry.widgetChild));
                _currentEntry.widgetChild = widget.child;
                _updateTransitionForEntry(_currentEntry);
                _markChildWidgetCacheAsDirty();
            }
        }
        protected internal CompilerResults Compile(string assemblyNameToCreate, string writeSourceTo)
        {
            HashSet <string> references = new HashSet <string>(DaoGenerator.DefaultReferenceAssemblies.ToArray())
            {
                typeof(JsonIgnoreAttribute).Assembly.GetFileInfo().FullName
            };

            _additionalReferenceAssemblies.Each(asm =>
            {
                FileInfo assemblyInfo = asm.GetFileInfo();
                if (references.Contains(assemblyInfo.Name))
                {
                    references.Remove(assemblyInfo.Name); // removes System.Core.dll if it is later referenced by full path
                }
                references.Add(assemblyInfo.FullName);
            });
            SchemaDefinitionCreateResult.TypeSchema.Tables.Each(type =>
            {
                references.Add(type.Assembly.GetFileInfo().FullName);
                CustomAttributeTypeDescriptor attrTypes = new CustomAttributeTypeDescriptor(type);
                attrTypes.AttributeTypes.Each(attrType => references.Add(attrType.Assembly.GetFileInfo().FullName));
            });
            references.Add(typeof(DaoRepository).Assembly.GetFileInfo().FullName);
            CompilerResults results = _daoGenerator.Compile(new DirectoryInfo(writeSourceTo), assemblyNameToCreate, references.ToArray(), false);

            return(results);
        }
        public SimpleWebsiteFubuRegistry()
        {
            IncludeDiagnostics(true);

            Applies.ToThisAssembly();

            var httpVerbs = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase)
                {"GET", "POST", "PUT", "HEAD"};

            Actions
                .IncludeTypes(t => t.Namespace.StartsWith(typeof(EndPointUrlPolicy).Namespace) && t.Name.EndsWith("Endpoint"))
                .IncludeMethods(action => httpVerbs.Contains(action.Method.Name));

            httpVerbs.Each(verb => Routes.ConstrainToHttpMethod(action => action.Method.Name.Equals(verb, StringComparison.InvariantCultureIgnoreCase), verb));

            Routes.UrlPolicy<EndPointUrlPolicy>();

            Output.ToJson.WhenCallMatches(action => action.Returns<AjaxResponse>());

            Views.TryToAttach(findViews => findViews.by_ViewModel_and_Namespace());

            // Note: Outside of a sample application, you would only configure services that Fubu requires within your FubuRegistry
            // Non-Fubu services should be configured through your container in the usual way (StructureMap Registry, etc)
            Services(s => s.AddService<IRepository, FakeRepository>());
        }
Exemple #12
0
        public void Cleanup()
        {
            WebHooksRepository repo = new WebHooksRepository();

            DeleteWebHookData(repo.Database);
            _databases.Each(DeleteWebHookData);
        }
Exemple #13
0
        public void ShouldBeAbleToRetrieveWithDynamicReturn()
        {
            HashSet <Database> dbs = DataTools.Setup();

            dbs.Each(db =>
            {
                try
                {
                    string name        = "Name_".RandomLetters(8);
                    TestTable instance = new TestTable();
                    instance.Name      = name;
                    instance.Save(db);
                    TestTable retrieved = RetrieveByNameAndValidate(db, instance);

                    SqlStringBuilder sql = db.Sql().Select(nameof(TestTable)).Where(new { Name = name });
                    dynamic queried      = sql.ExecuteDynamicReader(db).SingleOrDefault();
                    OutLineFormat("Result type is ({0})", queried.GetType().Name, ConsoleColor.Cyan);

                    Expect.AreEqual(retrieved.Id, (long)queried.Id);
                    Expect.AreEqual(retrieved.Uuid, queried.Uuid);
                    Expect.AreEqual(retrieved.Name, queried.Name);

                    Pass($"{db.GetType().Name} passed");
                }
                catch (Exception ex)
                {
                    Error($"{db.GetType().Name}: failed: {ex.Message}", ex);
                }
            });
            DataTools.Cleanup(dbs);
        }
Exemple #14
0
        private void SaveCollection()
        {
            string sql = "INSERT INTO " + typeof(T).Name.SanitizeTypeName() + " (" + GetFields() + ") VALUES (" + GetFieldHolders() + ")";

            OleDbCommand    cmd;
            OleDbConnection cn;

            CreateCommand(out cn, out cmd);

            OleDbTransaction trn = cn.BeginTransaction();

            cmd.Transaction = trn;

            _objectCollection.Each(o =>
            {
                cmd.CommandText = sql;
                cmd.Parameters.Clear();
                FillValues(ref cmd, o);
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (Exception) { }
            });
            trn.Commit();
            cn.Close();
            _reporter.ReportProgress(ProgressAction);
        }
        public CoolCodeFubuRegistry()
        {
            IncludeDiagnostics(true);

            Applies.ToThisAssembly();

            var httpVerbs = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { "GET", "POST" };

            Actions
                .IncludeTypes(t =>
                                    !string.IsNullOrEmpty(t.Namespace) &&
                                    t.Namespace.StartsWith(typeof(EndpointMarker).Namespace) &&
                                    t.Name.EndsWith(EndpointUrlPolicy.EndpointString)
                              )
                .IncludeMethods(a => httpVerbs.Contains(a.Method.Name));

            httpVerbs
               .Each(verb => Routes.ConstrainToHttpMethod(action => action.Method.Name.Equals(verb, StringComparison.InvariantCultureIgnoreCase), verb));

            Views.TryToAttach(findViews => findViews.by_ViewModel_and_Namespace());

            Routes
                .UrlPolicy<EndpointUrlPolicy>();

            HtmlConvention<CoolCodeHtmlConventions>();
        }
Exemple #16
0
        public void Evict(Func <object, bool> predicate)
        {
            HashSet <CacheItem> itemsCopy = new HashSet <CacheItem>(Items);
            HashSet <CacheItem> kept      = new HashSet <CacheItem>();
            List <CacheItem>    removed   = new List <CacheItem>();

            itemsCopy.Each(new { Removed = removed, Kept = kept }, (ctx, ci) =>
            {
                if (predicate(ci.Value))
                {
                    ctx.Removed.Add(ci);
                }
                else
                {
                    ctx.Kept.Add(ci);
                }
            });
            LastEvictionCount = removed.Count();
            Items             = kept;
            Organize();

            FireEvent(Evicted, new CacheEvictionEventArgs {
                Cache = this, EvictedItems = removed.ToArray()
            });
        }
        public PolyphonyFubuRegistry()
        {
            IncludeDiagnostics(true);

            Applies
                .ToThisAssembly();

            var httpVerbs = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { "GET", "POST", "PUT", "HEAD" };

            Actions
                .IncludeTypes(t => t.Namespace.StartsWith(typeof (EndpointUrlPolicy).Namespace) && t.Name.EndsWith("Endpoint"))
                .IncludeMethods(action => httpVerbs.Contains(action.Method.Name));

            httpVerbs
                .Each(verb => Routes.ConstrainToHttpMethod(action => action.Method.Name.Equals(verb, StringComparison.InvariantCultureIgnoreCase), verb));

            Views
                .TryToAttach(findViews => findViews.by_ViewModel());

            Routes
                .UrlPolicy<EndpointUrlPolicy>();

            Output
                .ToJson
                .WhenCallMatches(c => c.OutputType().Name.StartsWith("Ajax"));

            this.UseDefaultHtmlConventions();
        }
        public ConfigureFubuMVC()
        {
            var httpVerbs = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase){"GET", "POST", "PUT", "HEAD"};

            Applies.ToThisAssembly().ToAllPackageAssemblies();

            // This line turns on the basic diagnostics and request tracing
            IncludeDiagnostics(true);

            // All public methods from concrete classes ending in "Action"
            // in this assembly are assumed to be action methods
            Actions
                .IncludeTypes(t => t.Namespace.StartsWith(typeof(ActionUrlPolicy).Namespace) && t.Name.EndsWith("Action"))
                .IncludeMethods(action => httpVerbs.Contains(action.Method.Name));

            httpVerbs.Each(verb => Routes.ConstrainToHttpMethod(action =>
                action.Method.Name.EqualsIgnoreCase(verb), verb));

            // Policies
            Routes
                .HomeIs<HomeAction>(x => x.Get())
                .IgnoreControllerNamesEntirely()
                .IgnoreMethodSuffix("Html")
                .RootAtAssemblyNamespace()
                .UrlPolicy<ActionUrlPolicy>();

            // Match views to action methods by matching
            // on model type, view name, and namespace
            Views.TryToAttachWithDefaultConventions();
            Import<WebFormsEngine>();
        }
Exemple #19
0
 public override void Add(double n)
 {
     lock (this)
     {
         fanout.Each(f => f.Add(n));
         base.Add(n);
     }
 }
 public void ForEachIterationWithNoGarbage()
 {
     BuildHashSet();
     foreach (var element in actualHashSet.Each())
     {
         Debug.LogFormat("This is an iteration. Element = {0}", element);
     }
 }
Exemple #21
0
        public IEnumerable <IDbSaveHook> TriggerPreSaveHooks(IEnumerable <IHookedEntity> entries, bool importantHooksOnly, out bool anyStateChanged)
        {
            Guard.NotNull(entries, nameof(entries));

            anyStateChanged = false;

            var processedHooks = new HashSet <IDbSaveHook>();

            if (!entries.Any() || !_saveHooks.Any() || (importantHooksOnly && !this.HasImportantSaveHooks()))
            {
                return(processedHooks);
            }

            foreach (var entry in entries)
            {
                var e = entry; // Prevents access to modified closure

                if (HandledAlready(e, HookStage.PreSave))
                {
                    // Prevent repetitive hooking of the same entity/state/pre combination within a single request
                    continue;
                }

                var hooks = GetSaveHookInstancesFor(e, HookStage.PreSave, importantHooksOnly);

                foreach (var hook in hooks)
                {
                    // call hook
                    try
                    {
                        //Logger.DebugFormat("PRE save hook: {0}, State: {1}, Entity: {2}", hook.GetType().Name, e.InitialState, e.Entity.GetUnproxiedType().Name);
                        hook.OnBeforeSave(e);
                        processedHooks.Add(hook);
                    }
                    catch (Exception ex) when(ex is NotImplementedException || ex is NotSupportedException)
                    {
                        RegisterVoidHook(hook, e, HookStage.PreSave);
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat(ex, "PreSaveHook exception ({0})", hook.GetType().FullName);
                    }

                    // change state if applicable
                    if (e.HasStateChanged)
                    {
                        e.InitialState  = e.State;
                        anyStateChanged = true;
                    }
                }
            }

            processedHooks.Each(x => x.OnBeforeSaveCompleted());

            return(processedHooks);
        }
Exemple #22
0
 public static void Cleanup(HashSet <Database> testDatabases)
 {
     testDatabases.Each(db =>
     {
         SchemaWriter dropper = db.ServiceProvider.Get <SchemaWriter>();
         dropper.EnableDrop   = true;
         dropper.DropAllTables <TestTable>();
         db.ExecuteSql(dropper);
     });
 }
Exemple #23
0
 private void ResolveWaitingQueue()
 {
     if (waitingForMediation != null)
     {
         waitingForMediation.Each(mediated => onMediate.Dispatch(mediated));
         waitingForMediation = null;
         onPostponeMediating.RemoveAllListeners();
         onPostponeMediating = null;
     }
 }
        public bool TriggerPreSaveHooks(IEnumerable <HookedEntity> entries, bool importantHooksOnly)
        {
            bool anyStateChanged = false;

            if (entries != null)
            {
                // Skip entities explicitly marked as unhookable
                entries = entries.Where(IsHookableEntry);
            }

            if (entries == null || !entries.Any() || !_saveHooks.Any() || (importantHooksOnly && !this.HasImportantSaveHooks()))
            {
                return(false);
            }

            var processedHooks = new HashSet <IDbSaveHook>();

            foreach (var entry in entries)
            {
                var e      = entry;            // Prevents access to modified closure
                var entity = e.Entity;
                if (HandledAlready(entity, e.InitialState, false))
                {
                    // Prevent repetitive hooking of the same entity/state/pre combination within a single request
                    continue;
                }
                var hooks = GetSaveHookInstancesFor(entity, importantHooksOnly);
                foreach (var hook in hooks)
                {
                    // call hook
                    try
                    {
                        //Logger.DebugFormat("PRE save hook: {0}, State: {1}, Entity: {2}", hook.GetType().Name, e.InitialState, e.Entity.GetUnproxiedType().Name);
                        hook.OnBeforeSave(e);
                        processedHooks.Add(hook);
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat(ex, "PreSaveHook exception ({0})", hook.GetType().FullName);
                    }

                    // change state if applicable
                    if (e.HasStateChanged)
                    {
                        e.InitialState  = e.State;
                        anyStateChanged = true;
                    }
                }
            }

            processedHooks.Each(x => x.OnBeforeSaveCompleted());

            return(anyStateChanged);
        }
Exemple #25
0
        void DisposeOfDisposables()
        {
            _disposables.Each(x =>
            {
                try
                {
                    x.Dispose();
                }
                catch
                {
                }
            });

            _disposables.Clear();
        }
Exemple #26
0
        //******
        private string getValidationMetaData()
        {
            StringBuilder valJason = new StringBuilder();

            valJason.Append("{");
            StringBuilder valMessages = new StringBuilder();

            valMessages.Append("messages:{");
            _validationHelpers.Each(x =>
            {
                valJason.Append(x.JSonValidation + ",");
                valMessages.Append(x.ErrorMessage + ",");
            });
            return((valJason.Length > 1) ? valJason.Append(valMessages.Remove(valMessages.Length - 1, 1) + "}} ").ToString() : string.Empty);
        }
Exemple #27
0
        public virtual void EnqueueEmailToBeSent(string fromAddress, HashSet <Recipient> recipients, string subject)
        {
            Guard.Hope(State.CanSend, "cannot enqeue email in the current state: " + State.Name);
            Guard.Hope(_emailRecipients.Count == 0, "recipients must be empty");
            State       = EmailState.ToBeSent;
            FromAddress = fromAddress;
            Subject     = subject;

            recipients.Each(r => _emailRecipients.Add(new EmailRecipient(this, r)));

            DomainEvents.RaiseEvent(new EmailEnqueuedToBeSentDomainEvent
            {
                EmailId = Id
            });
        }
Exemple #28
0
        public override void OnAfterSaveCompleted()
        {
            if (_toDelete.Count == 0)
            {
                return;
            }

            using (var scope = new DbContextScope(autoCommit: false))
            {
                _toDelete.Each(x => _aclService.Value.DeleteAclRecord(x));
                scope.Commit();
            }

            _toDelete.Clear();
        }
        public override void OnAfterSaveCompleted()
        {
            if (_toDelete.Count == 0)
            {
                return;
            }

            using (var scope = new DbContextScope(autoCommit: false))
            {
                _toDelete.Each(x => _productAttributeService.Value.DeleteProductBundleItemAttributeFilter(x));
                scope.Commit();
            }

            _toDelete.Clear();
        }
        protected internal CompilerResults Compile(string assemblyNameToCreate, string writeSourceTo)
        {
            HashSet <string> references = new HashSet <string>(DaoGenerator.DefaultReferenceAssemblies.ToArray());

            references.Add(typeof(JsonIgnoreAttribute).Assembly.GetFileInfo().FullName);
            _additonalReferenceAssemblies.Each(asm =>
            {
                references.Add(asm.GetFilePath());
            });
            SchemaDefinitionCreateResult.TypeSchema.Tables.Each(type => references.Add(type.Assembly.GetFileInfo().FullName));
            references.Add(typeof(DaoRepository).Assembly.GetFileInfo().FullName);
            CompilerResults results = _daoGenerator.Compile(new DirectoryInfo(writeSourceTo), assemblyNameToCreate, references.ToArray(), false);

            return(results);
        }
        public override void OnAfterSaveCompleted()
		{
			if (_toDelete.Count == 0)
				return;

			using (var scope = new DbContextScope(autoCommit: false))
			{
				using (_localizedEntityService.Value.BeginScope())
				{
					_toDelete.Each(x => _localizedEntityService.Value.DeleteLocalizedProperty(x));
				}

				scope.Commit();
				_toDelete.Clear();
			}
		}
        void DisposeOfDisposables()
        {
            _disposables.Each(x =>
            {
                try
                {
                    x.Dispose();
                }
                catch (Exception ex)
                {
                    _log.Error(l => l.Write(ex, "An exception occurred disposing of a connection object"));
                }
            });

            _disposables.Clear();
        }
Exemple #33
0
        private void TryDrop(Database db, params Type[] types)
        {
            HashSet <Type> unique = new HashSet <Type>();

            types.Each(type =>
            {
                TypeInheritanceDescriptor inheritance = new TypeInheritanceDescriptor(type);
                inheritance.Chain.Each(t =>
                {
                    unique.Add(t.Type);
                });
            });
            unique.Each(type =>
            {
                TryDrop(db, type.Name);
            });
        }
Exemple #34
0
        public SyntaxProvider()
        {
            _separators =
                new HashSet <char>(new[] { ' ', '.', ',', ';', '=', '+', '-', '<', '>', '(', ')', '\t', '\n', '\r' });
            var cSharpKeywords = new HashSet <string>(new[]
            {
                "var", "void", "string", "object", "dynamic",
                "const", "int", "long", "double", "float", "decimal", "bool", "string", "true", "false", "char",
                "public", "protected", "private", "virtual", "override", "static", "class",
                "switch", "case", "default", "new", "in", "let", "orderby", "descending", "using"
            });
            var operators = new HashSet <string>(new[] { "+", "-", "*", "/", "=", "!", "<", ">", "<>" });

            _words = new Dictionary <string, TagType>();
            cSharpKeywords.Each(c => _words[c] = TagType.CSharp);
            operators.Each(o => _words[o]      = TagType.Operator);
        }
Exemple #35
0
        public static GitReleaseNotes MiscSinceLatestRelease(string gitRepoPath)
        {
            string           version       = Git.LatestRelease(gitRepoPath);
            HashSet <GitLog> logsSinceLast = GitLog.SinceLatestRelease(gitRepoPath);

            GitReleaseNotes result = new GitReleaseNotes(version);

            logsSinceLast.Each(gl =>
            {
                if (!HasPossibleProjectPrefix(gl.Subject))
                {
                    result.AddBullet(gl.Subject, gl.AbbreviatedCommitHash);
                }
            });

            return(result);
        }
        public HelloWorldFubuRegistry()
        {
            IncludeDiagnostics(true);

            Applies
                .ToThisAssembly();

            var httpVerbs = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { "GET", "POST" };

            Actions
                .IncludeTypes(t => t.Namespace.StartsWith(typeof (EndpointMarker).Namespace) && t.Name.EndsWith("Endpoint"))
                .IncludeMethods(action => httpVerbs.Contains(action.Method.Name))
                .FindWith<FindActionsSource>();

            httpVerbs
                .Each(verb => Routes.ConstrainToHttpMethod(action => action.Method.Name.Equals(verb, StringComparison.InvariantCultureIgnoreCase), verb));

            Views
                .TryToAttach(findViews => findViews.by_ViewModel());

            ApplyConvention<CrudErrorWrapperConvention>();
            ApplyConvention<CrudValidationConvention>();

            Routes
                .UrlPolicy<EndpointUrlPolicy>();

            Models
                .BindModelsWith<ComplexJsonBinder>();

            Services(r => r.SetServiceIfNone<IJsonService>(new JsonService()));

            Output
                .ToJson
                .WhenCallMatches(c => c.OutputType().Name.StartsWith("Ajax"));

            this.HtmlConvention(new HelloWorldHtmlConventions(Validator.ValidationGraph));
        }
        private List<ITypeWriter> WriteMethods(StringBuilder sb)
        {
            List<ITypeWriter> extendedTypes = new List<ITypeWriter>();
            var methodSignatures = new HashSet<string>();
            foreach (var method in TypeDefinition.Methods)
            {
                var methodSb = new StringBuilder();

                var methodName = method.Name;

                // ignore special event handler methods
                if (method.HasParameters &&
                    method.Parameters[0].Name.StartsWith("__param0") &&
                    (methodName.StartsWith("add_") || methodName.StartsWith("remove_")))
                    continue;

                if (method.IsSpecialName && !method.IsConstructor)
                    continue;

                // already handled properties
                if (method.IsGetter || method.IsSetter)
                    continue;

                // translate the constructor function
                if (method.IsConstructor)
                {
                    methodName = "constructor";
                }

                // Lowercase first char of the method
                methodName = methodName.ToTypeScriptName();

                Indent(methodSb); Indent(methodSb);
                if (method.IsStatic)
                {
                    methodSb.Append("static ");
                }
                methodSb.Append(methodName);

                var outTypes = new List<ParameterDefinition>();

                methodSb.Append("(");
                method.Parameters.Where(w => w.IsOut).Each(e => outTypes.Add(e));
                method.Parameters.Where(w => !w.IsOut).For((parameter, i, isLast) =>
                {
                    methodSb.AppendFormat("{0}{1}: {2}{3}",
                        (i == 0 ? "" : " "),                            // spacer
                        parameter.Name,                                 // argument name
                        parameter.ParameterType.ToTypeScriptType(),     // type
                        (isLast ? "" : ","));                           // last one gets a comma
                });
                methodSb.Append(")");

                // constructors don't have return types.
                if (!method.IsConstructor)
                {
                    string returnType;
                    if (outTypes.Any())
                    {
                        var outWriter = new OutParameterReturnTypeWriter(Config, IndentCount, TypeDefinition, methodName, method.ReturnType, outTypes);
                        extendedTypes.Add(outWriter);
                        //TypeCollection.Add(TypeDefinition.Namespace, outWriter.TypeName, outWriter);
                        returnType = outWriter.TypeName;
                    }
                    else
                    {
                        returnType = method.ReturnType.ToTypeScriptType();
                    }

                    methodSb.AppendFormat(": {0}", returnType);
                }
                methodSb.AppendLine(";");

                var renderedMethod = methodSb.ToString();
                if (!methodSignatures.Contains(renderedMethod))
                    methodSignatures.Add(renderedMethod);
            }

            // HACK: This not a sustainable approach (but working for now)
            //       The IWebSocket inherits from IClosable and the websocket's close 
            //       conflicts with the closable close so we have to hack this method
            //       onto the websocket interface.
            if (TypeDefinition.FullName == "Windows.Networking.Sockets.IWebSocket")
            {
                methodSignatures.Add(IndentValue + IndentValue + "close(): void;" + Environment.NewLine);
            }

            methodSignatures.Each(method => sb.Append(method));

            return extendedTypes;
        }
        public string GetCode(MetadataTypes metadata)
        {
            var namespaces = new HashSet<string>();
            Config.DefaultNamespaces.Each(x => namespaces.Add(x));
            metadata.Types.Each(x => namespaces.Add(x.Namespace));
            metadata.Operations.Each(x => namespaces.Add(x.Request.Namespace));

            var sb = new StringBuilderWrapper(new StringBuilder());
            sb.AppendLine("/* Options:");
            sb.AppendLine("Version: {0}".Fmt(Version));
            sb.AppendLine("BaseUrl: {0}".Fmt(Config.BaseUrl));
            sb.AppendLine();
            sb.AppendLine("ServerVersion: {0}".Fmt(metadata.Version));
            sb.AppendLine("MakePartial: {0}".Fmt(Config.MakePartial));
            sb.AppendLine("MakeVirtual: {0}".Fmt(Config.MakeVirtual));
            sb.AppendLine("MakeDataContractsExtensible: {0}".Fmt(Config.MakeDataContractsExtensible));
            sb.AppendLine("AddReturnMarker: {0}".Fmt(Config.AddReturnMarker));
            sb.AppendLine("AddDescriptionAsComments: {0}".Fmt(Config.AddDescriptionAsComments));
            sb.AppendLine("AddDataContractAttributes: {0}".Fmt(Config.AddDataContractAttributes));
            sb.AppendLine("AddDataAnnotationAttributes: {0}".Fmt(Config.AddDataAnnotationAttributes));
            sb.AppendLine("AddIndexesToDataMembers: {0}".Fmt(Config.AddIndexesToDataMembers));
            sb.AppendLine("AddResponseStatus: {0}".Fmt(Config.AddResponseStatus));
            sb.AppendLine("AddImplicitVersion: {0}".Fmt(Config.AddImplicitVersion));
            sb.AppendLine("InitializeCollections: {0}".Fmt(Config.InitializeCollections));
            sb.AppendLine("AddDefaultXmlNamespace: {0}".Fmt(Config.AddDefaultXmlNamespace));
            //sb.AppendLine("DefaultNamespaces: {0}".Fmt(Config.DefaultNamespaces.ToArray().Join(", ")));
            sb.AppendLine("*/");
            sb.AppendLine();

            namespaces.Each(x => sb.AppendLine("using {0};".Fmt(x)));

            if (Config.AddDataContractAttributes
                && Config.AddDefaultXmlNamespace != null)
            {
                sb.AppendLine();

                namespaces.Where(x => !Config.DefaultNamespaces.Contains(x)).ToList()
                    .ForEach(x =>
                        sb.AppendLine("[assembly: ContractNamespace(\"{0}\", ClrNamespace=\"{1}\")]"
                            .Fmt(Config.AddDefaultXmlNamespace, x)));
            }

            sb.AppendLine();

            string lastNS = null;

            var existingOps = new HashSet<string>();

            var requestTypes = metadata.Operations.Select(x => x.Request).ToHashSet();
            var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request);
            var responseTypes = metadata.Operations
                .Where(x => x.Response != null)
                .Select(x => x.Response).ToHashSet();
            var types = metadata.Types.ToHashSet();

            var allTypes = new List<MetadataType>();
            allTypes.AddRange(requestTypes);
            allTypes.AddRange(responseTypes);
            allTypes.AddRange(types);
            var orderedTypes = allTypes
                .OrderBy(x => x.Namespace)
                .ThenBy(x => x.Name);

            foreach (var type in orderedTypes)
            {
                var fullTypeName = type.GetFullName();
                if (requestTypes.Contains(type))
                {
                    if (!existingOps.Contains(fullTypeName))
                    {
                        MetadataType response = null;
                        MetadataOperationType operation;
                        if (requestTypesMap.TryGetValue(type, out operation))
                        {
                            response = operation.Response;
                        }

                        lastNS = AppendType(ref sb, type, lastNS,
                            new CreateTypeOptions
                            {
                                ImplementsFn = () =>
                                {
                                    if (!Config.AddReturnMarker
                                        && !type.ReturnVoidMarker
                                        && type.ReturnMarkerTypeName == null)
                                        return null;

                                    if (type.ReturnVoidMarker)
                                        return "IReturnVoid";
                                    if (type.ReturnMarkerTypeName != null)
                                        return Type("IReturn`1", new[] { Type(type.ReturnMarkerTypeName) });
                                    return response != null
                                        ? Type("IReturn`1", new[] { Type(type.Name, type.GenericArgs) })
                                        : null;
                                },
                                IsRequest = true,
                            });

                        existingOps.Add(fullTypeName);
                    }
                }
                else if (responseTypes.Contains(type))
                {
                    if (!existingOps.Contains(fullTypeName)
                        && !Config.IgnoreTypesInNamespaces.Contains(type.Namespace))
                    {
                        lastNS = AppendType(ref sb, type, lastNS,
                            new CreateTypeOptions
                            {
                                IsResponse = true,
                            });

                        existingOps.Add(fullTypeName);
                    }
                }
                else if (types.Contains(type) && !existingOps.Contains(fullTypeName))
                {
                    lastNS = AppendType(ref sb, type, lastNS,
                        new CreateTypeOptions { IsType = true });
                }
            }

            if (lastNS != null)
                sb.AppendLine("}");
            sb.AppendLine();

            return sb.ToString();
        }
        public string GetCode(MetadataTypes metadata, IRequest request)
        {
            var namespaces = new HashSet<string>();
            Config.DefaultNamespaces.Each(x => namespaces.Add(x));
            metadata.Types.Each(x => namespaces.Add(x.Namespace));
            metadata.Operations.Each(x => namespaces.Add(x.Request.Namespace));

            Func<string, string> defaultValue = k =>
                request.QueryString[k].IsNullOrEmpty() ? "'''" : "'";

            var sb = new StringBuilderWrapper(new StringBuilder());
            sb.AppendLine("' Options:");
            sb.AppendLine("'Date: {0}".Fmt(DateTime.Now.ToString("s").Replace("T", " ")));
            sb.AppendLine("'Version: {0}".Fmt(metadata.Version));
            sb.AppendLine("'BaseUrl: {0}".Fmt(Config.BaseUrl));
            sb.AppendLine("'");
            sb.AppendLine("{0}MakePartial: {1}".Fmt(defaultValue("MakePartial"), Config.MakePartial));
            sb.AppendLine("{0}MakeVirtual: {1}".Fmt(defaultValue("MakeVirtual"), Config.MakeVirtual));
            sb.AppendLine("{0}MakeDataContractsExtensible: {1}".Fmt(defaultValue("MakeDataContractsExtensible"), Config.MakeDataContractsExtensible));
            sb.AppendLine("{0}AddReturnMarker: {1}".Fmt(defaultValue("AddReturnMarker"), Config.AddReturnMarker));
            sb.AppendLine("{0}AddDescriptionAsComments: {1}".Fmt(defaultValue("AddDescriptionAsComments"), Config.AddDescriptionAsComments));
            sb.AppendLine("{0}AddDataContractAttributes: {1}".Fmt(defaultValue("AddDataContractAttributes"), Config.AddDataContractAttributes));
            sb.AppendLine("{0}AddIndexesToDataMembers: {1}".Fmt(defaultValue("AddIndexesToDataMembers"), Config.AddIndexesToDataMembers));
            sb.AppendLine("{0}AddResponseStatus: {1}".Fmt(defaultValue("AddResponseStatus"), Config.AddResponseStatus));
            sb.AppendLine("{0}AddImplicitVersion: {1}".Fmt(defaultValue("AddImplicitVersion"), Config.AddImplicitVersion));
            sb.AppendLine("{0}InitializeCollections: {1}".Fmt(defaultValue("InitializeCollections"), Config.InitializeCollections));
            sb.AppendLine("{0}AddDefaultXmlNamespace: {1}".Fmt(defaultValue("AddDefaultXmlNamespace"), Config.AddDefaultXmlNamespace));
            //sb.AppendLine("{0}DefaultNamespaces: {1}".Fmt(defaultValue("DefaultNamespaces"), Config.DefaultNamespaces.ToArray().Join(", ")));
            sb.AppendLine();

            namespaces.Each(x => sb.AppendLine("Imports {0}".Fmt(x)));

            if (Config.AddDataContractAttributes
                && Config.AddDefaultXmlNamespace != null)
            {
                sb.AppendLine();

                namespaces.Where(x => !Config.DefaultNamespaces.Contains(x)).ToList()
                    .ForEach(x =>
                        sb.AppendLine("<Assembly: ContractNamespace(\"{0}\", ClrNamespace:=\"{1}\")>"
                            .Fmt(Config.AddDefaultXmlNamespace, x)));
            }

            sb.AppendLine();

            sb.AppendLine("Namespace Global");
            sb = sb.Indent();

            string lastNS = null;

            var existingOps = new HashSet<string>();

            var requestTypes = metadata.Operations.Select(x => x.Request).ToHashSet();
            var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request);
            var responseTypes = metadata.Operations
                .Where(x => x.Response != null)
                .Select(x => x.Response).ToHashSet();
            var types = metadata.Types.ToHashSet();

            var allTypes = new List<MetadataType>();
            allTypes.AddRange(requestTypes);
            allTypes.AddRange(responseTypes);
            allTypes.AddRange(types);
            var orderedTypes = allTypes
                .OrderBy(x => x.Namespace)
                .ThenBy(x => x.Name);

            foreach (var type in orderedTypes)
            {
                var fullTypeName = type.GetFullName();
                if (requestTypes.Contains(type))
                {
                    if (!existingOps.Contains(fullTypeName))
                    {
                        MetadataType response = null;
                        MetadataOperationType operation;
                        if (requestTypesMap.TryGetValue(type, out operation))
                        {
                            response = operation.Response;
                        }

                        lastNS = AppendType(ref sb, type, lastNS, allTypes,
                            new CreateTypeOptions
                            {
                                ImplementsFn = () =>
                                {
                                    if (!Config.AddReturnMarker
                                        && !type.ReturnVoidMarker
                                        && type.ReturnMarkerTypeName == null)
                                        return null;

                                    if (type.ReturnVoidMarker)
                                        return "IReturnVoid";
                                    if (type.ReturnMarkerTypeName != null)
                                        return Type("IReturn`1", new[] { Type(type.ReturnMarkerTypeName) });
                                    return response != null
                                                ? Type("IReturn`1", new[] { Type(type.Name, type.GenericArgs) })
                                                : null;
                                },
                                IsRequest = true,
                            });

                        existingOps.Add(fullTypeName);
                    }
                }
                else if (responseTypes.Contains(type))
                {
                    if (!existingOps.Contains(fullTypeName)
                        && !Config.IgnoreTypesInNamespaces.Contains(type.Namespace))
                    {
                        lastNS = AppendType(ref sb, type, lastNS, allTypes,
                            new CreateTypeOptions { IsResponse = true, });

                        existingOps.Add(fullTypeName);
                    }
                }
                else if (types.Contains(type) && !existingOps.Contains(fullTypeName))
                {
                    lastNS = AppendType(ref sb, type, lastNS, allTypes,
                        new CreateTypeOptions { IsType = true });
                }
            }

            if (lastNS != null)
                sb.AppendLine("End Namespace");

            sb = sb.UnIndent();
            sb.AppendLine("End Namespace");

            sb.AppendLine();

            return sb.ToString();
        }
 /// <summary>Validates the properties.</summary>
 /// <returns></returns>
 public bool ValidateProperties()
 {
     var propertyNames = new HashSet<string>();
     _validatableEntity
         .GetType()
         .GetRuntimeProperties().Where(x => x.GetCustomAttributes<ValidationAttribute>().Any())
         .ToArray()
         .Each(propertyInfo =>
         {
             var propertyErrors = new List<string>();
             TryValidateProperty(propertyInfo, propertyErrors);
             var errorsChanged = SetPropertyErrors(propertyInfo.Name, propertyErrors);
             if (errorsChanged)
                 propertyNames.Add(propertyInfo.Name);
         });
     propertyNames.Each(RaiseHandlers);
     return !_errors.Values.Any();
 }
Exemple #41
0
        public virtual void EnqueueEmailToBeSent(string fromAddress, HashSet<Recipient> recipients, string subject)
        {
            Guard.Hope(State.CanSend, "cannot enqeue email in the current state: " + State.Name);
            Guard.Hope(_emailRecipients.Count == 0, "recipients must be empty");
            State = EmailState.ToBeSent;
            FromAddress = fromAddress;
            Subject = subject;

            recipients.Each(r => _emailRecipients.Add(new EmailRecipient(this, r)));

            DomainEvents.RaiseEvent(new EmailEnqueuedToBeSentEvent
                                        {
                                            EmailId = Id
                                        });
        }
Exemple #42
0
        public string GetCode(MetadataTypes metadata)
        {
            var namespaces = new HashSet<string>();
            Config.DefaultNamespaces.Each(x => namespaces.Add(x));
            metadata.Types.Each(x => namespaces.Add(x.Namespace));
            metadata.Operations.Each(x => namespaces.Add(x.Request.Namespace));

            var sb = new StringBuilderWrapper(new StringBuilder());
            sb.AppendLine("/* Options:");
            sb.AppendLine("Version: {0}".Fmt(Version));
            sb.AppendLine("BaseUrl: {0}".Fmt(Config.BaseUrl));
            sb.AppendLine();
            sb.AppendLine("ServerVersion: {0}".Fmt(metadata.Version));
            sb.AppendLine("MakePartial: {0}".Fmt(Config.MakePartial));
            sb.AppendLine("MakeVirtual: {0}".Fmt(Config.MakeVirtual));
            sb.AppendLine("MakeDataContractsExtensible: {0}".Fmt(Config.MakeDataContractsExtensible));
            sb.AppendLine("AddReturnMarker: {0}".Fmt(Config.AddReturnMarker));
            sb.AppendLine("AddDescriptionAsComments: {0}".Fmt(Config.AddDescriptionAsComments));
            sb.AppendLine("AddDataContractAttributes: {0}".Fmt(Config.AddDataContractAttributes));
            sb.AppendLine("AddDataAnnotationAttributes: {0}".Fmt(Config.AddDataAnnotationAttributes));
            sb.AppendLine("AddDefaultXmlNamespace: {0}".Fmt(Config.AddDefaultXmlNamespace));
            sb.AppendLine("AddIndexesToDataMembers: {0}".Fmt(Config.AddIndexesToDataMembers));
            sb.AppendLine("AddResponseStatus: {0}".Fmt(Config.AddResponseStatus));
            sb.AppendLine("AddImplicitVersion: {0}".Fmt(Config.AddImplicitVersion));
            sb.AppendLine("InitializeCollections: {0}".Fmt(Config.InitializeCollections));
            sb.AppendLine("DefaultNamespaces: {0}".Fmt(Config.DefaultNamespaces.ToArray().Join(", ")));
            sb.AppendLine("*/");
            sb.AppendLine();

            namespaces.Each(x => sb.AppendLine("using {0};".Fmt(x)));

            if (Config.AddDataContractAttributes
                && Config.AddDefaultXmlNamespace != null)
            {
                sb.AppendLine();

                namespaces.Where(x => !Config.DefaultNamespaces.Contains(x)).ToList()
                    .ForEach(x =>
                        sb.AppendLine("[assembly: ContractNamespace(\"{0}\", ClrNamespace=\"{1}\")]"
                            .Fmt(Config.AddDefaultXmlNamespace, x)));
            }

            sb.AppendLine();

            string lastNS = null;

            sb.AppendLine("#region Operations");
            sb.AppendLine();
            foreach (var operation in metadata.Operations
                .OrderBy(x => x.Request.Namespace)
                .OrderBy(x => x.Request.Name))
            {
                var request = operation.Request;
                var response = operation.Response;
                lastNS = AppendType(ref sb, request, lastNS,
                    new CreateTypeOptions {
                        ImplementsFn = () => {
                            if (!Config.AddReturnMarker
                                && !request.ReturnVoidMarker
                                && request.ReturnMarkerTypeName == null)
                                return null;

                            if (request.ReturnVoidMarker)
                                return "IReturnVoid";
                            if (request.ReturnMarkerTypeName != null)
                                return Type("IReturn`1", new[] { Type(request.ReturnMarkerTypeName) });
                            return response != null
                                ? Type("IReturn`1", new[] { Type(response.Name, response.GenericArgs) })
                                : null;
                        },
                        IsRequest = true,
                    });
                lastNS = AppendType(ref sb, operation.Response, lastNS,
                    new CreateTypeOptions {
                        IsResponse = true,
                    });
            }
            if (lastNS != null)
                sb.AppendLine("}");
            sb.AppendLine();
            sb.AppendLine("#endregion");

            sb.AppendLine();
            sb.AppendLine();

            lastNS = null;
            sb.AppendLine("#region Types");
            sb.AppendLine();
            foreach (var type in metadata.Types
                .OrderBy(x => x.Namespace)
                .ThenBy(x => x.Name))
            {
                lastNS = AppendType(ref sb, type, lastNS,
                    new CreateTypeOptions { IsType = true });
            }
            if (lastNS != null)
                sb.AppendLine("}");
            sb.AppendLine();
            sb.AppendLine("#endregion");

            return sb.ToString();
        }
        private List<ITypeWriter> WriteMethods(StringBuilder sb)
        {
            List<ITypeWriter> extendedTypes = new List<ITypeWriter>();
            var methodSignatures = new HashSet<string>();
            foreach (var method in TypeDefinition.Methods)
            {
                var methodSb = new StringBuilder();

                var methodName = method.Name;

                // ignore special event handler methods
                if (method.HasParameters &&
                    method.Parameters[0].Name.StartsWith("__param0") &&
                    (methodName.StartsWith("add_") || methodName.StartsWith("remove_")))
                    continue;

                // already handled properties
                if (method.IsGetter || method.IsSetter)
                    continue;

                // translate the constructor function
                if (method.IsConstructor)
                {
                    continue;
                }

                // Lowercase first char of the method
                methodName = methodName.ToTypeScriptName();

                Indent(methodSb); Indent(methodSb);
                if (method.IsStatic)
                {
                    methodSb.Append("static ");
                }
                methodSb.Append(methodName);

                var outTypes = new List<ParameterDefinition>();

                methodSb.Append("(");
                method.Parameters.Where(w => w.IsOut).Each(e => outTypes.Add(e));
                method.Parameters.Where(w => !w.IsOut).For((parameter, i, isLast) =>
                {
                    methodSb.AppendFormat("{0}{1}: {2}{3}",
                        (i == 0 ? "" : " "),                            // spacer
                        parameter.Name,                                 // argument name
                        parameter.ParameterType.ToTypeScriptType(),     // type
                        (isLast ? "" : ","));                           // last one gets a comma
                });
                methodSb.Append(")");

                // constructors don't have return types.
                if (!method.IsConstructor)
                {
                    string returnType;
                    if (outTypes.Any())
                    {
                        var outWriter = new OutParameterReturnTypeWriter(Config, IndentCount, TypeDefinition, methodName, method.ReturnType, outTypes);
                        extendedTypes.Add(outWriter);
                        returnType = outWriter.TypeName;
                    }
                    else
                    {
                        returnType = method.ReturnType.ToTypeScriptType();
                    }

                    methodSb.AppendFormat(": {0}", returnType);
                }
                methodSb.AppendLine(";");

                var renderedMethod = methodSb.ToString();
                if (!methodSignatures.Contains(renderedMethod))
                    methodSignatures.Add(renderedMethod);
            }

            methodSignatures.Each(method => sb.Append(method));

            return extendedTypes;
        }