예제 #1
0
        static void Main(string[] args)
        {
            GetStatus getStatus = null;

            getStatus += new GetStatus(new Light().Switch);
            getStatus += new GetStatus(new Light().Switch);
            getStatus += new GetStatus(new Fan().Speed);
            getStatus += new GetStatus(new Fan().Speed);

            /* 委托类型的Invoke方法包含了对数组中的所有项进行遍历的代码
             * 这是一个很简单的算法,尽管这个简单的算法足以应付很多情形,但是也有局限
             * 这个简单的算法只是顺序调用链中的每一个委托,所以一个委托对象出现问题,链中的所有后续对象都无法调用
             * 因此,MulticastDelegate类提供了一个实例方法GetInvocationList,用于显式调用链中每一个委托
             */

            Delegate[] delegates = getStatus.GetInvocationList();
            foreach (GetStatus status in delegates)
            {
                try
                {
                    Console.WriteLine(status());
                }
                catch (InvalidOperationException e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine(status.Target);
                }
            }

            Console.ReadKey();
        }
예제 #2
0
파일: Select.cs 프로젝트: N1025/Charactopia
    // Start is called before the first frame update
    public void Turn()
    {
        GameObject c = GameObject.Find("コメントパネル/Text");

        coment = c.GetComponent <Text>();
        GameObject sta = GameObject.Find("戦闘処理");

        getStatus = sta.GetComponent <GetStatus>();
        speed     = new List <int> {
            getStatus.Getpspd1(), getStatus.Getespd1() - 1
        };
        if (getStatus.Getkazu() >= 2)
        {
            speed.Add(getStatus.Getespd2() - 2);
            if (getStatus.Getkazu() >= 3)
            {
                speed.Add(getStatus.Getespd3() - 3);
                if (getStatus.Getkazu() == 4)
                {
                    speed.Add(getStatus.Getespd4() - 4);
                }
            }
        }
        move = smove;
        Debug.Log("ターン" + turn);
        Debug.Log("行動数" + move + "/" + smove);
        //Debug.Log("speed "+speed[0] + "," + speed[1] + "," + speed[2] + "," + speed[3] + "," + speed[4]);
        Move();
    }
예제 #3
0
        private bool GetLatestVersion(string Path, RecursionType RecursionLevel)
        {
            bool result = false;

            WorkspaceInfo[] wsis = Workstation.Current.GetAllLocalWorkspaceInfo();

            foreach (WorkspaceInfo wsi in wsis)
            {
                //Ensure that all this processing is for the current server.
                if (!wsi.ServerUri.DnsSafeHost.ToLower().Equals(collectionUrl.ToLower().Replace("http://", "").Split('/')[0]))
                {
                    continue;
                }

                Workspace ws = GetWorkspace(wsi);

                //CommonHelper.WriteMessage(string.Format("Check-Out {0}.", Path));
                GetRequest request = new GetRequest(new ItemSpec(Path, RecursionType.Full), VersionSpec.Latest);
                GetStatus  status  = ws.Get(request, GetOptions.Overwrite);

                //CommonHelper.WriteMessage(string.Format("Checked-Out {0}.", Path));

                result = true;
                break;
            }
            return(result);
        }
예제 #4
0
        /// <summary>
        ///    Запрашивание состояния у компонентов делегата GetStatus
        /// </summary>
        /// <param name="status">Делегат GetStatus</param>
        /// <returns>Отчет</returns>
        private static string GetComponentStatusReport(GetStatus status)
        {
            // Если цепочка пуста, действий не нужно
            if (status == null)
            {
                return(null);
            }

            // Построение отчета о состоянии
            StringBuilder report = new StringBuilder();

            // Создание массива из делегатов цепочки
            var delegates = status.GetInvocationList();

            foreach (var getStat in delegates.Cast <GetStatus>())
            {
                try
                {
                    report.AppendFormat("{0}{1}{1}", getStat(), Environment.NewLine);
                }
                catch (InvalidOperationException e)
                {
                    var component = getStat.Target;
                    report.AppendFormat("Failed to get status from {1}{2}{0} Error: {3}{0}{0}", Environment.NewLine,
                                        component == null ? "" : component.GetType() + ".", getStat.Method.Name, e.Message);
                }
            }

            return(report.ToString());
        }
예제 #5
0
        public GettingDialog(VersionControlServer vcs, Workspace workspace, GetRequest[] requests) : base("Progress")
        {
            VBox.Spacing = 10;
            VBox.Add(new Label("Getting files from the server..."));

            progressBar = new ProgressBar();
            VBox.Add(progressBar);

            fileLabel = new Label("");
            VBox.Add(fileLabel);

            AddCloseButton("Cancel");
            DefaultResponse = ResponseType.Cancel;

            ShowAll();

            getLatestList.Clear();
            vcs.Getting += MyGettingEventHandler;

            GetStatus status = workspace.Get(requests, GetOptions.GetAll | GetOptions.Overwrite);

            foreach (string file in getLatestList)
            {
                Console.WriteLine(file);
                Pulse("Setting permissions: " + file);
                if (!FileTypeDatabase.ShouldBeExecutable(file))
                {
                    continue;
                }
                FileType.MakeExecutable(file);
            }
        }
예제 #6
0
        private GetStatus IsFree(ChannelEvent latestEvent)
        {
            if (latestEvent == null)
            {
                return(new GetStatus
                {
                    IsFree = true
                });
            }

            var difference = DateTime.UtcNow - latestEvent.DateTime;

            var isFreeStatus = new GetStatus
            {
                DateTime   = DateTime.SpecifyKind(latestEvent.DateTime, DateTimeKind.Utc),
                Difference = difference
            };

            var differentTimeSpan = (new TimeSpan(0, 2, 0)); // 2 minutes

            if (difference >= differentTimeSpan)
            {
                isFreeStatus.IsFree = true;
            }

            return(isFreeStatus);
        }
예제 #7
0
        private void getLogic()
        {
            APICaller caller = new APICaller("getRankings.php").AddParam("privateKey", PrivateKey);

            JObject obj = caller.Call();

            //Console.WriteLine(obj);
            if (obj["status"].ToString() == "success")
            {
                List <User> rankings = new List <User>();
                obj["users"].ToList().ForEach((user) =>
                {
                    rankings.Add(new User
                    {
                        Username               = user["username"].ToString(),
                        FirstName              = user["firstName"].ToString(),
                        LastName               = user["lastName"].ToString(),
                        KarmaPoints            = user["karmaPoints"].ToObject <int>(),
                        IsLecturer             = Convert.ToBoolean(user["lecturer"].ToObject <int>()),
                        ProfilePictureLocation = user["profilePicture"].ToString()
                    });
                });
                GetRankingsResult(GetStatus.Success, rankings);
            }
            else
            {
                GetStatus status = GetStatus.UnknownError;
                if (!Enum.TryParse <GetStatus>(obj["message"].ToString(), out status))
                {
                    status = GetStatus.UnknownError;
                }
                GetRankingsResult(status, null);
            }
        }
        public List <BDMAppoinmentDetailByStatus> GetAllStatusCoordinator(GetStatus objAppointmentDetail)
        {
            List <BDMAppoinmentDetailByStatus> appoinment = new List <BDMAppoinmentDetailByStatus>();

            using (DbLayer dbLayer = new DbLayer())
            {
                SqlCommand SqlCmd = new SqlCommand("spSelectHotandWarm");
                SqlCmd.CommandType = CommandType.StoredProcedure;
                SqlCmd.Parameters.AddWithValue("@ActionBy", objAppointmentDetail.ActionBy);
                if (objAppointmentDetail.FromDate.Year != 1 && objAppointmentDetail.ToDate.Year != 1)
                {
                    SqlCmd.Parameters.AddWithValue("@FromDate", objAppointmentDetail.FromDate);
                    SqlCmd.Parameters.AddWithValue("@ToDate", objAppointmentDetail.ToDate);
                }
                else
                {
                    var fr = DateTime.Now.AddDays(-30);
                    var en = DateTime.Now;
                    SqlCmd.Parameters.AddWithValue("@FromDate", fr);
                    SqlCmd.Parameters.AddWithValue("@ToDate", en);
                }
                appoinment = dbLayer.GetEntityList <BDMAppoinmentDetailByStatus>(SqlCmd);
            }
            return(appoinment);
        }
예제 #9
0
        private static string GetComponentStatusReport(GetStatus getStatus)
        {
            if (getStatus == null)
            {
                return("delegate is null");
            }

            StringBuilder sb = new StringBuilder();

            Delegate[] arrayOfDelegates = getStatus.GetInvocationList();

            foreach (GetStatus status in arrayOfDelegates)
            {
                try
                {
                    sb.AppendFormat("{0}{1}{1}", status(), Environment.NewLine);
                }
                catch (Exception e)
                {
                    object component = status.Target;
                    sb.AppendFormat("failed to get status from {0}{2}{0}   error:{3}{0}{0}", Environment.NewLine,
                                    component == null ? "" : component.GetType() + ".", status.Method.Name, e.Message);
                }
            }
            return(sb.ToString());
        }
예제 #10
0
 private bool ValidateStatus(GetStatus status)
 {
     if (status.NoActionNeeded && status.NumOperations == 0)
     {
         _log.Info("Result: No operations were performed.");
         return(true);
     }
     else if (status.NoActionNeeded && status.NumOperations > 0 && status.NumConflicts == 0)
     {
         _log.Info("Result: Completed without conflicts.");
         return(true);
     }
     else if (status.NoActionNeeded && status.NumConflicts > 0 && status.NumResolvedConflicts > 0 && status.NumConflicts == status.NumResolvedConflicts)
     {
         _log.Info("Result: Completed with conflicts. Conflicts resolved automatically.");
         return(true);
     }
     else if (status.NoActionNeeded == false && status.NumConflicts > 0 && status.HaveResolvableWarnings == false)
     {
         _log.Info("Result: Completed with conflicts. Conflicts could NOT resolved automatically. Please resolve conflicts using IDE and rerun exe; process is stateless");
         return(false);
     }
     else
     {
         _log.Info("Result: *** Unhandled conflict status, process is terminating. Possible completed with conflicts, please resolve conflicts using IDE and contact administrator before rerun exe; process is stateless ***");
         _log.InfoFormat("NumOperations: {0}, NumResolvedConflicts: {1}, NumWarnings: {2}, NoActionNeeded {3}, HaveResolvableWarnings: {4}", status.NumOperations, status.NumResolvedConflicts, status.NumWarnings, status.NoActionNeeded, status.HaveResolvableWarnings);
         return(false);
     }
 }
예제 #11
0
        public void UpdateBranch(BranchType Branch)
        {
            if (!_branchMap.ContainsKey(Branch))
            {
                throw new MyTfsConnectionException("Invalid branch: " + Branch);
            }

            List <BranchType> branches = BranchToList(Branch);

            foreach (var branch in branches)
            {
                try
                {
                    string localPath  = _branchMap[branch].Local;
                    var    itemSpec   = new ItemSpec(localPath, RecursionType.Full);
                    var    getRequest = new GetRequest(itemSpec, VersionSpec.Latest);
                    Output.WriteLine("\nUpdating {0} branch...", branch.ToString());
                    //GetStatus getStatus = _workSpace.Get(getRequest, GetOptions.NoAutoResolve);
                    GetStatus getStatus = WorkSpace.Get(getRequest, GetOptions.None);

                    //Output.WriteLine("  {0} files ({1} bytes) downloaded", getStatus.NumFiles, getStatus.NumBytes);
                    Output.WriteLine();
                }
                catch (Exception ex)
                {
                    throw new MyTfsConnectionException("Exception on Get():\n" + ex.ToString());
                }
            }
        }
예제 #12
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "GetStopwatch")] HttpRequestMessage req,
            TraceWriter log)
        {
            var configuration = new HttpConfiguration();

            req.Properties[System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey] = configuration;

            var data = await req.Content.ReadAsStringAsync();

            var requestBody = JsonConvert.DeserializeObject <UserDetailsEntity>(data);

            if (string.IsNullOrEmpty(requestBody.UserName) && string.IsNullOrEmpty(requestBody.StopWatchName))
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest,
                                          "Please pass a username and/or stopwatchname on the query string or in the request body"));
            }

            IAzureService     azureService     = new AzureService();
            IStopwatchDetails stopwatchDetails = new StopwatchDetails(azureService);
            var stopwatchStatus = new GetStatus(stopwatchDetails);
            var userDetails     = JsonConvert.SerializeObject(await stopwatchStatus.RetrieveElapsedTime(requestBody)); //If webjob is running change this to .Retrieve

            return(req.CreateResponse(HttpStatusCode.OK, userDetails));
        }
예제 #13
0
    // Method that queries several components and returns a status report
    private static String GetComponentStatusReport(GetStatus status)
    {
        // If the chain is empty, there’s is nothing to do.
        if (status == null)
        {
            return(null);
        }

        // Use this to build the status report.
        StringBuilder report = new StringBuilder();

        // Get an array where each element is a delegate from the chain.
        Delegate[] arrayOfDelegates = status.GetInvocationList();

        // Iterate over each delegate in the array.
        foreach (GetStatus getStatus in arrayOfDelegates)
        {
            try {
                // Get a component's status string, and append it to the report.
                report.AppendFormat("{0}{1}{1}", getStatus(), Environment.NewLine);
            }
            catch (InvalidOperationException e) {
                // Generate an error entry in the report for this component.
                Object component = getStatus.Target;
                report.AppendFormat(
                    "Failed to get status from {1}{2}{0}   Error: {3}{0}{0}",
                    Environment.NewLine,
                    ((component == null) ? "" : component.GetType() + "."),
                    getStatus.GetMethodInfo().Name, e.Message);
            }
        }

        // Return the consolidated report to the caller.
        return(report.ToString());
    }
예제 #14
0
        public GetStatusResponse Post(GetStatus request)
        {
            _log.StartLog(request);
            try
            {
                var status = _azureClient.GetBlob(request.Container, _jobCreator.GetStatusPath(request.Path)).GetText();
                if (String.IsNullOrWhiteSpace(status))
                {
                    throw new Exception(@"Status couldn't be retrieved for {0}\{1}".format(request.Container,
                                                                                           request.Path));
                }

                var result = (StatusCode)Enum.Parse(typeof(StatusCode), status);
                return(new GetStatusResponse {
                    Status = result
                });
            }

            catch (Exception e)
            {
                _log.Fatal("error", e);
                Errors.Add(e.Message + " " + e.StackTrace);
                return(new GetStatusResponse {
                    Errors = Errors
                });
            }
        }
예제 #15
0
        private static string GetComponentStatusReport(GetStatus status)
        {
            // if (status == null) return null;

            status();

            var report = new StringBuilder();

            //Delegate[] arrayOfDelegates = status.GetInvocationList();

            //foreach (GetStatus getStatus in arrayOfDelegates)
            //{
            //    try
            //    {
            //        report.AppendFormat("{0}{1}{1}", getStatus(), Environment.NewLine);
            //    }
            //    catch (InvalidOperationException e)
            //    {
            //        Object component = getStatus.Target;//тип объекта
            //        report.AppendFormat(
            //           "Failed to get status from {1}{2}{0}   Error: {3}{0}{0}",
            //           Environment.NewLine,
            //           ((component == null) ? string.Empty : component.GetType() + "."),
            //           getStatus.Method.Name, e.Message);
            //    }
            //}

            return(report.ToString());
        }
예제 #16
0
        public async Task <GetStatus> CheckoutWithDTESourceControlProviderAsync(DTE2 dte, ItemSpec itemSpec)
        {
            GetStatus result = ExposedObject.New(typeof(GetStatus));
            var       fails  = new List <Failure>();

            Output.WriteLine("Checkout: {0}", itemSpec.Item);
            var checkOutItem = await Task.Run(() => dte.SourceControl.CheckOutItem(itemSpec.Item));

            if (!checkOutItem)
            {
                fails.Add((Failure)ExposedObject.New(typeof(Failure), "Error for " + itemSpec.Item, SeverityType.Error));
            }
            //if (dte.SourceControl.IsItemUnderSCC(itemSpec.Item))
            //{
            //	Output.WriteLine("Checkout: {0}", itemSpec.Item);
            //	var checkOutItem = await Task.Run(() => dte.SourceControl.CheckOutItem(itemSpec.Item));
            //	if (!checkOutItem)
            //		fails.Add((Failure)ExposedObject.New(typeof(Failure), "Error for " + itemSpec.Item, SeverityType.Error));
            //}
            //else
            //{
            //	string message = $"WARNING '{itemSpec.Item}' is not under SourceControl 0 files checked out";
            //	Output.WriteLine(message);
            //	fails.Add((Failure)ExposedObject.New(typeof(Failure), message, SeverityType.Error));
            //}

            if (fails.Any())
            {
                var fieldInfo = result.GetType().GetField("m_failures", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic);
                var failures  = fieldInfo?.GetValue(result) as List <Failure>;
                failures?.AddRange(fails);
            }
            return(result);
        }
        private void Deploy()
        {
            TfsTeamProjectCollection collection;

            // if setting "Domen" in config file initialized - it means that test run on the local machine,
            // otherwise means that test run on the specialized testing machine
            if (string.IsNullOrEmpty(ConfigHelper.Instance.Domen))
            {
                collection = new TfsTeamProjectCollection(new Uri(ConfigHelper.Instance.TestCollection));
            }
            else
            {
                collection = new TfsTeamProjectCollection(
                    new Uri(ConfigHelper.Instance.TestCollection),
                    new NetworkCredential(ConfigHelper.Instance.Login, ConfigHelper.Instance.Password, ConfigHelper.Instance.Domen));
            }

            var         vcs = collection.GetService <VersionControlServer>();
            TeamProject tp  = vcs.GetTeamProject(ConfigHelper.Instance.TestCollectionProject);

            const string workspaceName = "MyWorkspace";

            Workspace[] workspaces = vcs.QueryWorkspaces(workspaceName, vcs.AuthorizedUser, Workstation.Current.Name);
            foreach (var workspace in workspaces)
            {
                foreach (var workingFolder in workspace.Folders)
                {
                    if (Directory.Exists(workingFolder.LocalItem))
                    {
                        var files = Directory.GetFiles(workingFolder.LocalItem, "*.*", SearchOption.AllDirectories);
                        foreach (var file in files)
                        {
                            File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly);
                        }

                        Directory.Delete(workingFolder.LocalItem, true);
                    }
                    workspace.DeleteMapping(workingFolder);
                }
                vcs.DeleteWorkspace(workspace.Name, vcs.AuthorizedUser);
            }

            string projectPath      = tp.ServerItem;
            string workingDirectory = ClonedRepoFolder;

            Directory.CreateDirectory(workingDirectory);

            _workspace = vcs.CreateWorkspace(workspaceName, vcs.AuthorizedUser, "Test Workspace");

            try
            {
                _workspace.Map(projectPath, workingDirectory);
                GetRequest request = new GetRequest(new ItemSpec(projectPath, RecursionType.Full), VersionSpec.Latest);
                GetStatus  status  = _workspace.Get(request, GetOptions.GetAll | GetOptions.Overwrite);
            }
            catch
            {
                throw;
            }
        }
예제 #18
0
 private Conflict[] GetConflicts(string localOrServerPath, GetStatus getStatus)
 {
     Conflict[] conflicts = getStatus.NumConflicts > 0
         ? WorkSpace.QueryConflicts(new[] { localOrServerPath }, true).ToArray()
         : new Conflict[] { };
     return(conflicts);
 }
예제 #19
0
        // TODO: Implement a percentage done feedback in the future?

        /// <summary>
        /// Query the manager to determine if a job with the unique job handle provided is done or not. The server returns
        /// a "percentage" done, if that's 100%, then the job is complete. This is mainly used for background jobs, in case
        /// the progress needs to be reported.
        /// </summary>
        /// <param name="jobHandle">
        /// A <see cref="System.String"/> containing the unique job ID to query
        /// </param>
        /// <returns>
        /// True if complete, False otherwise
        /// </returns>
        public bool checkIsDone(string jobHandle)
        {
            GetStatus statusPkt = new GetStatus(jobHandle);

            Packet result = null;

            foreach (Connection conn in managers)
            {
                Log.DebugFormat("Checking for status on {0} on {1}", jobHandle, conn);
                conn.sendPacket(statusPkt);

                result = conn.getNextPacket();

                if (result.Type == PacketType.STATUS_RES)
                {
                    StatusRes statusResult = (StatusRes)result;

                    if (statusResult.jobhandle != jobHandle)
                    {
                        Log.DebugFormat("Wrong job!!");
                    }
                    else
                    {
                        Log.DebugFormat("Hooray, this is my job!!");

                        float percentdone = 0;

                        if (statusResult.pctCompleteDenominator != 0)
                        {
                            percentdone = statusResult.pctCompleteNumerator / statusResult.pctCompleteDenominator;
                        }


                        // Check to see if this response has a known status
                        // and if it's running

                        if (statusResult.knownstatus && statusResult.running)
                        {
                            Log.DebugFormat("{0}% done!", percentdone * 100);
                        }
                        else
                        {
                            if (!statusResult.knownstatus)
                            {
                                Log.DebugFormat("Status of job not known!");
                            }

                            if (!statusResult.running)
                            {
                                Log.DebugFormat("Job not running!");
                            }
                        }

                        return(percentdone == 1);
                    }
                }
            }

            return(false);
        }
예제 #20
0
        public async Task <GetStatus> CheckoutSolutionAsync(ISolutionProjectModel projectViewModel,
                                                            IServiceSettings settings = null, VersionSpec versionSpec = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            await cancellationToken.WaitWhenPaused();

            if (settings == null)
            {
                settings = settingsService.GetMainServiceSettings();
            }
            if (versionSpec == null)
            {
                versionSpec = settingsService.Get(SettingsKeys.VersionSpecKey, VersionSpec.Latest);
            }
            if (!IsCancelled(projectViewModel, cancellationToken))
            {
                try
                {
                    using (new PauseCheckedActionScope(() => projectViewModel.CurrentOperation = Operations.Checkout, () => projectViewModel.CurrentOperation = Operations.None, cancellationToken))
                    {
                        var externalActionService = serviceProvider.Get <ExternalActionService>();
                        await externalActionService.RunExternalPreActions(projectViewModel, this, settings, cancellationToken);

                        GetStatus status = await Task.Run(() => GetLatestVersionAsync(projectViewModel, settings, versionSpec, cancellationToken), cancellationToken);

                        await externalActionService.RunExternalPostActions(projectViewModel, this, status, settings, cancellationToken);

                        return(status);
                    }
                }
                finally { statusService.IncrementStep(); }
            }
            return(null);
        }
예제 #21
0
    // Метод запрашивает состояние компонентов и возвращает информацию
    private static String GetComponentStatusReport(GetStatus status)
    {
        // Если цепочка пуста, ничего делать не нужно
        if (status == null)
        {
            return(null);
        }
        // Построение отчета о состоянии
        StringBuilder report = new StringBuilder();

        // Создание массива из делегатов цепочки
        Delegate[] arrayOfDelegates = status.GetInvocationList();
        // Циклическая обработка делегатов массива
        foreach (GetStatus getStatus in arrayOfDelegates)
        {
            try
            {
                // Получение строки состояния компонента и добавление ее в отчет
                report.AppendFormat("{0}{1}{1}", getStatus(), Environment.NewLine);
            }
            catch (InvalidOperationException e)
            {
                // В отчете генерируется запись об ошибке для этого компонента
                Object component = getStatus.Target;
                report.AppendFormat(
                    "Failed to get status from {1}{2}{0} Error: {3}{0}{0}",
                    Environment.NewLine,
                    ((component == null) ? "" : component.GetType() + "."),
                    getStatus.Method.Name,
                    e.Message);
            }
        }
        // Возвращение сводного отчета вызывающему коду
        return(report.ToString());
    }
예제 #22
0
        private void getLogic()
        {
            JObject obj = new APICaller("getCategories.php").addParam("privateKey", PrivateKey).call();

            //Console.WriteLine(obj);
            if (obj["status"].ToString() == "success")
            {
                List <Category> categories = new List <Category>();
                obj["categories"].ToList().ForEach((category) =>
                {
                    categories.Add(new Category
                    {
                        Title           = category["title"].ToString(),
                        Description     = category["description"].ToString(),
                        CreatorUsername = category["username"].ToString(),
                        CreatedDate     = DateTimeOffset.FromUnixTimeSeconds(category["createdDate"].ToObject <long>()).LocalDateTime.ToFullDate(),
                        LastUpdatedDate = DateTimeOffset.FromUnixTimeSeconds(category["lastUpdatedDate"].ToObject <long>()).LocalDateTime.ToFullDate()
                    });
                });
                GetCategoriesResult(GetStatus.Success, categories);
            }
            else
            {
                GetStatus status = GetStatus.UnknownError;
                if (!Enum.TryParse <GetStatus>(obj["message"].ToString(), out status))
                {
                    status = GetStatus.UnknownError;
                }
                GetCategoriesResult(status, null);
            }
        }
예제 #23
0
        public void Save()
        {
            if (!HasNoFileContents())
            {
                string filePath = Path.Combine(Settings.Default.ConfigurationsPath, _filename);
                if (Settings.Default.ConfigurationsPath.StartsWith("$"))
                {
                    VersionControlServer versionControlServer = Connection.GetConnection().TfsTeamProjectCollection.GetService <VersionControlServer>();

                    Workspace ws = versionControlServer.QueryWorkspaces(null, versionControlServer.AuthorizedUser, Environment.MachineName, WorkspacePermissions.CheckIn).FirstOrDefault();
                    if (ws == null) // Create Temp Workspace
                    {
                        ws = versionControlServer.CreateWorkspace(Resources.WorkspaceName, versionControlServer.AuthorizedUser, Resources.AutomaticWorkspaceToManageWorkItemFieldMappings,
                                                                  new WorkingFolder[] { new WorkingFolder(Settings.Default.ConfigurationsPath, Settings.SettingsFolderPath, WorkingFolderType.Map, RecursionType.OneLevel) });
                    }
                    GetStatus gs = ws.Get(new string[] { Settings.Default.ConfigurationsPath }, VersionSpec.Latest, RecursionType.OneLevel, GetOptions.None);
                    if (gs.NoActionNeeded)
                    {
                        WorkingFolder wf = ws.GetWorkingFolderForServerItem(filePath);
                        SaveFile(wf.LocalItem);
                        int pendingStatus = versionControlServer.ServerItemExists(wf.ServerItem, ItemType.File) ? ws.PendEdit(wf.ServerItem) : ws.PendAdd(wf.ServerItem);
                        int checkInStatus = ws.CheckIn(ws.GetPendingChanges(wf.ServerItem), Resources.SettingsFileCheckInComment);
                    }
                    else
                    {
                    }        // TODO Error Saving
                }
                else
                {
                    SaveFile(filePath);
                }
            }

            IsDirty = false;
        }
예제 #24
0
        }         // End Sub DownloadFiles

        // http://msdn.microsoft.com/en-us/library/bb130331.aspx
        public static void WorkspaceGetter()
        {
            // Connect to the team project collection and the server that hosts the version-control repository.
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(
                //new Uri("http://*****:*****@"WorkspaceName", @"UserName");
            Workspace ws = vcServer.GetWorkspace(wsInfo);

            // Update the workspace with most recent version of the files from the repository.
            GetStatus status = ws.Get();

            Console.Write("Conflicts: ");
            Console.WriteLine(status.NumConflicts);
        } // End Sub WorkspaceGetter
예제 #25
0
        public IList <Conflict> Merge(int changesetFrom, int changesetTo, MergeOptionsEx mergeOptions = MergeOptionsEx.None)
        {
            CheckPathsDefined();

            string sourcePath = _branchMap[BranchType.Source].Local;
            string targetPath = _branchMap[BranchType.Target].Local;

            var versionFrom = new ChangesetVersionSpec(changesetFrom);
            var versionTo   = new ChangesetVersionSpec(changesetTo);

            GetStatus status = WorkSpace.Merge(sourcePath, targetPath, versionFrom, versionTo, LockLevel.Unchanged,
                                               RecursionType.Full, mergeOptions);

            if (status.NoActionNeeded && status.NumOperations == 0)
            {
                Popups.ShowMessage("No changes found when merging cs " + versionFrom.ToString() + "-" + versionTo.ToString() + ".", MessageBoxImage.Asterisk);
            }

            /* Interpreting the return value:
             * http://teamfoundation.blogspot.fi/2006/11/merging-and-resolving-conflicts-using.html
             * NoActionNeeded == true && NumOperations == 0  – means that no changes in source needed to be merged, so no actual changes were pended
             * NoActionNeeded == false && NumOperations > 0 && HaveResolvableWarnings == false  – means that merges were performed,
             *                   but all conflicts were resolved automatically. Need to check in pended merge changes and that’s about it
             * NoActionNeeded == false && NumConflicts > 0  – merge was performed and there are conflicts to resolve
             * */

            return(GetConflicts(targetPath, status));
        }
예제 #26
0
        private void getLogic(string username)
        {
            JObject obj = new APICaller("getUser.php").AddParam("username", username).AddParam("privateKey", PrivateKey).Call();

            if (obj["status"].ToString() == "success")
            {
                User user = new User
                {
                    Username               = obj["user"]["username"].ToString(),
                    FirstName              = obj["user"]["firstName"].ToString(),
                    LastName               = obj["user"]["lastName"].ToString(),
                    KarmaPoints            = obj["user"]["karmaPoints"].ToObject <int>(),
                    IsLecturer             = Convert.ToBoolean(obj["user"]["lecturer"].ToObject <int>()),
                    ProfilePictureLocation = obj["user"]["profilePicture"].ToString()
                };
                GetUserResult(GetStatus.Success, user);
            }
            else
            {
                GetStatus status = GetStatus.UnknownError;
                if (!Enum.TryParse <GetStatus>(obj["message"].ToString(), out status))
                {
                    status = GetStatus.UnknownError;
                }
                GetUserResult(status, null);
            }
        }
예제 #27
0
파일: Program.cs 프로젝트: Max1545698/Prof-
        private static string GetComponentStatusReport(GetStatus status)
        {
            if (status == null)
            {
                return(null);
            }

            StringBuilder report = new StringBuilder();

            Delegate[] arrayOfDelegates = status.GetInvocationList();

            foreach (GetStatus getStatus in arrayOfDelegates)
            {
                try
                {
                    report.AppendFormat($"{getStatus()}{Environment.NewLine}{Environment.NewLine}");
                }
                catch (InvalidOperationException e)
                {
                    object component = getStatus.Target;
                    report.AppendFormat(
                        "Failed to get status from{1}{2}{0} Error{3}{0}{0}",
                        Environment.NewLine,
                        ((component == null) ? "" : component.GetType() + "."),
                        getStatus.Method.Name,
                        e.Message);
                }
            }
            return(report.ToString());
        }
예제 #28
0
        private void getLogic()
        {
            JObject obj = new APICaller("getKarmaBadges.php").AddParam("privateKey", PrivateKey).Call();

            //Console.WriteLine(obj);
            if (obj["status"].ToString() == "success")
            {
                List <KarmaBadge> karmaBadges = new List <KarmaBadge>();
                obj["badges"].ToList().ForEach((KarmaBadge) =>
                {
                    karmaBadges.Add(new KarmaBadge
                    {
                        Image      = KarmaBadge["imageLocation"].ToString(),
                        Title      = KarmaBadge["name"].ToString(),
                        StartValue = KarmaBadge["starts"].ToObject <int>(),
                    });
                });
                GetKarmaBadgeListResult(GetStatus.Success, karmaBadges);
            }
            else
            {
                GetStatus status = GetStatus.UnknownError;
                if (!Enum.TryParse <GetStatus>(obj["message"].ToString(), out status))
                {
                    status = GetStatus.UnknownError;
                }
                GetKarmaBadgeListResult(status, null);
            }
        }
예제 #29
0
파일: DelegateList.cs 프로젝트: eagles/demo
        private static String GetComponentStatusReport(GetStatus status)
        {
            // 如果委托链为空,就不进行任何操作
            if (status == null)
                return null;

            StringBuilder report = new StringBuilder();

            Delegate[] arrayOfDelegates = status.GetInvocationList();

            // 遍历数组中的每一个委托
            foreach (GetStatus getStatus in arrayOfDelegates)
            {
                try
                {
                    report.AppendFormat("{0} {1} {1}", getStatus(), Environment.NewLine);
                }
                catch(InvalidOperationException e)
                {
                    Object component = getStatus.Target;
                    report.AppendFormat("Failed to get status from {1} {2} {0}  Error: {3} {0} {0}",
                        Environment.NewLine,
                        ((component == null) ? "" : component.GetType() + "."),
                        getStatus.Method.Name,
                        e.Message);
                }
            }

            return report.ToString();
        }
예제 #30
0
        public void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel)
        {
            if (null != Override)
            {
                if (Override(this, server, context))
                {
                    return;
                }
            }

            var error = GetError?.Invoke(this, server, context) ?? Error;

            if (null != error)
            {
                throw error;
            }

            var status  = GetStatus?.Invoke(this, server, context) ?? Status;
            var mime    = GetMime?.Invoke(this, server, context) ?? Mime;
            var content = GetContent?.Invoke(this, server, context) ?? Content;
            var timeout = GetTimeout?.Invoke(this, server, context) ?? Timeout;

            if (0 < timeout)
            {
                Thread.Sleep(timeout);
            }

            context.Finish(content, mime, status);
        }
        public object Any(GetStatus request)
        {
            var result = MapReduceUtils.getStatuses();

            return(new GetStatusResponse {
                inactiveWorkers = result.Item2, statuses = result.Item1
            });
        }
예제 #32
0
        public string Factory(ICondition condition)
        {
            SuperType superType = new SuperType();
            superType._condition = condition;
            GetStatus getStatus=new GetStatus();
            superType.Accept(getStatus);

            return getStatus.status;
        }
        public object Get(GetStatus request)
        {
            return new
            {
                Address = manager.Connection.Address.ToString(),
                manager.Connection.Name,
                manager.Connection.Type,
                manager.Network.IsConnected,
                manager.Network.Devices.Count
            };

        }
예제 #34
0
파일: DelegateList.cs 프로젝트: eagles/demo
        public static void Main(String[] args)
        {
            // 声明一个委托链
            GetStatus getStatus = null;

            // 构造3个组件,将它们的状态方法添加到委托链中
            getStatus += new GetStatus(new Light().SwitchPosition);
            getStatus += new GetStatus(new Fan().Speed);
            getStatus += new GetStatus(new Speaker().Volume);

            // 显示整理好的状态报告,反映这3个组件的状态
            Console.WriteLine(GetComponentStatusReport(getStatus));
        }
예제 #35
0
        private void testDelegateChain()
        {
            // Объявление пустой цепочки делегатов
            GetStatus getStatus = null;
            // Создание трех компонентов и добавление в цепочку
            // методов проверки их состояния
            getStatus += new GetStatus(new Light().SwitchPosition);
            getStatus += new GetStatus(new Fan().Speed);

            getStatus += new GetStatus(new Speaker().Volume);
            // Сводный отчет о состоянии трех компонентов
            Console.WriteLine(GetComponentStatusReport(getStatus));
        }
예제 #36
0
        public GetStatusResponse Post(GetStatus request)
        {
            _log.StartLog(request);
            try
            {
                var status = _azureClient.GetBlob(request.Container, _jobCreator.GetStatusPath(request.Path)).GetText();
                if (String.IsNullOrWhiteSpace(status))
                {
                    throw new Exception(@"Status couldn't be retrieved for {0}\{1}".format(request.Container,
                                                                                           request.Path));
                }

                var result = (StatusCode) Enum.Parse(typeof (StatusCode), status);
                return new GetStatusResponse {Status = result};
            }

            catch (Exception e)
            {
                _log.Fatal("error", e);
                Errors.Add(e.Message + " " + e.StackTrace);
                return new GetStatusResponse { Errors = Errors };
            }
        }
예제 #37
0
   public static void Go() {
      // Declare an empty delegate chain.
      GetStatus getStatus = null;

      // Construct the three components, and add their status methods 
      // to the delegate chain.
      getStatus += new GetStatus(new Light().SwitchPosition);
      getStatus += new GetStatus(new Fan().Speed);
      getStatus += new GetStatus(new Speaker().Volume);

      // Show consolidated status report reflecting 
      // the condition of the three components.
      Console.WriteLine(GetComponentStatusReport(getStatus));
   }
예제 #38
0
 // Метод запрашивает состояние компонентов и возвращает информацию
 private static String GetComponentStatusReport(GetStatus status)
 {
     // Если цепочка пуста, ничего делать не нужно
     if (status == null) return null;
     // Построение отчета о состоянии
     StringBuilder report = new StringBuilder();
     // Создание массива из делегатов цепочки
     Delegate[] arrayOfDelegates = status.GetInvocationList();
     // Циклическая обработка делегатов массива
     foreach (GetStatus getStatus in arrayOfDelegates)
     {
         try
         {
             // Получение строки состояния компонента и добавление ее в отчет
             report.AppendFormat("{0}{1}{1}", getStatus(), Environment.NewLine);
         }
         catch (InvalidOperationException e)
         {
             // В отчете генерируется запись об ошибке для этого компонента
             Object component = getStatus.Target;
             report.AppendFormat(
             "Failed to get status from {1}{2}{0} Error: {3}{0}{0}",
             Environment.NewLine,
             ((component == null) ? "" : component.GetType() + "."),
             getStatus.Method.Name,
             e.Message);
         }
     }
     // Возвращение сводного отчета вызывающему коду
     return report.ToString();
 }
예제 #39
0
        private StatusResult KeepGettingStatus(string container, string blob, TimeSpan timeToUpload, CancellationTokenSource tokenSource)
        {
            try
            {
                StatusCode c = StatusCode.WaitingToRun;
                 SendMessage(new Message
                        {
                            Contents = @"We're waiting for signing to run on {0}\{1}".format(container, blob)
                        });
                var getStatusMessage = new GetStatus {Container = container, Path = blob};
                while (c == StatusCode.WaitingToRun)
                {
                    if (tokenSource != null && tokenSource.IsCancellationRequested)
                    {
                        return null;
                    }
                    Thread.Sleep(3000);
                    var r = Client.Post(getStatusMessage);
                    ThrowErrors(r.Errors);
                    c = r.Status;
                }

                SendMessage(new Message
                {
                    Contents = @"Signing has started for {0}\{1}".format(container, blob)
                });

                var startSigningTime = DateTime.Now;

                // we wait three times as long as timeToUpload
                while (c == StatusCode.Running)
                {
                    if (tokenSource != null && tokenSource.IsCancellationRequested)
                    {
                        return null;
                    }

                    if ((DateTime.Now - startSigningTime) > new TimeSpan(timeToUpload.Ticks*3))
                    {
                        return new StatusResult {TimedOut = true};
                    }
                    var r = Client.Post(getStatusMessage);
                    ThrowErrors(r.Errors);
                    c = r.Status;

                }

                return new StatusResult {Status = c};

            }
            catch (Exception e)
            {
                return new StatusResult {Exception = e};
            }
        }
예제 #40
0
   // Method that queries several components and returns a status report
   private static String GetComponentStatusReport(GetStatus status) {

      // If the chain is empty, there’s is nothing to do.
      if (status == null) return null;

      // Use this to build the status report.
      StringBuilder report = new StringBuilder();

      // Get an array where each element is a delegate from the chain.
      Delegate[] arrayOfDelegates = status.GetInvocationList();

      // Iterate over each delegate in the array. 
      foreach (GetStatus getStatus in arrayOfDelegates) {

         try {
            // Get a component's status string, and append it to the report.
            report.AppendFormat("{0}{1}{1}", getStatus(), Environment.NewLine);
         }
         catch (InvalidOperationException e) {
            // Generate an error entry in the report for this component.
            Object component = getStatus.Target;
            report.AppendFormat(
               "Failed to get status from {1}{2}{0}   Error: {3}{0}{0}",
               Environment.NewLine,
               ((component == null) ? "" : component.GetType() + "."),
               getStatus.GetMethodInfo().Name, e.Message);
         }
      }

      // Return the consolidated report to the caller.
      return report.ToString();
   }