Example #1
0
        public int Run(ProcessUtility exe, string path, string project, XDictionary<string, string> macros)
        {
            // Reset my working directory.
            Environment.CurrentDirectory = path;

            string tmpFile = Path.GetTempFileName();
            File.Move(tmpFile, tmpFile+".bat");
            tmpFile += ".bat";
            FileStream file = new FileStream(tmpFile,FileMode.Open);
            StreamWriter FS = new StreamWriter(file);
            macros.Default = null;

            foreach (string command in Commands)
            {
                FS.WriteLine(command.FormatWithMacros((input) =>
                {
                    string Default = null;
                    if (input.Contains("??"))
                    {
                        var parts = input.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries);
                        Default = parts.Length > 1 ? parts[1].Trim() : string.Empty;
                        input = parts[0];
                    }
                    return (macros[input.ToLower()] ?? Default) ?? input;
                }
                ));
            }

            FS.Close();
            return exe.Exec(@"/c """ + tmpFile + @"""");
        }
Example #2
0
        public string Flatten(XDictionary <string, string> macros = null)
        {
            StringBuilder Out = new StringBuilder();

            if (macros == null)
            {
                foreach (string s in Commands)
                {
                    Out.AppendLine(s);
                }
            }
            else
            {
                foreach (string s in Commands)
                {
                    Out.AppendLine(s.FormatWithMacros((input) =>
                    {
                        string Default = null;
                        if (input.Contains("??"))
                        {
                            var parts = input.Split(new[] { '?' },
                                                    StringSplitOptions.
                                                    RemoveEmptyEntries);
                            Default = parts.Length > 1
                                                                                ? parts[1].Trim()
                                                                                : string.Empty;
                            input = parts[0];
                        }
                        return((macros[input.ToLower()] ?? Default) ?? String.Empty);
                    }));
                }
            }

            return(Out.ToString());
        }
Example #3
0
        public string Flatten(XDictionary<string, string> macros = null)
        {
            StringBuilder Out = new StringBuilder();
            if (macros == null)
                foreach (string s in Commands)
                    Out.AppendLine(s);
            else
                foreach (string s in Commands)
                    Out.AppendLine(s.FormatWithMacros((input) =>
                                                          {
                                                              string Default = null;
                                                              if (input.Contains("??"))
                                                              {
                                                                  var parts = input.Split(new[] {'?'},
                                                                                          StringSplitOptions.
                                                                                              RemoveEmptyEntries);
                                                                  Default = parts.Length > 1
                                                                                ? parts[1].Trim()
                                                                                : string.Empty;
                                                                  input = parts[0];
                                                              }
                                                              return (macros[input.ToLower()] ?? Default) ?? String.Empty;
                                                          }));

            return Out.ToString();
        }
Example #4
0
        /// <exception cref="ParseException">Token '{0}' not expected in object declaration</exception>
        private XDictionary <string, IValue> ParseMetadataObject(ObjectNode context, XDictionary <string, IValue> result = null)
        {
            if (TokenType.CloseBrace == NextAfter(WhiteSpaceCommentsOrSemicolons))
            {
                return(result);
            }

            Rewind();

            var selector = ParseSelector(ColonOrEqual);

            // should be at the terminator still!
            switch (Type)
            {
            case TokenType.Equal:
                result = result ?? new XDictionary <string, IValue>();
                result.Add(selector.Name, ParseRValue(context, SemicolonCommaOrCloseBrace, null));
                return(ParseMetadataObject(context, result));

            case TokenType.Colon:
                result = result ?? new XDictionary <string, IValue>();
                result.Add(selector.Name, ParseRValue(context, SemicolonCommaOrCloseBrace, null));
                return(ParseMetadataObject(context, result));
            }
            throw Fail(ErrorCode.TokenNotExpected, "Token '{0}' not expected in metadata kvpair declaration");
        }
Example #5
0
        public int Run(ProcessUtility exe, string path, string project, XDictionary <string, string> macros)
        {
            // Reset my working directory.
            Environment.CurrentDirectory = path;

            string tmpFile = Path.GetTempFileName();

            File.Move(tmpFile, tmpFile + ".bat");
            tmpFile += ".bat";
            FileStream   file = new FileStream(tmpFile, FileMode.Open);
            StreamWriter FS   = new StreamWriter(file);

            macros.Default = null;

            foreach (string command in Commands)
            {
                FS.WriteLine(command.FormatWithMacros((input) =>
                {
                    string Default = null;
                    if (input.Contains("??"))
                    {
                        var parts = input.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries);
                        Default   = parts.Length > 1 ? parts[1].Trim() : string.Empty;
                        input     = parts[0];
                    }
                    return((macros[input.ToLower()] ?? Default) ?? input);
                }
                                                      ));
            }

            FS.Close();
            return(exe.Exec(@"/c """ + tmpFile + @""""));
        }
Example #6
0
 public IncomingCallDispatcher(T target)
 {
     _targetObject  = target;
     _methodTargets = target.GetType().GetMethods().ToXDictionary(method => method.Name, method => new DispatchableMethod {
         MethodInfo = method,
         Parameters = method.GetParameters().ToXDictionary(each => each.Name, each => each.ParameterType.GetPersistableInfo())
     });
 }
Example #7
0
        public OutgoingCallDispatcher(Type targetInterface, WriteAsyncMethod writeAsync)
        {
            _writeAsync = writeAsync;

            _methodTargets = targetInterface.GetMethods().ToXDictionary(method => method.Name, method => new DispatchableMethod {
                MethodInfo = method,
                Parameters = method.GetParameters().ToXDictionary(each => each.Name, each => each.ParameterType.GetPersistableInfo())
            });
        }
        public static IDictionary<string, string> GetSubjectNameParts(this X509Certificate2 cert) {
            var result = new XDictionary<string, string>();

            foreach (var bits in cert.SubjectName.Name.SplitToList(',').Select(each => each.Split('='))) {
                var newKey = bits[0].Trim(' ');
                result.Add(result.ContainsKey(newKey) ? newKey + result.Keys.Where(key => key.StartsWith(newKey)).Count() : newKey, bits[1]);
            }

            return result;
        }
Example #9
0
        private void InitializeNuget()
        {
            View nugetView = _sheet.View.nuget;

            _nuget = nugetView;

            if (!nugetView.HasChildren)
            {
                FailAlways(Event <SourceError> .Raise("AP100", _sheet.CurrentView.SourceLocations, "script does not contain a declaration for a NuGet package"));
            }

            _nuspec = _nuget.nuspec;

            if (!_nuspec.HasChildren)
            {
                FailAlways(Event <SourceError> .Raise("AP102", nugetView.SourceLocations, "script does not contain a 'nuspec' declaration in 'nuget'"));
            }


            if (string.IsNullOrEmpty(_nuspec.id.Value))
            {
                FailAlways(Event <SourceError> .Raise("AP103", _nuspec.SourceLocations, "script does not contain a 'id' declaration in 'nuspec'"));
            }

            NugetPackage = new NugetPackage(this, PackageRole.@default, _nuspec.id.Value);
            nugetView.AddChildRoutes(NugetPackage.Initialize());

            // do the property sheet mapping
            var conditions = new XDictionary <string, string>();

            // map the file routes
            nugetView.AddChildRoute("files".MapTo(new object(), new [] {
                "condition".MapTo(conditions, key => Pivots.GetExpressionFilepath(_nuspec.id, nugetView.ResolveMacrosInContext(key))),
                "*".MapTo(conditions, key => Pivots.GetExpressionFilepath(_nuspec.id, nugetView.ResolveMacrosInContext(key)))
            }));

            var nuspecid = _nuspec.id;

            var conditionFolderMacroHander = (GetMacroValueDelegate)((macro, context) => {
                if (macro == "conditionFolder")
                {
                    return(LinqExtensions.SingleItemAsEnumerable(Pivots.GetExpressionFilepath(nuspecid, ((View)context).GetSingleMacroValue("ElementId") ?? "")));
                }
                return(null);
            });

            _nuget.props.AddMacroHandler(conditionFolderMacroHander);
            _nuget.targets.AddMacroHandler(conditionFolderMacroHander);

            nugetView.AddChildRoute("props".MapTo(NugetPackage.Props.Value /*, GetPropsProject("default").ProjectRoutes() */));

            // always need a targets
            nugetView.AddChildRoute("targets".MapTo(NugetPackage.Targets.Value /*, GetTargetsProject("default").ProjectRoutes() */));
            // other variants/frameworks
        }
Example #10
0
 internal ProcessStartInfo(System.Diagnostics.ProcessStartInfo psi)
 {
     _processStartInfo = psi;
     _environmentVariables = new XDictionary<string, string>();
     foreach (var i in psi.EnvironmentVariables.Keys) {
         _environmentVariables.Add(i.ToString(), psi.EnvironmentVariables[(string)i]);
     }
     _processStartInfo.RedirectStandardError = true;
     _processStartInfo.RedirectStandardOutput = true;
     SyncEnvironment();
 }
Example #11
0
 private static void InnerRead(RegistryKey key, XDictionary <string, XDictionary <string, ValueObject> > data)
 {
     foreach (var name in key.GetValueNames())
     {
         data[key.Name][name] = new ValueObject(key.GetValueType(name), key.GetValue(name));
     }
     foreach (var sub in key.GetSubKeyNames())
     {
         InnerRead(key.OpenSubKey(sub), data);
     }
 }
Example #12
0
        public static IDictionary <string, string> GetSubjectNameParts(this X509Certificate2 cert)
        {
            var result = new XDictionary <string, string>();

            foreach (var bits in cert.SubjectName.Name.SplitToList(',').Select(each => each.Split('=')))
            {
                var newKey = bits[0].Trim(' ');
                result.Add(result.ContainsKey(newKey) ? newKey + result.Keys.Where(key => key.StartsWith(newKey)).Count() : newKey, bits[1]);
            }

            return(result);
        }
Example #13
0
 public VersionControl(string name, Tool tool = null, IDictionary <string, string> properties = null)
 {
     if (name == null)
     {
         throw new ArgumentNullException("name", "VersionControl.Name cannot be null.");
     }
     Name       = name;
     Tool       = tool;
     Properties = properties == null
                       ? new XDictionary <string, string>()
                       : new XDictionary <string, string>(properties);
 }
Example #14
0
 internal ProcessStartInfo(System.Diagnostics.ProcessStartInfo psi)
 {
     _processStartInfo     = psi;
     _environmentVariables = new XDictionary <string, string>();
     foreach (var i in psi.EnvironmentVariables.Keys)
     {
         _environmentVariables.Add(i.ToString(), psi.EnvironmentVariables[(string)i]);
     }
     _processStartInfo.RedirectStandardError  = true;
     _processStartInfo.RedirectStandardOutput = true;
     SyncEnvironment();
 }
Example #15
0
        public static IDictionary <string, string> GetPublisherInformation(string filename)
        {
            var result = new XDictionary <string, string>();

            try {
                var cert   = new X509Certificate2(filename);
                var fields = cert.Subject.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                // var result = fields.Select(f => f.Split('=')).Where(s => s.Length > 1).ToDictionary(s => s[0], s => s[1]);

                result.Add("PublisherName", fields[0].Split('=')[1]);
            } catch (Exception) {
            }

            return(result);
        }
Example #16
0
        public static IDictionary<string, string> GetPublisherInformation(string filename) {
            var result = new XDictionary<string, string>();
            try {
                var cert = new X509Certificate2(filename);
                var fields = cert.Subject.Split(new[] {
                    ','
                }, StringSplitOptions.RemoveEmptyEntries);
                // var result = fields.Select(f => f.Split('=')).Where(s => s.Length > 1).ToDictionary(s => s[0], s => s[1]);

                result.Add("PublisherName", fields[0].Split('=')[1]);
            } catch (Exception) {
            }

            return result;
        }
Example #17
0
        public void Test2()
        {
            const string src = @"<?xml version=""1.0""?>
<dictionary>
  <item key=""test"" value=""ok"" />
  <item key=""run"" value=""fine"" />
</dictionary>";

            XDictionary <string, string> dictionary = XmlSerializer <XDictionary <string, string> > .Xml.Deserialize(src);

            Assert.IsNotNull(dictionary);
            Assert.AreEqual(2, dictionary.Count);
            Assert.AreEqual("ok", dictionary["test"]);
            Assert.AreEqual("fine", dictionary["run"]);
        }
Example #18
0
        public void Test1()
        {
            var dictionary = new XDictionary <string, string> {
                { "test", "ok" }, { "run", "fine" }
            };
            string act = XmlSerializer <XDictionary <string, string> > .Xml.Serialize(dictionary);

            const string exp = @"<?xml version=""1.0""?>
<dictionary>
  <item key=""test"" value=""ok"" />
  <item key=""run"" value=""fine"" />
</dictionary>";

            Assert.AreEqual(exp, act);
        }
Example #19
0
        private void ProcessMessage(byte[] serverInput, int numBytes)
        {
            try {
                var rawMessage     = Encoding.UTF8.GetString(serverInput, 0, numBytes);
                var requestMessage = new UrlEncodedMessage(rawMessage);

                if (string.IsNullOrEmpty(requestMessage))
                {
                    return;
                }

                if (IsCanceled)
                {
                    Event <GetResponseInterface> .RaiseFirst().OperationCanceled("Service is shutting down");
                }
                else
                {
                    Logger.Message("REQ[{2}]:#{0}:{1}".format(requestMessage["rqid"], requestMessage.ToString(), _clientId));
                    // Logger.Message("Request:[{0}]{1}".format(requestMessage["rqid"], requestMessage.ToString()));


                    var packageRequestData = new XDictionary <string, PackageRequestData>();
                    var rqid = requestMessage["rqid"];

                    CurrentTask.Events += new GetCurrentRequestId(() => rqid);
                    CurrentTask.Events += new GetResponseInterface(() => _dispatcher);
                    CurrentTask.Events += new GetRequestPackageDataCache(() => packageRequestData);

                    var dispatchTask = PackageManagerImpl.Dispatcher.Dispatch(requestMessage);
                    dispatchTask.ContinueOnFail(failure => {
                        if (!IsCanceled)
                        {
                            Logger.Error(failure);
                            Event <GetResponseInterface> .RaiseFirst().UnexpectedFailure(failure.GetType().Name, failure.Message, failure.StackTrace);
                        }
                    });

                    dispatchTask.ContinueAlways(dt => Event <GetResponseInterface> .RaiseFirst().TaskComplete());
                }
            } catch (Exception e) {
                Logger.Error(e);
                throw e;
            }
            finally {
                // whatever, after this point let the messages flow!
                _bufferReady.Set();
            }
        }
Example #20
0
        public void Test1()
        {
            var dictionary = new XDictionary<string, string> {{"test", "ok"}, {"run", "fine"}};
            string act = XmlSerializer<XDictionary<string, string>>.Xml.Serialize(dictionary);

            var root = XElement.Parse (act);
            Assert.AreEqual ("dictionary", root.Name.LocalName);
            int n = 0;
            var values = new string[] {"test", "ok", "run", "fine"};
            foreach (var item in root.Elements("item")) {
                Assert.AreEqual (values[n], item.Attribute ("key").Value);
                Assert.AreEqual (values[n+1], item.Attribute ("value").Value);
                n += 2;
            }
            Assert.AreEqual (4, n);
        }
Example #21
0
        public static void AddChildren(this XDictionary <string, string> propertyDictionary, IEnumerable <XElement> children)
        {
            foreach (var child in children)
            {
                var val = child.Value;
                var key = child.LocalName();

                if (propertyDictionary.ContainsKey(key))
                {
                    var cur = propertyDictionary[key];
                    val = val.Replace("%({0})".format(key), cur);
                }
                val = Event <CustomReplacement> .Raise(val);

                propertyDictionary.Add(key, val);
            }
        }
Example #22
0
 public AutoBuild()
 {
     Daemons         = new List <Daemon>();
     Waiting         = new XDictionary <string, Timer>();
     RunQueue        = new Queue <string>();
     Running         = new List <string>();
     Projects        = new XDictionary <string, ProjectData>();
     MasterConfig    = new AutoBuild_config();
     ServiceName     = "AutoBuild";
     EventLog.Log    = "Application";
     EventLog.Source = ServiceName;
     // Events to enable
     CanHandlePowerEvent         = false;
     CanHandleSessionChangeEvent = false;
     CanPauseAndContinue         = false;
     CanShutdown = true;
     CanStop     = true;
 }
Example #23
0
 public AutoBuild()
 {
     Daemons = new List<Daemon>();
     Waiting = new XDictionary<string, Timer>();
     RunQueue = new Queue<string>();
     Running = new List<string>();
     Projects = new XDictionary<string, ProjectData>();
     MasterConfig = new AutoBuild_config();
     ServiceName = "AutoBuild";
     EventLog.Log = "Application";
     EventLog.Source = ServiceName;
     // Events to enable
     CanHandlePowerEvent = false;
     CanHandleSessionChangeEvent = false;
     CanPauseAndContinue = false;
     CanShutdown = true;
     CanStop = true;
 }
Example #24
0
        //A copy constructor, because I'm always annoyed when I can't find one.
        public AutoBuild_config(AutoBuild_config source)
        {
            _DefaultCleanRepo  = source.DefaultCleanRepo;
            _UseGithubListener = source.UseGithubListener;
            _ProjectRoot       = source.ProjectRoot;
            _OutputStore       = source.OutputStore;
            _PreTriggerWait    = source.PreTriggerWait;

            _MaxJobs           = source.MaxJobs;
            VersionControlList = new XDictionary <string, VersionControl>(source.VersionControlList);
            DefaultCommands    = new XDictionary <string, List <string> >(source.DefaultCommands);
            Commands           = new XDictionary <string, CommandScript>(source.Commands);
            DefaultRefs        = new ObservableCollection <string>(source.DefaultRefs);

            VersionControlList.Changed    += VCSChanged;
            DefaultCommands.Changed       += DefaultCommandsChanged;
            Commands.Changed              += CommandsChanged;
            DefaultRefs.CollectionChanged += CollectionChanged;
        }
Example #25
0
        //Default constructor.  Always good to have one of these.
        public AutoBuild_config()
        {
            _DefaultCleanRepo = true;
            _UseGithubListener = true;
            _ProjectRoot = DEFAULTROOT;
            _OutputStore = DEFAULTOUTPUT;
            _PreTriggerWait = 60 * 1000;

            _MaxJobs = 4;
            VersionControlList = new XDictionary<string, VersionControl>();
            DefaultCommands = new XDictionary<string, List<string>>();
            Commands = new XDictionary<string, CommandScript>();
            DefaultRefs = new ObservableCollection<string>();

            VersionControlList.Changed += VCSChanged;
            DefaultCommands.Changed += DefaultCommandsChanged;
            Commands.Changed += CommandsChanged;
            DefaultRefs.CollectionChanged += CollectionChanged;
        }
Example #26
0
        //A copy constructor, because I'm always annoyed when I can't find one.
        public AutoBuild_config(AutoBuild_config source)
        {
            _DefaultCleanRepo = source.DefaultCleanRepo;
            _UseGithubListener = source.UseGithubListener;
            _ProjectRoot = source.ProjectRoot;
            _OutputStore = source.OutputStore;
            _PreTriggerWait = source.PreTriggerWait;

            _MaxJobs = source.MaxJobs;
            VersionControlList = new XDictionary<string, VersionControl>(source.VersionControlList);
            DefaultCommands = new XDictionary<string, List<string>>(source.DefaultCommands);
            Commands = new XDictionary<string, CommandScript>(source.Commands);
            DefaultRefs = new ObservableCollection<string>(source.DefaultRefs);

            VersionControlList.Changed += VCSChanged;
            DefaultCommands.Changed += DefaultCommandsChanged;
            Commands.Changed += CommandsChanged;
            DefaultRefs.CollectionChanged += CollectionChanged;
        }
Example #27
0
 /// <summary>
 /// Finds the first key which contains a value with the provided object.
 /// </summary>
 /// <typeparam name="TKey"></typeparam>
 /// <typeparam name="TValue"></typeparam>
 /// <param name="dict">the dictionary to look through</param>
 /// <param name="searchValue">object to look for in the dictionary</param>
 /// <returns>The first key found which contains the searchValue in its value.  Returns null if no match is found.</returns>
 public static object FindKey <TKey, TValue>(this XDictionary <TKey, TValue> dict, object searchValue)
 {
     foreach (KeyValuePair <TKey, TValue> pair in dict)
     {
         dynamic val = pair.Value;
         if (val is IEnumerable <TValue> )
         {
             if (val.Contains(searchValue))
             {
                 return(pair.Key);
             }
         }
         if (val.Equals(searchValue))
         {
             return(pair.Key);
         }
     }
     return(null);
 }
Example #28
0
        //Default constructor.  Always good to have one of these.
        public AutoBuild_config()
        {
            _DefaultCleanRepo  = true;
            _UseGithubListener = true;
            _ProjectRoot       = DEFAULTROOT;
            _OutputStore       = DEFAULTOUTPUT;
            _PreTriggerWait    = 60 * 1000;

            _MaxJobs           = 4;
            VersionControlList = new XDictionary <string, VersionControl>();
            DefaultCommands    = new XDictionary <string, List <string> >();
            Commands           = new XDictionary <string, CommandScript>();
            DefaultRefs        = new ObservableCollection <string>();

            VersionControlList.Changed    += VCSChanged;
            DefaultCommands.Changed       += DefaultCommandsChanged;
            Commands.Changed              += CommandsChanged;
            DefaultRefs.CollectionChanged += CollectionChanged;
        }
Example #29
0
 //Default constructor.  Always good to have one of these.
 public ProjectData()
 {
     Enabled       = false;
     KeepCleanRepo = true;
     RepoURL       = String.Empty;
     WatchRefs     = new ObservableCollection <string>();
     WatchRefs.CollectionChanged += CollectionChanged;
     BuildCheckouts          = new XDictionary <string, CheckoutInfo>();
     BuildCheckouts.Changed += CheckoutsChanged;
     Commands          = new XDictionary <string, CommandScript>();
     Commands.Changed += CommandsChanged;
     BuildTriggers     = new ObservableCollection <BuildTrigger>();
     BuildTriggers.CollectionChanged += CollectionChanged;
     Build = new ObservableCollection <string>();
     Build.CollectionChanged += CollectionChanged;
     PreBuild = new ObservableCollection <string>();
     PreBuild.CollectionChanged += CollectionChanged;
     PostBuild = new ObservableCollection <string>();
     PostBuild.CollectionChanged += CollectionChanged;
     LoadHistory(String.Empty);
 }
Example #30
0
 //A copy constructor, because I'm always annoyed when I can't find one.
 public ProjectData(ProjectData source)
 {
     Enabled        = source.Enabled;
     KeepCleanRepo  = source.KeepCleanRepo;
     RepoURL        = source.RepoURL;
     WatchRefs      = new ObservableCollection <string>(source.WatchRefs);
     BuildCheckouts = new XDictionary <string, CheckoutInfo>(source.BuildCheckouts);
     Commands       = new XDictionary <string, CommandScript>(source.Commands);
     BuildTriggers  = new ObservableCollection <BuildTrigger>(source.BuildTriggers);
     Build          = new ObservableCollection <string>(source.Build);
     PreBuild       = new ObservableCollection <string>(source.PreBuild);
     PostBuild      = new ObservableCollection <string>(source.PostBuild);
     WatchRefs.CollectionChanged     += CollectionChanged;
     BuildCheckouts.Changed          += CheckoutsChanged;
     Commands.Changed                += CommandsChanged;
     BuildTriggers.CollectionChanged += CollectionChanged;
     Build.CollectionChanged         += CollectionChanged;
     PreBuild.CollectionChanged      += CollectionChanged;
     PostBuild.CollectionChanged     += CollectionChanged;
     LoadHistory(String.Empty);
 }
Example #31
0
 //Default constructor.  Always good to have one of these.
 public ProjectData()
 {
     Enabled = false;
     KeepCleanRepo = true;
     RepoURL = String.Empty;
     WatchRefs = new ObservableCollection<string>();
     WatchRefs.CollectionChanged += CollectionChanged;
     BuildCheckouts = new XDictionary<string, CheckoutInfo>();
     BuildCheckouts.Changed += CheckoutsChanged;
     Commands = new XDictionary<string, CommandScript>();
     Commands.Changed += CommandsChanged;
     BuildTriggers = new ObservableCollection<BuildTrigger>();
     BuildTriggers.CollectionChanged += CollectionChanged;
     Build = new ObservableCollection<string>();
     Build.CollectionChanged += CollectionChanged;
     PreBuild = new ObservableCollection<string>();
     PreBuild.CollectionChanged += CollectionChanged;
     PostBuild = new ObservableCollection<string>();
     PostBuild.CollectionChanged += CollectionChanged;
     LoadHistory(String.Empty);
 }
Example #32
0
        private static int BuildActions(string projectName, BuildStatus status = null, string checkoutRef = null)
        {
            if (projectName == null)
            {
                throw new ArgumentException("ProjectName cannot be null.");
            }
            if (!Projects.ContainsKey(projectName))
            {
                throw new ArgumentException("Project not found: " + projectName);
            }

            WriteVerbose("Start Build: " + projectName);
            if (checkoutRef != null)
            {
                XDictionary <string, string> macros = new XDictionary <string, string>();
                macros["checkout"] = checkoutRef;
                return(doActions(projectName, Projects[projectName].BuildCheckouts[checkoutRef].BuildCmd, status, macros));
            }
            // else
            return(doActions(projectName, Projects[projectName].Build, status));
        }
Example #33
0
        public void Test1()
        {
            var dictionary = new XDictionary <string, string> {
                { "test", "ok" }, { "run", "fine" }
            };
            string act = XmlSerializer <XDictionary <string, string> > .Xml.Serialize(dictionary);

            var root = XElement.Parse(act);

            Assert.AreEqual("dictionary", root.Name.LocalName);
            int n      = 0;
            var values = new string[] { "test", "ok", "run", "fine" };

            foreach (var item in root.Elements("item"))
            {
                Assert.AreEqual(values[n], item.Attribute("key").Value);
                Assert.AreEqual(values[n + 1], item.Attribute("value").Value);
                n += 2;
            }
            Assert.AreEqual(4, n);
        }
Example #34
0
 //A copy constructor, because I'm always annoyed when I can't find one.
 public ProjectData(ProjectData source)
 {
     Enabled = source.Enabled;
     KeepCleanRepo = source.KeepCleanRepo;
     RepoURL = source.RepoURL;
     WatchRefs = new ObservableCollection<string>(source.WatchRefs);
     BuildCheckouts = new XDictionary<string, CheckoutInfo>(source.BuildCheckouts);
     Commands = new XDictionary<string, CommandScript>(source.Commands);
     BuildTriggers = new ObservableCollection<BuildTrigger>(source.BuildTriggers);
     Build = new ObservableCollection<string>(source.Build);
     PreBuild = new ObservableCollection<string>(source.PreBuild);
     PostBuild = new ObservableCollection<string>(source.PostBuild);
     WatchRefs.CollectionChanged += CollectionChanged;
     BuildCheckouts.Changed += CheckoutsChanged;
     Commands.Changed += CommandsChanged;
     BuildTriggers.CollectionChanged += CollectionChanged;
     Build.CollectionChanged += CollectionChanged;
     PreBuild.CollectionChanged += CollectionChanged;
     PostBuild.CollectionChanged += CollectionChanged;
     LoadHistory(String.Empty);
 }
Example #35
0
        /// <summary>
        /// Finds all keys which contain the searchValue in their value.
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="dict">dictionary to look through</param>
        /// <param name="searchValue">object to serch for</param>
        /// <returns>An enumerable set containing all keys located, or null if no matches were found.</returns>
        public static IEnumerable <TKey> FindKeys <TKey, TValue>(this XDictionary <TKey, TValue> dict, TValue searchValue)
        {
            List <TKey> found = new List <TKey>();

            foreach (KeyValuePair <TKey, TValue> pair in dict)
            {
                dynamic val = pair.Value;
                if (val is IEnumerable <TValue> )
                {
                    if (val.Contains(searchValue))
                    {
                        found.Add(pair.Key);
                    }
                }
                if (val.Equals(searchValue))
                {
                    found.Add(pair.Key);
                }
            }

            return(found.Count <= 0 ? null : found);
        }
Example #36
0
        public static XDictionary <TKey, TElement> ToXDictionary <TSource, TKey, TElement>(this IEnumerable <TSource> source, Func <TSource, TKey> keySelector, Func <TSource, TElement> elementSelector, IEqualityComparer <TKey> comparer)
        {
            if (source == null)
            {
                throw new CoAppException("ToXDictionary (source) value null.");
            }
            if (keySelector == null)
            {
                throw new CoAppException("ToXDictionary (keySelector) value null.");
            }
            if (elementSelector == null)
            {
                throw new CoAppException("ToXDictionary (elementSelector) value null.");
            }

            var d = new XDictionary <TKey, TElement>(comparer);

            foreach (var element in source)
            {
                d.Add(keySelector(element), elementSelector(element));
            }
            return(d);
        }
Example #37
0
        public static TValue Get <TKey, TValue>(Object scope, TKey key, Func <TValue> valueFunc)
        {
            var cache = C <TKey, TValue> .Cache;
            IDictionary <TKey, TValue> inner;

            lock (cache) {
                if (!cache.ContainsKey(scope))
                {
                    cache.Add(scope, (inner = new XDictionary <TKey, TValue>()));
                }
                else
                {
                    inner = cache[scope];
                }
            }

            lock (inner) {
                if (!inner.ContainsKey(key))
                {
                    inner[key] = valueFunc();
                }
                return(inner[key]);
            }
        }
Example #38
0
 internal RegDiff()
 {
     Data = new XDictionary<string, XDictionary<string, ValueObject>>();
 }
Example #39
0
 internal CopyQueue()
 {
     _queue = new XDictionary <DiscFileInfo, DiscFileInfo>();
 }
        /// <summary>
        ///   The (non-static) startup method
        /// </summary>
        /// <param name = "args">
        ///   The command line arguments.
        /// </param>
        /// <returns>
        ///   Process return code.
        /// </returns>
        protected override int Main(IEnumerable<string> args)
        {
            // force temporary folder to be where we want it to be.
            CurrentTask.Events += new DownloadProgress((remoteLocation, location, progress) => {
                "Downloading {0}".format(remoteLocation.UrlDecode()).PrintProgressBar(progress);
            });

            CurrentTask.Events += new DownloadCompleted((remoteLocation, locallocation) => {
                Console.WriteLine();
            });

            PackageManager.AddSessionFeed(Environment.CurrentDirectory).Wait();

            var macrovals = new XDictionary<string, string>();

            try {
                // default:
                var options = args.Where(each => each.StartsWith("--")).Switches();
                var parameters = args.Where(each => !each.StartsWith("--")).Parameters();

                foreach (var arg in options.Keys) {
                    var argumentParameters = options[arg];
                    var last = argumentParameters.LastOrDefault();
                    var lastAsBool = string.IsNullOrEmpty(last) || last.IsTrue();

                    switch (arg) {
                            /* options  */

                            /* global switches */
                        case "verbose":
                            _verbose = lastAsBool;
                            Logger.Messages = true;
                            Logger.Warnings = true;
                            Logger.Errors = true;
                            break;

                        case "load-config":
                            // all ready done, but don't get too picky.
                            break;

                        case "nologo":
                            this.Assembly().SetLogo(string.Empty);
                            break;

                        case "show-tools":
                            Tools.ShowTools = lastAsBool;
                            break;

                        case "certificate-path":
                            _signingCertPath = Path.GetFullPath(last);
                            break;

                        case "password":
                            _signingCertPassword = last;
                            break;

                        case "remember":
                            _remember = lastAsBool;
                            break;

                        case "override":
                            Override = true;
                            break;

                        case "help":
                            return Help();

                        case "no-toolkit-dependency":
                            break;

                        default:
                            macrovals.Add(arg, last);
                            break;
                    }
                }

                // set up the stuff to catch our errors and warnings

                CurrentTask.Events += new Error(HandleErrors);
                CurrentTask.Events += new Warning(HandleWarnings);
                CurrentTask.Events += new Verbose(Verbose);
                CurrentTask.Events += new Message(HandleMessage);

                // find all the command line tools that we're gonna need.
                Tools.LocateCommandlineTools();

                if (!parameters.Any()) {
                    throw new ConsoleException("Missing .autopkg script.");
                    // throw new ConsoleException(Resources.NoConfigFileLoaded);
                }

                Logo();

                var allFiles = parameters.FindFilesSmarter().ToArray();
                foreach (var file in allFiles) {
                    FilesystemExtensions.ResetTempFolder();
                    using (var popd = new PushDirectory(Path.GetDirectoryName(file.GetFullPath()))) {
                        Binary.UnloadAndResetAll();

                        PackageManager.AddSessionFeed(Path.GetDirectoryName(file.GetFullPath())).Wait();

                        PackageSource = new PackageSource(file, macrovals );

                        var template = PropertySheet.Parse(Resources.template_autopkg,null);

                        PackageSource.ImportedSheets.Add("template", template);

                        FindCertificate();

                        SigningCertPath = _signingCertPath;
                        SigningCertPassword = _signingCertPassword;
                        Remember = _remember;

                        // ------- Create data model for package
                        CreatePackageModel();

                        // ------ Generate package MSI from model
                        CreatePackageFile();
                    }
                }

            } catch (PackageException) {
                return Fail("Autopackage encountered errors.\r\n");
            } catch (ConsoleException failure) {
                return Fail("{0}\r\n\r\n    {1}", failure.Message, Resources.ForCommandLineHelp);
            } catch (Exception failure) {
                if( failure.InnerException != null ) {
                    Fail("Exception Caught: {0}\r\n{1}\r\n\r\n    {2}", failure.InnerException.Message, failure.InnerException.StackTrace, Resources.ForCommandLineHelp);
                }

                return Fail("Exception Caught: {0}\r\n{1}\r\n\r\n    {2}", failure.Message, failure.StackTrace, Resources.ForCommandLineHelp);
            }
            return 0;
        }
Example #41
0
 private static void InnerRead(RegistryKey key, XDictionary<string, XDictionary<string, ValueObject>> data)
 {
     foreach (var name in key.GetValueNames())
     {
         data[key.Name][name] = new ValueObject(key.GetValueType(name), key.GetValue(name));
     }
     foreach (var sub in key.GetSubKeyNames())
     {
         InnerRead(key.OpenSubKey(sub), data);
     }
 }
Example #42
0
        private void Clean(IEnumerable<Rule> builds)
        {
            foreach( var build in builds ) {
                try {
                    // set environment variables:
                    var savedVariables = _originalEnvironment;
                    _originalEnvironment = new XDictionary<string, string>(savedVariables);

                    var sets = build["set"];
                    if (sets != null) {
                        foreach (var label in sets.Labels) {
                            _originalEnvironment.AddOrSet(label, sets[label].Value);
                            Environment.SetEnvironmentVariable(label, sets[label].Value);
                        }
                    }

                    // build dependencies first
                    CleanDependencies(build);

                    SetCompilerSdkAndPlatform(build);

                    var cmd = build["clean-command"];
                    try {
                        if (cmd != null && !string.IsNullOrEmpty(cmd.Value)) {
                            Exec(cmd.Value);
                        }
                    }
                    catch  {
                        //ignoring any failures from clean command.
                    }
                    File.Delete(Path.Combine(Environment.CurrentDirectory, "trace[{0}].xml".format(build.Name)));

                    _originalEnvironment = savedVariables;
                }
                catch (Exception e) {
                    Console.WriteLine("Uh, throw? {0} : {1}", e.Message, e.StackTrace);
                    //ignoring any failures from clean command.
                }

            }
        }
Example #43
0
        private static int doActions(string projectName, IEnumerable <string> commands, BuildStatus status = null, XDictionary <string, string> Macros = null)
        {
            if (projectName == null)
            {
                throw new ArgumentException("ProjectName cannot be null.");
            }
            if (!Projects.ContainsKey(projectName))
            {
                throw new ArgumentException("Project not found: " + projectName);
            }

            Macros = Macros ?? new XDictionary <string, string>();

            status = status ?? new BuildStatus();
            string ArchiveLoc = Path.Combine(MasterConfig.ProjectRoot, projectName, "Archive",
                                             status.TimeStamp.ToString(DateTimeDirFormat));

            if (!Directory.Exists(ArchiveLoc))
            {
                Directory.CreateDirectory(ArchiveLoc);
            }
            ProjectData    proj    = Projects[projectName];
            ProcessUtility _cmdexe = new ProcessUtility("cmd.exe");
            // Redirect stdout and stderr to the same output

            Func <string> getToolSwitches = () =>
            {
                string ret = String.Empty;
                foreach (
                    string s in
                    MasterConfig.VersionControlList[proj.VersionControl].Tool.
                    Switches)
                {
                    if (s.Contains(" "))
                    {
                        ret += " \"" + s + "\"";
                    }
                    else
                    {
                        ret += " " + s;
                    }
                }
                return(ret);
            };

            Macros["project"]     = projectName;
            Macros["vcstool"]     = MasterConfig.VersionControlList[proj.VersionControl].Tool.Path;
            Macros["vcsswitches"] = getToolSwitches();
            Macros["keepclean"]   = proj.KeepCleanRepo.ToString();
            string rootPath = MasterConfig.ProjectRoot + @"\" + projectName;

            Macros["projectroot"]    = rootPath;
            Macros["repo_url"]       = proj.RepoURL;
            Macros["build_datetime"] = status.TimeStamp.ToString(DateTimeDirFormat);
            Macros["archive"]        = ArchiveLoc;
            Macros["output_store"]   = MasterConfig.OutputStore;

            foreach (string command in commands)
            {
                StringBuilder std = new StringBuilder();
                _cmdexe.ResetStdOut(std);
                _cmdexe.ResetStdErr(std);

                status.Append("AutoBuild - Begin command:  " + command);
                Macros["currentcommand"] = command;

                CommandScript tmp;
                if (proj.Commands.ContainsKey(command))
                {
                    tmp = proj.Commands[command];
                }
                else if (MasterConfig.Commands.ContainsKey(command))
                {
                    tmp = MasterConfig.Commands[command];
                }
                else
                {
                    // Can't locate the specified command.  Bail with error.
                    status.Append("AutoBuild Error:  Unable to locate command script: " + command);
                    return((int)Errors.NoCommand);
                }

                int retVal = tmp.Run(_cmdexe, rootPath, projectName, new XDictionary <string, string>(Macros));
                status.Append(_cmdexe.StandardOut);
                if (retVal != 0)
                {
                    return(retVal);
                }
            }

            return(0);
        }
Example #44
0
 internal RegDiff()
 {
     Data = new XDictionary <string, XDictionary <string, ValueObject> >();
 }
Example #45
0
        /// <summary>
        /// Runs build rules
        /// </summary>
        /// <param name="builds">A list of build rules to build</param>
        private void Build(IEnumerable<Rule> builds)
        {
            foreach (var build in builds) {
                // set environment variables:
                var savedVariables = _originalEnvironment;
                _originalEnvironment = new XDictionary<string, string>(savedVariables);

                var sets = build["set"];
                if (sets != null) {
                    foreach( var label in sets.Labels ) {
                        _originalEnvironment.AddOrSet(label, sets[label].Value);
                        Environment.SetEnvironmentVariable(label, sets[label].Value);
                    }
                }

                // build dependencies first
                BuildDependencies(build);

                // install required packages...
                var requires = build["requires"];
                if( requires != null ) {
                    foreach( var pkg in requires.Values ) {
                        Console.WriteLine("Looking for {0}", pkg);
                        var installedPkgs = _easy.QueryPackages(pkg, Package.Properties.Installed.Is(true)).Result;
                        if( !installedPkgs.Any()) {
                            // there isn't a matching installed package, we'd better install one.
                            // refresh the feeds, as a package dependency might have recently been built...
                            foreach( var feed in sessionFeeds) {
                                _easy.AddSessionFeed(feed);
                            }

                            var pkgToInstall = _easy.QueryPackages(pkg, Package.Properties.Installed.Is(false)).Result;
                            bool failed = false;
                            _easy.InstallPackage(pkgToInstall.First().CanonicalName, autoUpgrade: true).Wait();

                            if( failed ) {
                                throw new ConsoleException("Unable to install dependent package.");
                            }
                        }
                    }
                }

                SetCompilerSdkAndPlatform(build);

                var generate = build["generate"];
                if(generate !=null &&  generate.HasValues ) {
                    var files = build["generate"].Labels;
                    if (!files.IsNullOrEmpty()) {
                        foreach (var file in files) {
                            File.WriteAllText(file,generate[file].Value);
                        }
                    }
                }

                if( !(_skipBuilt && CheckTargets(build, false)) )  {
                    // read the build command from PropertySheet
                    var cmd = build["build-command"];

                    // tell the user which build rule we are processing right now
                    if (_verbose || (cmd != null && !string.IsNullOrEmpty(cmd.Value))) {
                        using (new ConsoleColors(ConsoleColor.White, ConsoleColor.Black)) {
                            Console.WriteLine("Building Configuration [{0}]", build.Name);
                        }
                    }

                    // run this build command
                    if (cmd != null && !string.IsNullOrEmpty(cmd.Value)) {
                        Exec(cmd.Value);
                    }
                }

                // check to see that the right things got built
                CheckTargets(build);

                _originalEnvironment = savedVariables;
            }
        }
Example #46
0
        private int Startup(IEnumerable<string> args)
        {
            var options = args.Where(each => each.StartsWith("--")).Switches();
            var parameters = args.Parameters();

            foreach (var arg in options.Keys) {
                var argumentParameters = options[arg];

                switch (arg) {
                        /* global switches */
                    case "load-config":
                        // all ready done, but don't get too picky.
                        break;

                    case "nologo":
                        this.Assembly().SetLogo(string.Empty);
                        break;

                    case "help":
                        return Help();

                    case "certificate-path":
                        var cert = argumentParameters.Last();
                        _signingCertPath = _signingCertPath.IndexOf(":") > 1 ? cert : Path.GetFullPath(argumentParameters.Last());
                        break;

                    case "password":
                        _signingCertPassword = argumentParameters.Last();
                        break;

                    case "remember":
                        _remember = true;
                        break;

                    case "auto":
                        break;

                    case "sign":
                        _sign = true;
                        break;

                    case "just-sign":
                        _sign = true;
                        _justsign = true;
                        break;

                    case "strong-name":
                        _strongname = true;
                        break;

                    case "verbose":
                        _verbose = true;
                        break;

                    case "company":
                        _company = argumentParameters.Last();
                        break;

                    case "description":
                        _description = argumentParameters.Last();
                        break;

                    case "internal-name":
                        _internalName = argumentParameters.Last();
                        break;

                    case "copyright":
                        _copyright = argumentParameters.Last();
                        break;

                    case "original-filename":
                        _originalFilename = argumentParameters.Last();
                        break;

                    case "product-name":
                        _productName = argumentParameters.Last();
                        break;

                    case "verify":
                        _verify = true;
                        break;

                    case "reference-assembly":
                        foreach (var asmRef in argumentParameters) {
                            if (string.IsNullOrEmpty(asmRef)) {
                                return Fail("Missing assembly information for --assembly-reference.");
                            }

                            var parts = asmRef.Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                            var assemblyref = new AssemblyReference {Name = parts[0]};

                            foreach (var part in parts.Skip(1)) {
                                var kp = part.Split("= ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                                if (kp.Length != 2) {
                                    return Fail("Invalid option '{0}' in assembly reference '{1}'.", part, asmRef);
                                }

                                switch (kp[0].ToLower()) {
                                    case "version":
                                    case "ver":
                                        assemblyref.Version = kp[1];
                                        if (assemblyref.Version == 0L) {
                                            return Fail("Invalid Version '{0}' in assembly reference '{1}'.", kp[1], asmRef);
                                        }
                                        break;

                                    case "publickeytoken":
                                    case "pkt":
                                    case "token":
                                        if (kp[1].Length != 16) {
                                            return Fail("Invalid publicKeyToken '{0}' in assembly reference '{1}'.", kp[1], asmRef);
                                        }
                                        assemblyref.PublicKeyToken = kp[1];
                                        break;

                                    case "processorarchitecture":
                                    case "architecture":
                                    case "arch":
                                        assemblyref.Architecture = kp[1];
                                        if (assemblyref.Architecture == Architecture.Auto || assemblyref.Architecture == Architecture.Unknown) {
                                            return Fail("Invalid processorArchitecture '{0}' in assembly reference '{1}'.", kp[1], asmRef);
                                        }
                                        break;
                                }
                            }
                            if (assemblyref.Version == 0 || assemblyref.Architecture == Architecture.Unknown || string.IsNullOrEmpty(assemblyref.PublicKeyToken)) {
                                return Fail("Invalid assembly reference '{0}' ", asmRef);
                            }
                            assemblyReferences.Add(assemblyref);
                        }
                        break;

                    case "product-version":
                        _productVersion = argumentParameters.Last();
                        if (_productVersion == 0L) {
                            return Fail("--product-version must be in the form ##.##.##.##");
                        }

                        break;

                    case "file-version":
                        _fileVersion = argumentParameters.Last();
                        if (_fileVersion == 0L) {
                            return Fail("--file-version must be in the form ##.##.##.##");
                        }
                        break;

                    case "execution-level":
                        switch (argumentParameters.Last()) {
                            case "administrator":
                            case "admin":
                            case "requires-admin":
                            case "requiresadmin":
                            case "requiresadministrator":
                            case "requires-administrator":
                                _executionLevel = ExecutionLevel.requireAdministrator;
                                break;
                            case "invoker":
                            case "asinvoker":
                            case "as-invoker":
                                _executionLevel = ExecutionLevel.asInvoker;
                                break;
                            case "highest-available":
                            case "highest":
                            case "highestavailable":
                                _executionLevel = ExecutionLevel.highestAvailable;
                                break;
                        }
                        break;

                    case "dpi-aware":
                        if (argumentParameters.Last().IsTrue()) {
                            _dpiAware = true;
                        }
                        if (argumentParameters.Last().IsFalse()) {
                            _dpiAware = false;
                        }
                        break;
                    default:
                        return Fail("Unknown parameter [--{0}]", arg);
                }
            }

            Logo();

            if (_verify) {
                // return Verify(parameters);
            }

            if (string.IsNullOrEmpty(_signingCertPath)) {
                _certificate = CertificateReference.Default;
                if (_certificate == null) {
                    return Fail("No default certificate stored in the registry");
                }
            } else if (string.IsNullOrEmpty(_signingCertPassword)) {
                _certificate = new CertificateReference(_signingCertPath);
            } else {
                _certificate = new CertificateReference(_signingCertPath, _signingCertPassword);
            }

            using (new ConsoleColors(ConsoleColor.White, ConsoleColor.Black)) {
                Verbose("Loaded certificate with private key {0}", _certificate.Location);
            }

            if (_remember) {
                Verbose("Storing certificate details in the registry.");
                _certificate.RememberPassword();
                CertificateReference.Default = _certificate;
            }

            if (parameters.Count() < 1) {
                return Fail("Missing files to sign/name. \r\n\r\n    Use --help for command line help.");
            }

            var tasks = new List<Task>();

            if (_company != null && _company.Equals("auto", StringComparison.CurrentCultureIgnoreCase)) {
                _company = _certificate.CommonName;
            }
            var failures = 0;
            try {
                var allFiles = parameters.FindFilesSmarter().ToArray();
                var origMD5 = new XDictionary<string, string>();

                var loading = allFiles.Select(each =>
                    Binary.Load(each,
                        BinaryLoadOptions.PEInfo |
                            BinaryLoadOptions.VersionInfo |
                                BinaryLoadOptions.Managed |
                                    BinaryLoadOptions.Resources |
                                        BinaryLoadOptions.Manifest |
                                            BinaryLoadOptions.UnsignedManagedDependencies |
                                                BinaryLoadOptions.MD5).ContinueWith(antecedent => {
                                                    lock (allFiles) {
                                                        if (antecedent.IsFaulted) {
                                                            Console.WriteLine("Failed to load file '{0}'", each);
                                                            var e = antecedent.Exception.Flatten().InnerExceptions.First();
                                                            Console.WriteLine("{0}--{1}", e.Message, e.StackTrace);
                                                            return;
                                                        }

                                                        try {
                                                            var binary = antecedent.Result;
                                                            origMD5.Add(each, binary.MD5);

                                                            if (binary.IsPEFile && !_justsign) {
                                                                // do PE file stuff
                                                                if (_sign) {
                                                                    binary.SigningCertificate = _certificate;
                                                                }

                                                                if (binary.IsManaged && _strongname) {
                                                                    binary.StrongNameKeyCertificate = _certificate;
                                                                }

                                                                if (!assemblyReferences.IsNullOrEmpty()) {
                                                                    foreach (var asmRef in assemblyReferences) {
                                                                        binary.Manifest.Value.AddDependency(asmRef.Name, asmRef.Version, asmRef.Architecture, asmRef.PublicKeyToken);
                                                                    }
                                                                }

                                                                if (_company != null) {
                                                                    binary.CompanyName = _company;
                                                                }
                                                                if (_description != null) {
                                                                    binary.FileDescription = _description;
                                                                }
                                                                if (_internalName != null) {
                                                                    binary.InternalName = _internalName;
                                                                }
                                                                if (_copyright != null) {
                                                                    binary.LegalCopyright = _copyright;
                                                                }
                                                                if (_originalFilename != null) {
                                                                    binary.OriginalFilename = _originalFilename;
                                                                }
                                                                if (_productName != null) {
                                                                    binary.ProductName = _productName;
                                                                }
                                                                if (_productVersion != 0) {
                                                                    binary.ProductVersion = _productVersion;
                                                                }
                                                                if (_fileVersion != 0) {
                                                                    binary.FileVersion = _fileVersion;
                                                                }
                                                                if (_dpiAware != null) {
                                                                    binary.Manifest.Value.DpiAware = _dpiAware == true;
                                                                }
                                                                if (_executionLevel != ExecutionLevel.none) {
                                                                    binary.Manifest.Value.RequestedExecutionLevel = _executionLevel;
                                                                }
                                                            } else {
                                                                // do stuff for non-pe files
                                                                // we can try to apply a signature, and that's about it.
                                                                if (_sign) {
                                                                    binary.SigningCertificate = _certificate;
                                                                }
                                                            }
                                                            binary.Save().Wait();
                                                        } catch (Exception e) {
                                                            while (e.GetType() == typeof (AggregateException)) {
                                                                e = (e as AggregateException).Flatten().InnerExceptions[0];
                                                            }
                                                            failures += Fail("{0}--{1}", e.Message, e.StackTrace);
                                                        }
                                                    }
                                                }, TaskContinuationOptions.AttachedToParent)).ToArray();

                // Thread.Sleep(1000);
                // wait for loading.
                return Task.Factory.ContinueWhenAll(loading, tsks => {
                    Console.WriteLine("Done {0} files", tsks.Length);

                    (from each in Binary.Files
                        select new {
                            Filename = Path.GetFileName(each.Filename),
                            Original_MD5 = origMD5[each.Filename],
                            New_MD5 = each.MD5,
                            //  Status = each.Message,
                        }).ToTable().ConsoleOut();

                    if (failures > 0) {
                        Console.WriteLine("*** Bad News. Failed. *** ");
                    }

                    if (Binary.IsAnythingStillLoading) {
                        Console.WriteLine("\r\n==== Uh, stuff is still in the loading state?! ====\r\n");
                    }

                    return failures;
                }).Result;
            } catch (Exception e) {
                Console.WriteLine("{0}--{1}", e.Message, e.StackTrace);
                return Fail("not good.");
            }
        }
Example #47
0
        public PackageScript(string filename)
        {
            _nuspec.metadata.id = "Package";
            _nuspec.metadata.version = "1.0.0";
            _nuspec.metadata.authors = "NAME";
            _nuspec.metadata.owners = "NAME";
            _nuspec.metadata.licenseUrl = "http://LICENSE_URL_HERE_OR_DELETE_THIS_LINE";
            _nuspec.metadata.projectUrl = "http://PROJECT_URL_HERE_OR_DELETE_THIS_LINE";
            _nuspec.metadata.iconUrl = "http://ICON_URL_HERE_OR_DELETE_THIS_LINE";
            _nuspec.metadata.requireLicenseAcceptance = "false";
            _nuspec.metadata.description = "Package description";
            _nuspec.metadata.releaseNotes = "Summary of changes made in this release of the package.";
            _nuspec.metadata.copyright = "Copyright 2013";

            _sheet = new PropertySheet(this);

            // get the full path to the .autopkgFile
            var fullPath = filename.GetFullPath();
            autopkgFolder = Directory.GetParent(fullPath).FullName;

            // parse the script
            _sheet.ParseFile(filename);
            _sheet.ImportText(RequiredTemplate, "required");

            // ensure we have at least the package ID
            pkgName = _sheet.View.nuget.nuspec.id;
            if (string.IsNullOrEmpty(pkgName)) {
                throw new ClrPlusException("the Field nuget.nuspec.id can not be null or empty. You must specify an id for a package.");
            }

            // set the package name macro
            _sheet.AddMacro("pkgname", pkgName);

            // generate the relative output paths.
            nuspecPath = Path.Combine(autopkgFolder, "{0}.nuspec".format(pkgName));
            propsPath = Path.Combine(autopkgFolder, "{0}.props".format(pkgName));
            targetsPath = Path.Combine(autopkgFolder, "{0}.targets".format(pkgName));

            // do the property sheet mapping
            var conditions = new XDictionary<string, string>();

            _sheet.Route("nuget.nuspec".MapTo(new object() , MapNuspec().ToArray() ));
            _sheet.Route("nuget.files".MapTo( new object() ,
                "condition".MapTo(conditions, key => Configurations.NormalizeConditionKey(key, _sheet.View.configurations as View)),
                "*".MapTo(conditions, key => Configurations.NormalizeConditionKey(key, _sheet.View.configurations as View))
                ));

            var hasProps = (_sheet.View.nuget.HasChild("props") && _sheet.View.nuget.props.HasChildren );
            var hasTargets = (_sheet.View.nuget.HasChild("targets") && _sheet.View.nuget.targets.HasChildren);

            if (hasProps) {
                _sheet.MapProject("nuget.props", _props);
                _sheet.MapConfigurations("configurations", _props);
            }

            if (hasTargets) {
                _sheet.MapProject("nuget.targets", _targets);
                _sheet.MapConfigurations("configurations", _targets);
            }

            // persist the propertysheet to the msbuild model.
            _sheet.View.CopyToModel();

            // generate automatic rules for lib/bin/include
            var implictRules = _sheet.CurrentView.GetMetadataValue("options.implicit-rules").IsNegative();

            // process files
            ProcessFiles(_sheet.View.nuget.files, autopkgFolder, implictRules, null);
        }
        protected override int Main(IEnumerable<string> args)
        {
            var hosts = new string[] { "*" };
            var ports = new int[] { 80 };
            var commitMessage = "trigger";
            var packageUpload = "upload";

            string localfeedLocation = null;
            string packageStoragePath = null;
            string packagePrefixUrl = null;
            string canonicalFeedUrl = null;

            string tweetCommits = Settings["#tweet-commits"].StringValue;
            string tweetPackages = Settings["#tweet-packages"].StringValue;
            string azureAccount = Settings["#azure-account"].StringValue;

            string azureKey = null;

            var options = args.Where(each => each.StartsWith("--")).Switches();
            var parameters = args.Where(each => !each.StartsWith("--")).Parameters();
            var aliases = new XDictionary<string, string>();

            foreach (var arg in options.Keys) {
                var argumentParameters = options[arg];
                var last = argumentParameters.LastOrDefault();
                var lastAsBool = string.IsNullOrEmpty(last) || last.IsTrue();

                switch (arg) {
                        /* options  */
                    case "verbose":
                        _verbose = lastAsBool;
                        Logger.Errors = true;
                        Logger.Messages = true;
                        Logger.Warnings = true;
                        break;

                        /* global switches */
                    case "load-config":
                        // all ready done, but don't get too picky.
                        break;

                    case "nologo":
                        this.Assembly().SetLogo(string.Empty);
                        break;

                    case "help":
                        return Help();

                    case "feed-path":
                        localfeedLocation = last;
                        break;

                    case "feed-url":
                        canonicalFeedUrl = last;
                        break;

                    case "package-path":
                        packageStoragePath = last;
                        break;

                    case "package-prefix":
                        packagePrefixUrl = last;
                        break;

                    case "host":
                        hosts = argumentParameters.ToArray();
                        break;

                    case "port":
                        ports = argumentParameters.Select(each => each.ToInt32()).ToArray();
                        break;

                    case "package-upload":
                        packageUpload = last;
                        break;

                    case "commit-message":
                        commitMessage = last;
                        break;

                    case "tweet-commits":
                        Settings["#tweet-commits"].StringValue = tweetCommits = last;
                        break;

                    case "tweet-packages":
                        Settings["#tweet-commits"].StringValue = tweetPackages = last;
                        break;

                    case "azure-name":
                        Settings["#azure-account"].StringValue = azureAccount = last;
                        break;

                    case "azure-key":
                        azureKey = last;
                        break;
                }
                if( arg.StartsWith("alias-")) {
                    aliases.Add(arg.Substring(6), last);
                }
            }

            Tweeter.Init(Settings, options);
            Bitly.Init(Settings, options);
            CloudFileSystem cfs = null;

            if( !string.IsNullOrEmpty(azureAccount)) {
                cfs = new CloudFileSystem(Settings, azureAccount, azureKey);
            }

            try {
                var listener = new Listener();

                // get startup information.

                foreach( var host in hosts ) {
                    listener.AddHost(host);
                }

                foreach( var port in ports ) {
                    listener.AddPort(port);
                }

                listener.AddHandler(commitMessage, new CommitMessageHandler(tweetCommits, aliases));

                if( string.IsNullOrEmpty(packageStoragePath) || string.IsNullOrEmpty(localfeedLocation) || string.IsNullOrEmpty(packagePrefixUrl)  ) {
                    Console.WriteLine("[Package Uploader Disabled] specify must specify --package-path, --feed-path and  --package-prefix");
                }else {
                    listener.AddHandler(packageUpload, new UploadedFileHandler(localfeedLocation, canonicalFeedUrl, packageStoragePath, packagePrefixUrl, tweetPackages, cfs));
                }
                listener.Start();

                Console.WriteLine("Press ctrl-c to stop the listener.");

                while (true) {
                    // one day, Ill put a check to restart the server in here.
                    Thread.Sleep(60 * 1000);

                }

                // listener.Stop();
            } catch(Exception e) {
                Listener.HandleException(e);
                CancellationTokenSource.Cancel();
            }

            return 0;
        }
Example #49
0
        private static int PreBuildActions(string projectName, BuildStatus status = null, string checkoutRef = null)
        {
            if (projectName == null)
                throw new ArgumentException("ProjectName cannot be null.");
            if (!Projects.ContainsKey(projectName))
                throw new ArgumentException("Project not found: " + projectName);

            WriteVerbose("Start PreBuild: " + projectName);
            if (checkoutRef != null)
            {
                XDictionary<string, string> macros = new XDictionary<string, string>();
                macros["checkout"] = checkoutRef;
                return doActions(projectName, Projects[projectName].BuildCheckouts[checkoutRef].PreCmd, status, macros);
            }
            // else
            return doActions(projectName, Projects[projectName].PreBuild, status);
        }
Example #50
0
        private static int doActions(string projectName, IEnumerable<string> commands, BuildStatus status = null, XDictionary<string, string> Macros = null)
        {
            if (projectName == null)
                throw new ArgumentException("ProjectName cannot be null.");
            if (!Projects.ContainsKey(projectName))
                throw new ArgumentException("Project not found: " + projectName);

            Macros = Macros ?? new XDictionary<string, string>();

            status = status ?? new BuildStatus();
            string ArchiveLoc = Path.Combine(MasterConfig.ProjectRoot, projectName, "Archive",
                                             status.TimeStamp.ToString(DateTimeDirFormat));

            if (!Directory.Exists(ArchiveLoc))
                Directory.CreateDirectory(ArchiveLoc);
            ProjectData proj = Projects[projectName];
            ProcessUtility _cmdexe = new ProcessUtility("cmd.exe");
            // Redirect stdout and stderr to the same output

            Func<string> getToolSwitches = () =>
            {
                string ret = String.Empty;
                foreach (
                    string s in
                        MasterConfig.VersionControlList[proj.VersionControl].Tool.
                            Switches)
                    if (s.Contains(" "))
                        ret += " \"" + s + "\"";
                    else
                        ret += " " + s;
                return ret;
            };

            Macros["project"] = projectName;
            Macros["vcstool"] = MasterConfig.VersionControlList[proj.VersionControl].Tool.Path;
            Macros["vcsswitches"] = getToolSwitches();
            Macros["keepclean"] = proj.KeepCleanRepo.ToString();
            string rootPath = MasterConfig.ProjectRoot + @"\" + projectName;
            Macros["projectroot"] = rootPath;
            Macros["repo_url"] = proj.RepoURL;
            Macros["build_datetime"] = status.TimeStamp.ToString(DateTimeDirFormat);
            Macros["archive"] = ArchiveLoc;
            Macros["output_store"] = MasterConfig.OutputStore;

            foreach (string command in commands)
            {
                StringBuilder std = new StringBuilder();
                _cmdexe.ResetStdOut(std);
                _cmdexe.ResetStdErr(std);

                status.Append("AutoBuild - Begin command:  " + command);
                Macros["currentcommand"] = command;

                CommandScript tmp;
                if (proj.Commands.ContainsKey(command))
                {
                    tmp = proj.Commands[command];
                }
                else if (MasterConfig.Commands.ContainsKey(command))
                {
                    tmp = MasterConfig.Commands[command];
                }
                else
                {
                    // Can't locate the specified command.  Bail with error.
                    status.Append("AutoBuild Error:  Unable to locate command script: " + command);
                    return (int)Errors.NoCommand;
                }

                int retVal = tmp.Run(_cmdexe, rootPath, projectName, new XDictionary<string, string>(Macros));
                status.Append(_cmdexe.StandardOut);
                if (retVal != 0)
                    return retVal;
            }

            return 0;
        }
Example #51
0
 public int Run(string path, string project, XDictionary<string, string> macros)
 {
     ProcessUtility _cmdexe = new ProcessUtility("cmd.exe");
     return Run(_cmdexe, path, project, macros);
 }
Example #52
0
 public RegDiff()
 {
     Data = new XDictionary<string, XDictionary<string, ValueObject>>();
 }
Example #53
0
        private void InitializeNuget()
        {
            View nugetView = _sheet.View.nuget;

            _nuget = nugetView;

            if (!nugetView.HasChildren)
            {
                FailAlways(Event <SourceError> .Raise("AP100", _sheet.CurrentView.SourceLocations, "script does not contain a declaration for a NuGet package"));
            }

            _nuspec = _nuget.nuspec;

            if (!_nuspec.HasChildren)
            {
                FailAlways(Event <SourceError> .Raise("AP102", nugetView.SourceLocations, "script does not contain a 'nuspec' declaration in 'nuget'"));
            }

            var outputs = nugetView.GetMetadataItems("output-packages.");

            if (!outputs.Any())
            {
                FailAlways(Event <SourceError> .Raise("AP101", nugetView.SourceLocations, "script does not contain '#output-packages' declaration in 'nuget'"));
            }

            if (string.IsNullOrEmpty(_nuspec.id.Value))
            {
                FailAlways(Event <SourceError> .Raise("AP103", _nuspec.SourceLocations, "script does not contain a 'id' declaration in 'nuspec'"));
            }

            foreach (var each in outputs.Keys)
            {
                _nugetPackages.Add(each, new NugetPackage(this, each, outputs[each]));
            }

            // initialize the nuget packages
            nugetView.AddChildRoutes(_nugetPackages.Values.SelectMany(each => each.Initialize()));


            // do the property sheet mapping
            var conditions = new XDictionary <string, string>();

            // map the file routes
            nugetView.AddChildRoute("files".MapTo(new object(), new [] {
                "condition".MapTo(conditions, key => Pivots.GetExpressionFilepath(_nuspec.id, key)),
                "*".MapTo(conditions, key => Pivots.GetExpressionFilepath(_nuspec.id, key))
            }));

            var nuspecid = _nuspec.id;

            var conditionFolderMacroHander = (GetMacroValueDelegate)((macro, context) => {
                if (macro == "conditionFolder")
                {
                    return(LinqExtensions.SingleItemAsEnumerable(Pivots.GetExpressionFilepath(nuspecid, ((View)context).GetSingleMacroValue("ElementId") ?? "")));
                }
                return(null);
            });

            _nuget.props.AddMacroHandler(conditionFolderMacroHander);
            _nuget.targets.AddMacroHandler(conditionFolderMacroHander);

            nugetView.AddChildRoute("props".MapTo(() => GetPropsProject("default") /*, GetPropsProject("default").ProjectRoutes() */));

            // always need a targets
            nugetView.AddChildRoute("targets".MapTo(() => GetTargetsProject("default") /*, GetTargetsProject("default").ProjectRoutes() */));
            // other variants/frameworks

            nugetView.AddChildRoute(
                "condition".MapTo(_nugetPackages, key => NormalizeOuptutKey(key), new[] {
                "targets".MapTo <NugetPackage>(package => GetTargetsProject(package.PkgRole)),
                "props".MapTo <NugetPackage>(package => GetPropsProject(package.PkgRole))
            }));

            nugetView.AddChildRoute(
                "*".MapTo(_nugetPackages, key => NormalizeOuptutKey(key), new [] {
                "targets".MapTo <NugetPackage>(package => GetTargetsProject(package.PkgRole)),
                "props".MapTo <NugetPackage>(package => GetPropsProject(package.PkgRole))
            }));
        }
Example #54
0
        internal void ProcessFauxRoles()
        {
            foreach (var fauxPaxRule in Source.FauxApplicationRules) {
                Roles.Add(new Role() { Name = fauxPaxRule.Parameter ?? string.Empty, PackageRole = PackageRole.Faux });
                Console.WriteLine("Processing Faux-Pax Role: {0}", fauxPaxRule.Parameter);
                var files = FileList.ProcessIncludes(null, fauxPaxRule, "faux-pax", "include", Source.FileRules, Environment.CurrentDirectory);
                var name = fauxPaxRule.Parameter;
                var fauxPax = CompositionData.FauxApplications ?? (CompositionData.FauxApplications = new List<FauxApplication>());
                var downloadProperty = fauxPaxRule["downloads"] ?? fauxPaxRule["download"];
                var downloads = new XDictionary<string, Uri>();
                if (downloadProperty != null) {
                    foreach (var l in downloadProperty.Labels) {
                        if (downloadProperty.HasValues) {
                            var values = downloadProperty[l];
                            foreach (var uri in values) {
                                try {
                                    var targetUrl = new Uri(uri);
                                    string filename = l.MakeSafeFileName();
                                    if (string.IsNullOrEmpty(filename)) {
                                        var p = targetUrl.AbsolutePath;
                                        filename = p.Substring(p.IndexOf("/") + 1).MakeSafeFileName();
                                    }
                                    downloads[filename] = targetUrl;
                                } catch {
                                    Event<Error>.Raise(MessageCode.InvalidUri, fauxPaxRule.SourceLocation, "Uri '{0}' is not valid", uri);
                                }
                            }
                        }
                    }
                }

                var hasInstallCmd = fauxPaxRule["install"] != null && fauxPaxRule["install"]["command"] != null;
                var hasInstallParam = fauxPaxRule["install"] != null && fauxPaxRule["install"]["parameters"] != null;
                var hasRemoveCmd = fauxPaxRule["remove"] != null && fauxPaxRule["remove"]["command"] != null;
                var hasRemoveParam = fauxPaxRule["remove"] != null && fauxPaxRule["remove"]["parameters"] != null;

                fauxPax.Add( new FauxApplication {
                    Name = fauxPaxRule.Parameter,
                    Downloads =downloads,

                    InstallCommand = hasInstallCmd ? fauxPaxRule["install"]["command"].Value : "",
                    InstallParameters = hasInstallParam ? fauxPaxRule["install"]["parameters"].Value : "",

                    RemoveCommand = hasRemoveCmd ? fauxPaxRule["remove"]["command"].Value : "",
                    RemoveParameters = hasRemoveParam ? fauxPaxRule["remove"]["parameters"].Value : "",
                });

                if (!string.IsNullOrEmpty(name)) {
                    files = files.Select(
                        each => new FileEntry(each.SourcePath, Path.Combine(name.MakeSafeFileName(), each.DestinationPath))).ToArray();
                }
                DestinationDirectoryFiles = DestinationDirectoryFiles.Union(files);
            }
        }
Example #55
0
        private bool CheckTargets(Rule build, bool haltOnFail = true )
        {
            // we need the environment set correctly here.
            var savedVariables = _originalEnvironment;
            _originalEnvironment = new XDictionary<string, string>(savedVariables);

            var sets = build["set"];
            if (sets != null) {
                foreach (var label in sets.Labels) {
                    _originalEnvironment.AddOrSet(label, sets[label].Value);
                    Environment.SetEnvironmentVariable(label, sets[label].Value);
                }
            }

            ResetEnvironment();

            // var kids = LocalChildBuilds(build);
            var failed = LocalChildBuilds(build).Aggregate(false, (current, childBuild) => current || (!CheckTargets(childBuild, haltOnFail)));

            // if there are no targets, then you can't skip them if they aren't there.
            if (build["targets"] == null && !haltOnFail ) {
                return false;
            }

            if (build["targets"] != null) {
                foreach (var targ in build["targets"].Values.Where(targ => !File.Exists(targ))) {
                    failed = true;
                    if (haltOnFail) {
                        throw new ConsoleException("Target [{0}] was not found.", targ);
                    }
                }

                using (new ConsoleColors(ConsoleColor.Gray, ConsoleColor.Black)) {
                    Console.WriteLine("Targets Verified.");
                }
            }

            _originalEnvironment = savedVariables;
            return !failed;
        }
Example #56
0
        internal void ProcessDependencyInformation()
        {
            // -----------------------------------------------------------------------------------------------------------------------------------
            // Step 3 : Gather the dependency information for the package

            // explictly defined
            DependentPackages = new List<Package>();

            if( !Name.Equals("coapp", StringComparison.CurrentCultureIgnoreCase) ) {
                // don't auto-add the coapp.toolkit dependency for the toolkit itself.
                var toolkitPackage = AutopackageMain.PackageManager.QueryPackages(CanonicalName.CoAppItself, null, null, null).Result.OrderByDescending(each => each.Version).FirstOrDefault();

                if( toolkitPackage != null ) {
                    AutopackageMain.PackageManager.GetPackageDetails(toolkitPackage.CanonicalName).Wait();
                    //Console.WriteLine("Implict Package Dependency: {0}", toolkitPackage.CanonicalName);
                    DependentPackages.Add(toolkitPackage);
                }
            }

            AutopackageMain.PackageManager.SetAllFeedsStale().Wait();

            foreach (var pkgName in Source.RequiresRules.SelectMany(each => each["package"].Values)) {
                // for now, lets just see if we can do a package match, and grab just that packages
                // in the future, we should figure out how to make better decisions for this.
                try {
                    var packages = AutopackageMain.PackageManager.QueryPackages(pkgName, null, null, null).Result.OrderByDescending(each => each.Version).ToArray();

                    if( packages.IsNullOrEmpty()) {
                        Event<Error>.Raise( MessageCode.FailedToFindRequiredPackage, null, "Failed to find package '{0}'.", pkgName);
                    }

                    if( packages.Select(each => each.Name).Distinct().Count() > 1 ) {
                        Event<Error>.Raise(MessageCode.MultiplePackagesMatched, null, "Multiple Packages Matched package reference: '{0}'.", pkgName);
                    }

                    // makes sure it takes the latest one that matches. Hey, if you wanted an earlier one, you'd say explicitly :p
                    var pkg = packages.OrderByDescending(each => each.Version).FirstOrDefault();

                    // Console.WriteLine("Package Dependency: {0}", pkg.CanonicalName);

                    AutopackageMain.PackageManager.GetPackageDetails(pkg.CanonicalName).Wait();

                    DependentPackages.Add(pkg);

                } catch (Exception e) {
                    Event<Error>.Raise(
                        MessageCode.FailedToFindRequiredPackage, null, "Failed to find package '{0}'. [{1}]", pkgName, e.Message);
                }
            }

            foreach (var pkg in DependentPackages) {
                if (Dependencies == null ) {
                    Dependencies = new XDictionary<CanonicalName, XList<Uri>>();
                }
                Dependencies.Add(pkg.CanonicalName, pkg.Feeds.Where( each => each.IsWebUri()).ToXList());
            }

            // implicitly defined (check all binaries, to see what they depend on)
            // maybe in RC.
        }
        private void InitializeNuget() {
            View nugetView = _sheet.View.nuget;
            _nuget = nugetView;

            if (!nugetView.HasChildren ) {
                FailAlways(Event<SourceError>.Raise("AP100", _sheet.CurrentView.SourceLocations, "script does not contain a declaration for a NuGet package"));
            }

            _nuspec = _nuget.nuspec;

            if(!_nuspec.HasChildren) {
                FailAlways(Event<SourceError>.Raise("AP102", nugetView.SourceLocations, "script does not contain a 'nuspec' declaration in 'nuget'"));
            }


            if(string.IsNullOrEmpty(_nuspec.id.Value)) {
                FailAlways(Event<SourceError>.Raise("AP103", _nuspec.SourceLocations, "script does not contain a 'id' declaration in 'nuspec'"));
            }

            NugetPackage = new NugetPackage(this, PackageRole.@default, _nuspec.id.Value);
            nugetView.AddChildRoutes(NugetPackage.Initialize());

            // do the property sheet mapping
            var conditions = new XDictionary<string, string>();

            // map the file routes 
            nugetView.AddChildRoute("files".MapTo(new object() , new [] {
                "condition".MapTo(conditions, key => Pivots.GetExpressionFilepath(_nuspec.id, nugetView.ResolveMacrosInContext(key))),
                "*".MapTo(conditions, key => Pivots.GetExpressionFilepath(_nuspec.id, nugetView.ResolveMacrosInContext(key)))
            }));

            var nuspecid = _nuspec.id;

            var conditionFolderMacroHander = (GetMacroValueDelegate)((macro, context) => {
                if (macro == "conditionFolder") {
                    return LinqExtensions.SingleItemAsEnumerable(Pivots.GetExpressionFilepath(nuspecid, ((View)context).GetSingleMacroValue("ElementId")??""));
                }
                return null;
            });
            _nuget.props.AddMacroHandler(conditionFolderMacroHander);
            _nuget.targets.AddMacroHandler(conditionFolderMacroHander);

            nugetView.AddChildRoute("props".MapTo(NugetPackage.Props.Value /*, GetPropsProject("default").ProjectRoutes() */));
            
            // always need a targets
            nugetView.AddChildRoute("targets".MapTo(NugetPackage.Targets.Value/*, GetTargetsProject("default").ProjectRoutes() */));
            // other variants/frameworks

        }
Example #58
0
 public CopyQueue(bool CopyOnlyAsBinary = false)
 {
     _copyAsBinary = CopyOnlyAsBinary;
     _queue = new XDictionary<DiscFileInfo, Lineage>();
 }
Example #59
0
 internal CopyQueue()
 {
     _queue = new XDictionary<DiscFileInfo, DiscFileInfo>();
 }
Example #60
0
        private void InitializeNuget()
        {
            View nugetView = _sheet.View.nuget;
            _nuget = nugetView;

            if (!nugetView.HasChildren ) {
                FailAlways(Event<SourceError>.Raise("AP100", _sheet.CurrentView.SourceLocations, "script does not contain a declaration for a NuGet package"));
            }

            _nuspec = _nuget.nuspec;

            if(!_nuspec.HasChildren) {
                FailAlways(Event<SourceError>.Raise("AP102", nugetView.SourceLocations, "script does not contain a 'nuspec' declaration in 'nuget'"));
            }

            var outputs = nugetView.GetMetadataItems("output-packages.");
            if (!outputs.Any()) {
                FailAlways(Event<SourceError>.Raise("AP101", nugetView.SourceLocations, "script does not contain '#output-packages' declaration in 'nuget'"));
            }

            if(string.IsNullOrEmpty(_nuspec.id.Value)) {
                FailAlways(Event<SourceError>.Raise("AP103", _nuspec.SourceLocations, "script does not contain a 'id' declaration in 'nuspec'"));
            }

            foreach (var each in outputs.Keys) {
                _nugetPackages.Add(each, new NugetPackage(this, each, outputs[each]));
            }

            // initialize the nuget packages
            nugetView.AddChildRoutes(_nugetPackages.Values.SelectMany(each => each.Initialize()));

            // do the property sheet mapping
            var conditions = new XDictionary<string, string>();

            // map the file routes
            nugetView.AddChildRoute("files".MapTo(new object() , new [] {
                "condition".MapTo(conditions, key => Pivots.GetExpressionFilepath(_nuspec.id, key)),
                "*".MapTo(conditions, key => Pivots.GetExpressionFilepath(_nuspec.id, key))
            }));

            var nuspecid = _nuspec.id;

            var conditionFolderMacroHander = (GetMacroValueDelegate)((macro, context) => {
                if (macro == "conditionFolder") {

                    return LinqExtensions.SingleItemAsEnumerable(Pivots.GetExpressionFilepath(nuspecid, ((View)context).GetSingleMacroValue("ElementId")??""));
                }
                return null;
            });
            _nuget.props.AddMacroHandler(conditionFolderMacroHander);
            _nuget.targets.AddMacroHandler(conditionFolderMacroHander);

            nugetView.AddChildRoute("props".MapTo(() => GetPropsProject("default") /*, GetPropsProject("default").ProjectRoutes() */));

            // always need a targets
            nugetView.AddChildRoute("targets".MapTo(() => GetTargetsProject("default")/*, GetTargetsProject("default").ProjectRoutes() */));
            // other variants/frameworks

            nugetView.AddChildRoute(
                "condition".MapTo(_nugetPackages, key => NormalizeOuptutKey(key), new[] {
                    "targets".MapTo<NugetPackage>(package => GetTargetsProject(package.PkgRole)),
                    "props".MapTo<NugetPackage>(package => GetPropsProject(package.PkgRole))
                }));

            nugetView.AddChildRoute(
                "*".MapTo(_nugetPackages, key => NormalizeOuptutKey(key),new [] {
                    "targets".MapTo<NugetPackage>(package => GetTargetsProject(package.PkgRole)),
                    "props".MapTo<NugetPackage>(package => GetPropsProject(package.PkgRole))}));
        }