Beispiel #1
0
 public Fail(string message, ref AppsClient.AppsResult result)
 {
     result.FailMessages.Add(message);
     this.FlowProps.Add("Message", message);
     this.Color = "orange";
     this.End();
     AppsClient.AppsLog.LogInfo(message);
 }
Beispiel #2
0
 public Fail(string failMessage, ref AppsClient.AppsResult result)
 {
     Message = failMessage;
     //base.Signal(failMessage);
     base.Color = "orange";
     base.End();
     AppsClient.AppsLog.LogInfo(failMessage);
 }
        public static void Exec(string fileName, string command, Dictionary <string, string> args, string workingDirectory, ref AppsClient.AppsResult outResult)
        {
            var result = new AppsClient.AppsResult();

            try
            {
                var arguments = string.Join(" ", args.Select((k) => string.Format("{0} {1}", k.Key, " " + k.Value + " ")));

                //var projectPath = @"D:\Work\Brooksoft\AppsJS\AppsJSDev\AppsJSDev\AppsJSDev\appsjsdev.csproj"; // @"C:\Users\xyz\Documents\Visual Studio 2017\myConsole\bin\Debug\netcoreapp2.1\myConsole.dll";
                var procStartInfo = new System.Diagnostics.ProcessStartInfo();
                procStartInfo.FileName               = fileName;
                procStartInfo.Arguments              = @$ " {command} {arguments}";
                procStartInfo.UseShellExecute        = false;
                procStartInfo.CreateNoWindow         = false;
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.RedirectStandardError  = true;
                procStartInfo.WorkingDirectory       = workingDirectory;

                var sb = new System.Text.StringBuilder();
                var pr = new System.Diagnostics.Process();
                pr.StartInfo = procStartInfo;

                pr.OutputDataReceived += (s, ev) =>
                {
                    if (string.IsNullOrWhiteSpace(ev.Data))
                    {
                        return;
                    }

                    //string[] split = ev.Data.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                    result.SuccessMessages.Add(ev.Data.ToString());
                };

                pr.ErrorDataReceived += (s, err) =>
                {
                    //result.FailMessages.Add("data: " + s.ToString() + ", err: " + err.ToString());
                };

                pr.EnableRaisingEvents = true;

                result.SuccessMessages.Add("files: " + pr.StartInfo.FileName + ", args: " + pr.StartInfo.Arguments);

                pr.Start();
                pr.BeginOutputReadLine();
                pr.BeginErrorReadLine();

                pr.WaitForExit();

                result.Success = true;

                outResult = result;
            }
            catch (System.Exception ex)
            {
                new AppFlows.Helpers.AppsSystem.Exception(ex, ref outResult);
            }
        }
        public void GetANewDatabaseOnFirstRegistration()
        {
            var appsData = new Moq.Mock <AppsDesktop.AppsData>(Moq.MockBehavior.Strict);
            var db       = new Moq.Mock <LiteDB.LiteDatabase>(Moq.MockBehavior.Strict);

            var config = new AppsClient.AppsClientConfig();
            var result = new AppsClient.AppsResult();

            //Business.AppsHelper.RegisterClient(appsData.Object, db.Object, config, ref result);
        }
        /// <summary>
        /// Called whenever client starts up (Run).
        ///
        ///See https://github.com/rbrooks33/Brooksoft.Apps.DevOps/discussions/3
        ///
        /// Scenarios
        /// 1.) New client (no database yet or database deleted)
        ///
        /// 2.) Existing client (sunny day, database exists
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public async Task SendAppsClientConfig(AppsClient.AppsClientConfig config)
        {
            var result = new AppsClient.AppsResult();

            try
            {
                AppsHelper.RegisterClient(_data, AppsDB, config, ref result);
            }
            catch (System.Exception ex)
            {
                new AppFlows.Helpers.AppsSystem.Exception(ex, ref result);
            }
        }
        public Client(int appId, LiteDB.LiteDatabase appsDb, ref AppsClient.AppsResult result)
        {
            var appsTable = appsDb.GetCollection <App>("Apps");
            var appsList  = appsTable.Query().Where(app => app.AppID == appId);

            if (appsList.Count() == 1)
            {
                PopulateClient(appsList.Single());
            }
            else
            {
                new AppFlows.Helpers.AppsSystem.Fail("Number of apps for appid not one: " + appsList.Count().ToString(), ref result);
            }
        }
Beispiel #7
0
        public Test(AppsClient.AppsResult result)
        {
            string resultString = "Success: " + result.Success.ToString() + System.Environment.NewLine;

            resultString += "Success Messages: " + System.Environment.NewLine;
            foreach (string smessage in result.SuccessMessages)
            {
                resultString += smessage + System.Environment.NewLine;
            }

            foreach (string fmessage in result.FailMessages)
            {
                resultString += fmessage + System.Environment.NewLine;
            }

            this.Color  = "green";
            this.Result = resultString;
            this.End();
        }
Beispiel #8
0
 public Exception(System.Exception ex, ref AppsClient.AppsResult result)
 {
     this.Color = "red";
     this.ExceptionAndResult(ex, ref result);
     AppsClient.AppsLog.LogError(ex.ToString());
 }
        public static void ExceptionAndResult(this AppFlow flow, System.Exception ex, ref AppsClient.AppsResult result)
        {
            var f = new AppFlowEvent();

            f.FlowProps.Add("Message", ex.Message);
            f.FlowProps.Add("StackTrace", ex.ToString());
            f.FlowProps.Add("Result", Newtonsoft.Json.JsonConvert.SerializeObject(result));
            FlowUtility.SaveFlow(f, flow);
        }
        public void ReadEffectivePermissions(string folder, string username, ref AppsClient.AppsResult result)
        {
            ////String UserName = "******";
            //do
            //{
            //    Console.WriteLine("UserName:"******"rbrooks"; // Console.ReadLine();
            //    Console.WriteLine("Path:");
            String Path = folder;       // @"D:\Work\Brooksoft\AppsJS\AppsJSCLI2\AppsDesktop\AppFolders\App49\Software\Software19"; // Console.ReadLine();


            if (System.IO.Directory.Exists(folder))
            {
                IntPtr      pSidOwner, pSidGroup, pDacl, pSacl, pSecurityDescriptor;
                ACCESS_MASK mask = new ACCESS_MASK();
                uint        ret  = GetNamedSecurityInfo(Path,
                                                        SE_OBJECT_TYPE.SE_FILE_OBJECT,
                                                        SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION | SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION,
                                                        out pSidOwner, out pSidGroup, out pDacl, out pSacl, out pSecurityDescriptor);

                IntPtr hManager = IntPtr.Zero;


                bool f = AuthzInitializeResourceManager(1, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, null, out hManager);

                NTAccount          ac    = new NTAccount(UserName);
                SecurityIdentifier sid   = (SecurityIdentifier)ac.Translate(typeof(SecurityIdentifier));
                byte[]             bytes = new byte[sid.BinaryLength];
                sid.GetBinaryForm(bytes, 0);
                String _psUserSid = "";
                foreach (byte si in bytes)
                {
                    _psUserSid += si;
                }

                LUID   unusedSid = new LUID();
                IntPtr UserSid   = Marshal.AllocHGlobal(bytes.Length);
                Marshal.Copy(bytes, 0, UserSid, bytes.Length);
                IntPtr pClientContext = IntPtr.Zero;

                if (f)
                {
                    f = AuthzInitializeContextFromSid(0, UserSid, hManager, IntPtr.Zero, unusedSid, IntPtr.Zero, out pClientContext);


                    AUTHZ_ACCESS_REQUEST request = new AUTHZ_ACCESS_REQUEST();
                    request.DesiredAccess        = 0x02000000;
                    request.PrincipalSelfSid     = null;
                    request.ObjectTypeList       = null;
                    request.ObjectTypeListLength = 0;
                    request.OptionalArguments    = IntPtr.Zero;

                    AUTHZ_ACCESS_REPLY reply = new AUTHZ_ACCESS_REPLY();
                    reply.GrantedAccessMask     = IntPtr.Zero;
                    reply.ResultListLength      = 0;
                    reply.SaclEvaluationResults = IntPtr.Zero;
                    IntPtr AccessReply = IntPtr.Zero;
                    reply.Error             = Marshal.AllocHGlobal(1020);
                    reply.GrantedAccessMask = Marshal.AllocHGlobal(sizeof(uint));
                    reply.ResultListLength  = 1;
                    int i = 0;
                    Dictionary <String, String> rightsmap = new Dictionary <String, String>();
                    List <string> effectivePermissionList = new List <string>();
                    string[]      rights = new string[14] {
                        "Full Control", "Traverse Folder / execute file", "List folder / read data", "Read attributes", "Read extended attributes", "Create files / write files", "Create folders / append data", "Write attributes", "Write extended attributes", "Delete subfolders and files", "Delete", "Read permission", "Change permission", "Take ownership"
                    };
                    rightsmap.Add("FILE_TRAVERSE", "Traverse Folder / execute file");
                    rightsmap.Add("FILE_LIST_DIRECTORY", "List folder / read data");
                    rightsmap.Add("FILE_READ_DATA", "List folder / read data");
                    rightsmap.Add("FILE_READ_ATTRIBUTES", "Read attributes");
                    rightsmap.Add("FILE_READ_EA", "Read extended attributes");
                    rightsmap.Add("FILE_ADD_FILE", "Create files / write files");
                    rightsmap.Add("FILE_WRITE_DATA", "Create files /  write files");
                    rightsmap.Add("FILE_ADD_SUBDIRECTORY", "Create folders / append data");
                    rightsmap.Add("FILE_APPEND_DATA", "Create folders / append data");
                    rightsmap.Add("FILE_WRITE_ATTRIBUTES", "Write attributes");
                    rightsmap.Add("FILE_WRITE_EA", "Write extended attributes");
                    rightsmap.Add("FILE_DELETE_CHILD", "Delete subfolders and files");
                    rightsmap.Add("DELETE", "Delete");
                    rightsmap.Add("READ_CONTROL", "Read permission");
                    rightsmap.Add("WRITE_DAC", "Change permission");
                    rightsmap.Add("WRITE_OWNER", "Take ownership");


                    f = AuthzAccessCheck(0, pClientContext, ref request, IntPtr.Zero, pSecurityDescriptor, null, 0, ref reply, out AccessReply);
                    if (f)
                    {
                        int granted_access = Marshal.ReadInt32(reply.GrantedAccessMask);

                        mask = (ACCESS_MASK)granted_access;

                        foreach (ACCESS_MASK item in Enum.GetValues(typeof(ACCESS_MASK)))
                        {
                            if ((mask & item) == item)
                            {
                                effectivePermissionList.Add(rightsmap[item.ToString()]);
                                i++;
                            }
                        }
                    }
                    Marshal.FreeHGlobal(reply.GrantedAccessMask);



                    if (i == 16)
                    {
                        new AppFlows.Publish.Success("All perms satisfied so adding also full control.");
                        effectivePermissionList.Insert(0, "Full Control");
                    }
                    //        Console.WriteLine(".......................");
                    //        foreach (string r in rights)
                    //        {
                    //            if (effectivePermissionList.Contains(r))
                    //            {
                    //                Console.WriteLine(r);
                    //            }
                    //        }

                    //    }
                    //    Console.WriteLine("_________________________________________________\n");
                    //} while (true);

                    //Console.ReadLine();
                    result.Data    = effectivePermissionList;
                    result.Success = true;
                }
            }
            else
            {
                new AppFlows.Publish.Fail("Folder provided was not found.", ref result);
            }
        }
        private static void UpdateAppSoftwareFilesAndCodes(Client client, AppsClient.AppsClientConfig clientConfig, ref AppsClient.AppsResult result)
        {
            var softwareFilesDB = client.DB.GetCollection <SoftwareFile>("SoftwareFiles");

            //softwareFilesDB.DeleteMany(sf => sf.AppID == client.App.AppID);

            //Update software files
            foreach (string csFileFullName in clientConfig.CSFileFullNames)
            {
                if (System.IO.File.Exists(csFileFullName))
                {
                    string csContents = System.IO.File.ReadAllText(csFileFullName);

                    //Look for already-saved cs file in app
                    var existingFileList = client.App.SoftwareFiles.Where(f => f.FullName == csFileFullName);

                    if (existingFileList.Count() == 1)
                    {
                        //We've already gotten it, refresh and save
                        var existingFile = existingFileList.Single();
                        existingFile.Contents = csContents;
                        existingFile.FullName = csFileFullName;
                        existingFile.Updated  = DateTime.Now;
                        existingFile.AppID    = client.App.AppID;

                        softwareFilesDB.Upsert(existingFile);

                        UpdateCSFileCodes(client, existingFile, ref result);
                    }
                    else if (existingFileList.Count() == 0)
                    {
                        //Haven't seen this one, add it to app
                        var newFile = new SoftwareFile
                        {
                            Contents     = csContents,
                            Created      = DateTime.Now,
                            FileLanguage = SoftwareFileLanguages.CSharp,
                            FullName     = csFileFullName,
                            AppID        = client.App.AppID
                        };

                        softwareFilesDB.Insert(newFile);

                        client.App.SoftwareFiles.Add(newFile);

                        UpdateCSFileCodes(client, newFile, ref result);
                    }
                    else
                    {
                        new AppFlows.Helpers.AppsSystem.Fail("More than one copy of csfile in app: " + existingFileList.Count().ToString(), ref result);
                    }
                }
                else
                {
                    new AppFlows.Helpers.AppsSystem.Fail("Incoming config cs file path not found.", ref result);
                }

                client.App.Updated = DateTime.Now;
            }
        }
        public static void RegisterClient(AppsData data, LiteDB.LiteDatabase appsDb, AppsClient.AppsClientConfig config, ref AppsClient.AppsResult result)
        {
            var objs = appsDb.GetCollection <App>("Apps");
            var apps = objs.Query().Where(a => a.MachineName == config.MachineName && a.WorkingFolder == config.WorkingDirectory);
            App app  = null;

            if (apps.Count() == 0)
            {
                app = new App()
                {
                    Created       = DateTime.Now,
                    MachineName   = config.MachineName,
                    WorkingFolder = config.WorkingDirectory,
                    Updated       = DateTime.Now,
                    IsEnabled     = true,
                    LocalHostPort = config.LocalHostPort
                };

                objs.Insert(app);
            }
            else if (apps.Count() == 1)
            {
                app               = apps.Single();
                app.Updated       = DateTime.Now;
                app.LocalHostPort = config.LocalHostPort;
                objs.Upsert(app);
            }
            else
            {
                new AppFlows.Helpers.AppsSystem.Fail("Found more than one matching app for incoming config: " + apps.Count().ToString(), ref result);
            }

            var client = new Client(app, ref result);

            AppsHelper.UpdateAppSoftwareFilesAndCodes(client, config, ref result);
        }
        private static void UpdateCSFileCodes(Client client, SoftwareFile softwareFile, ref AppsClient.AppsResult result)
        {
            var softwareFileCodeDB = client.DB.GetCollection <SoftwareFileCode>("SoftwareFileCodes");

            Microsoft.CodeAnalysis.SyntaxTree tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(softwareFile.Contents);
            var descendents = tree.GetRoot().DescendantNodes(); //.OfType<LiteralExpressionSyntax>();

            foreach (var desc in descendents)
            {
                if (desc.GetType().Name == "MethodDeclarationSyntax")
                {
                    var method = (MethodDeclarationSyntax)desc;

                    var existingCodeList = softwareFile.SoftwareFileCodes.Where(sc => sc.Name == method.Identifier.Text);
                    if (existingCodeList.Count() == 1)
                    {
                        var existingCode = existingCodeList.Single();
                        existingCode.CodeType       = SoftwareFileCodeTypes.Method;
                        existingCode.Contents       = method.Body.ToFullString();
                        existingCode.Name           = method.Identifier.Text;
                        existingCode.SoftwareFileID = softwareFile.SoftwareFileID;

                        softwareFileCodeDB.Upsert(existingCode);
                    }
                    else if (existingCodeList.Count() == 0)
                    {
                        var newCode = new SoftwareFileCode
                        {
                            CodeType                                           = SoftwareFileCodeTypes.Method,
                            Contents                                           = method.Body != null?method.Body.ToFullString() : "",
                                                                Name           = method.Identifier.Text,
                                                                SoftwareFileID = softwareFile.SoftwareFileID
                        };

                        softwareFileCodeDB.Insert(newCode);

                        softwareFile.SoftwareFileCodes.Add(newCode);
                    }
                    else
                    {
                        result.FailMessages.Add("More than one code found for " + method.Identifier.Text + " in file " + softwareFile.FullName);
                    }
                }
            }
        }
Beispiel #14
0
 public CompileSuccess(ref AppsClient.AppsResult result)
 {
     this.Result = Newtonsoft.Json.JsonConvert.SerializeObject(result);
     this.Color  = "green";
     this.End();
 }
        public Client(string machineName, string workingFolder, LiteDB.LiteDatabase appsDb, ref AppsClient.AppsResult result)
        {
            var appsTable = appsDb.GetCollection <App>("Apps");
            var appsList  = appsTable.Query().Where(app => app.MachineName == machineName && app.WorkingFolder == workingFolder);

            if (appsList.Count() == 1)
            {
                PopulateClient(appsList.Single());
            }
            else
            {
                new AppFlows.Helpers.AppsSystem.Fail("Number of apps for appid not one: " + appsList.Count().ToString(), ref result);
            }
        }
 public Client(App app, ref AppsClient.AppsResult result)
 {
     PopulateClient(app);
 }