Пример #1
0
 /// <summary>
 /// Overrides Package.OnSaveOptions()
 /// Invoked by the Package class when there are options to be saved to the solution file.
 /// </summary>
 /// <param name="key">The name of the option key to save.</param>
 /// <param name="stream">The stream to save the option data to.</param>
 protected override void OnSaveOptions(string key, Stream stream)
 {
     try
     {
         if (0 == string.Compare(key, CommandLineOptionKey))
         {
             Logging.WriteLine("Saving CommandLineEditor options");
             CommandLineEditor.SaveOptions(stream);
         }
         else if (0 == string.Compare(key, BatchBuildSetsOptionKey))
         {
             Logging.WriteLine("Saving BatchBuilder options");
             BatchBuilder.SaveOptions(stream);
         }
     }
     catch (Exception Ex)
     {
         // Couldn't save options
         Exception AppEx = new ApplicationException("OnSaveOptions() failed with key " + key, Ex);
         Logging.WriteLine(AppEx.ToString());
         throw AppEx;
     }
 }
Пример #2
0
        /// <summary>
        /// Helper to check the properties of a project and determine whether it can be run in VS.
        /// Projects that return true can be run in the debugger by pressing the usual Start Debugging (F5) command.
        /// </summary>
        public static bool IsProjectSuitable(Project Project)
        {
            try
            {
                Logging.WriteLine("IsProjectExecutable: Attempting to determine if project " + Project.Name + " is executable");

                var ConfigManager = Project.ConfigurationManager;
                if (ConfigManager == null)
                {
                    return(false);
                }

                var ActiveProjectConfig = Project.ConfigurationManager.ActiveConfiguration;
                if (ActiveProjectConfig != null)
                {
                    Logging.WriteLine(
                        "IsProjectExecutable: ActiveProjectConfig=\"" + ActiveProjectConfig.ConfigurationName + "|" + ActiveProjectConfig.PlatformName + "\"");
                }
                else
                {
                    Logging.WriteLine("IsProjectExecutable: Warning - ActiveProjectConfig is null!");
                }

                bool IsSuitable = false;

                if (Project.Kind.Equals(GuidList.VCSharpProjectKindGuidString, StringComparison.OrdinalIgnoreCase))
                {
                    // C# project

                    // Chris.Wood
                    //Property StartActionProp = GetProjectConfigProperty(Project, null, "StartAction");
                    //if (StartActionProp != null)
                    //{
                    //	prjStartAction StartAction = (prjStartAction)StartActionProp.Value;
                    //	if (StartAction == prjStartAction.prjStartActionProject)
                    //	{
                    //		// Project starts the project's output file when run
                    //		Property OutputTypeProp = GetProjectProperty(Project, "OutputType");
                    //		if (OutputTypeProp != null)
                    //		{
                    //			prjOutputType OutputType = (prjOutputType)OutputTypeProp.Value;
                    //			if (OutputType == prjOutputType.prjOutputTypeWinExe ||
                    //				OutputType == prjOutputType.prjOutputTypeExe)
                    //			{
                    //				IsSuitable = true;
                    //			}
                    //		}
                    //	}
                    //	else if (StartAction == prjStartAction.prjStartActionProgram ||
                    //			 StartAction == prjStartAction.prjStartActionURL)
                    //	{
                    //		// Project starts an external program or a URL when run - assume it has been set deliberately to something executable
                    //		IsSuitable = true;
                    //	}
                    //}

                    IsSuitable = true;
                }
                else if (Project.Kind.Equals(GuidList.VCProjectKindGuidString, StringComparison.OrdinalIgnoreCase))
                {
                    // C++ project

                    SolutionConfiguration SolutionConfig      = UnrealVSPackage.Instance.DTE.Solution.SolutionBuild.ActiveConfiguration;
                    SolutionContext       ProjectSolutionCtxt = SolutionConfig.SolutionContexts.Item(Project.UniqueName);

                    // Get the correct config object from the VCProject
                    string ActiveConfigName = string.Format(
                        "{0}|{1}",
                        ProjectSolutionCtxt.ConfigurationName,
                        ProjectSolutionCtxt.PlatformName);

                    // Get the VS version-specific VC project object.
                    VCProject VCProject = new VCProject(Project, ActiveConfigName);

                    if (VCProject != null)
                    {
                        // Sometimes the configurations is null.
                        if (VCProject.Configurations != null)
                        {
                            var VCConfigMatch = VCProject.Configurations.FirstOrDefault(VCConfig => VCConfig.Name == ActiveConfigName);

                            if (VCConfigMatch != null)
                            {
                                if (VCConfigMatch.DebugAttach)
                                {
                                    // Project attaches to a running process
                                    IsSuitable = true;
                                }
                                else
                                {
                                    // Project runs its own process

                                    if (VCConfigMatch.DebugFlavor == DebuggerFlavor.Remote)
                                    {
                                        // Project debugs remotely
                                        if (VCConfigMatch.DebugRemoteCommand.Length != 0)
                                        {
                                            // An remote program is specified to run
                                            IsSuitable = true;
                                        }
                                    }
                                    else
                                    {
                                        // Local debugger

                                        if (VCConfigMatch.DebugCommand.Length != 0 && VCConfigMatch.DebugCommand != "$(TargetPath)")
                                        {
                                            // An external program is specified to run
                                            IsSuitable = true;
                                        }
                                        else
                                        {
                                            // No command so the project runs the target file

                                            if (VCConfigMatch.ConfigType == ConfigType.Application)
                                            {
                                                IsSuitable = true;
                                            }
                                            else if (VCConfigMatch.ConfigType == ConfigType.Generic)
                                            {
                                                // Makefile

                                                if (VCConfigMatch.NMakeToolOutput.Length != 0)
                                                {
                                                    string Ext = Path.GetExtension(VCConfigMatch.NMakeToolOutput);
                                                    if (!IsLibraryFileExtension(Ext))
                                                    {
                                                        IsSuitable = true;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    // @todo: support other project types
                    Logging.WriteLine("IsProjectExecutable: Unrecognised 'Kind' in project " + Project.Name + " guid=" + Project.Kind);
                }

                return(IsSuitable);
            }
            catch (Exception ex)
            {
                Exception AppEx = new ApplicationException("IsProjectExecutable() failed", ex);
                Logging.WriteLine(AppEx.ToString());
                throw AppEx;
            }
        }
Пример #3
0
    /// <summary>
    /// Save comment
    /// </summary>
    /// <param name="member">Comment to save</param>
    public void SaveComment(Comment comment)
    {
        if (comment.IsValid)
            {
                if (comment.CommentId == 0)
                {
                    CommentDAL.InsertComment(comment);
                }
                else
                {
                    CommentDAL.UpdateComment(comment);
                }
            }
            else
            {
                ApplicationException ex = new ApplicationException(comment.Error);
                ex.Data.Add("Comment", comment);

                Service.WriteToLog(ex.ToString(), (int)Membership.GetUser().ProviderUserKey);
                throw ex;
            }
    }
Пример #4
0
        static void Main(string[] args)
        {
            Console.WriteLine("BrightLocal Demo");

            List <string> localDirectories = new List <string>();

            localDirectories.Add("google");
            localDirectories.Add("yahoo");
            //localDirectories.Add("facebook");


            api      Api          = new api("api key", "secret");
            batchApi batchRequest = new batchApi(Api);

            // Create a new batch
            int batchId = batchRequest.Create();

            Console.WriteLine($"Batch created: id {batchId}");

            var model = new {
                BusinessNames = "Foo",
                City          = "New York",
                PostalCode    = "90210",
                Telephone     = "2140000000"
            };

            // Add jobs to batch
            foreach (var item in localDirectories)
            {
                var parameters = new api.Parameters();
                parameters.Add("batch-id", batchId);
                parameters.Add("business-names", model.BusinessNames);
                parameters.Add("city", model.City);
                parameters.Add("postcode", model.PostalCode);
                parameters.Add("local-directory", item);
                parameters.Add("country", "USA");

                var jobId = Api.Post("/v4/ld/fetch-reviews-by-business-data", parameters);

                Console.WriteLine($"Job created with id {jobId}");

                // NOTE: ResponseStatus.Completed doesn't exist
                if (jobId.ResponseStatus == jobId.ResponseStatus) //ResponseStatus.Completed)
                {
                    dynamic job = JsonConvert.DeserializeObject(jobId.Content);
                    if (!job.success)
                    {
                        string message        = "Error adding job";
                        var    batchException = new ApplicationException(message + job.errors, job.ErrorException);
                        throw batchException;
                    }
                }
                else
                {
                    throw new ApplicationException(jobId.ErrorMessage);
                }
            }
            // Commit the batch, resturns true or false
            bool commit = batchRequest.Commit(batchId);

            // Poll for results. In a real world example you should do this in a backgroud process, such as HangFire,  or use the Task Parallel Library to create a BackGroundWorker Task.
            // It is bad practice to use Thread.Sleep(). This is only for the example and will actually freeze the UI until the while loop is finished.

            var results        = batchRequest.GetResults(batchId);
            var resultsContent = results.Content;

            LogResults(resultsContent);
            dynamic reviewResults = JsonConvert.DeserializeObject(resultsContent);

            if (reviewResults.success)
            {
                while (reviewResults.status != "Stopped" || reviewResults.status != "Finished")
                {
                    Thread.Sleep(10000);
                    results        = batchRequest.GetResults(batchId);
                    resultsContent = results.Content;
                    LogResults(resultsContent);
                    reviewResults = JsonConvert.DeserializeObject(resultsContent);
                }
                Console.WriteLine($"Results: {reviewResults.ToString()}");
                //return reviewResults;
            }
            else
            {
                const string message        = "Error Retrieving batch results ";
                var          batchException = new ApplicationException(message + reviewResults.errors, results.ErrorException);
                Console.WriteLine("Error: " + batchException.ToString());
                throw batchException;
            }

            Console.WriteLine("Done!");
        }
Пример #5
0
        ///--------------------------------------------------------------------------------
        /// <summary>This method loads a specification source with information from a
        /// SQL database.</summary>
        ///--------------------------------------------------------------------------------
        public void LoadSpecificationSource()
        {
            try
            {
                switch (DatabaseTypeCode)
                {
                case (int)BLL.Config.DatabaseTypeCode.SqlServer:
                    Database sqlDatabase = null;

                    Server sqlServer;
                    if (SourceDbServerName.StartsWith("(localdb)", StringComparison.OrdinalIgnoreCase))
                    {
                        var conn = new ServerConnection(new SqlConnection(String.Format("server={0};integrated security=true", SourceDbServerName)));
                        sqlServer = new Server(conn);
                        sqlServer.SetDefaultInitFields(true);
                    }
                    else
                    {
                        sqlServer = new Server(SourceDbServerName);
                        sqlServer.SetDefaultInitFields(true);
                        if (!String.IsNullOrEmpty(PasswordClearText) && !String.IsNullOrEmpty(UserName))
                        {
                            // sql server authentication
                            sqlServer.ConnectionContext.LoginSecure = false;
                            sqlServer.ConnectionContext.Login       = UserName;
                            sqlServer.ConnectionContext.Password    = PasswordClearText;
                        }
                        else
                        {
                            // windows authentication
                            sqlServer.ConnectionContext.LoginSecure = true;
                        }
                    }
                    sqlServer.ConnectionContext.Connect();
                    if (sqlServer.ConnectionContext.IsOpen == false)
                    {
                        SpecDatabase = null;
                        ApplicationException ex = new ApplicationException(String.Format(DisplayValues.Exception_SourceDbServerConnection, SourceDbServerName));
                        Solution.ShowIssue(ex.Message + "\r\n" + ex.StackTrace);
                        throw ex;
                    }

                    if (SourceDbName.Contains("\\"))
                    {
                        var dbName = Path.GetFileNameWithoutExtension(SourceDbName);
                        sqlDatabase = sqlServer.Databases[dbName];

                        if (sqlDatabase == null)
                        {
                            // attach the database instead of opening the database by name
                            var stringColl = new StringCollection();
                            stringColl.Add(SourceDbName);
                            stringColl.Add(Path.Combine(Path.GetDirectoryName(SourceDbName), Path.GetFileNameWithoutExtension(SourceDbName) + "_log.ldf"));

                            sqlServer.AttachDatabase(dbName, stringColl);

                            sqlDatabase = sqlServer.Databases[SourceDbName];
                        }
                    }
                    else
                    {
                        sqlDatabase = sqlServer.Databases[SourceDbName];
                    }

                    if (sqlDatabase == null)
                    {
                        SpecDatabase = null;
                        ApplicationException ex = new ApplicationException(String.Format(DisplayValues.Exception_SourceDbNotFound, SourceDbName, SourceDbServerName));
                        Solution.ShowIssue(ex.Message + "\r\n" + ex.StackTrace);
                        throw ex;
                    }
                    else
                    {
                        // load the database information
                        SpecDatabase = new SqlDatabase();
                        SpecDatabase.SqlDatabaseID = Guid.NewGuid();
                        SpecDatabase.Solution      = Solution;
                        SpecDatabase.LoadSqlServerDatabase(sqlDatabase);
                    }
                    break;

                case (int)BLL.Config.DatabaseTypeCode.MySQL:
                    string myConnectionString = "SERVER=" + SourceDbServerName + ";" +
                                                "DATABASE=" + SourceDbName + ";" +
                                                "UID=" + UserName + ";" +
                                                "PASSWORD="******";";
                    MySqlConnection connection = new MySqlConnection(myConnectionString);
                    using (connection)
                    {
                        try
                        {
                            connection.Open();
                        }
                        catch
                        {
                            SpecDatabase = null;
                            ApplicationException ex = new ApplicationException(String.Format(DisplayValues.Exception_MySQLConnection, SourceDbName, SourceDbServerName));
                            Solution.ShowIssue(ex.Message + "\r\n" + ex.StackTrace);
                            throw;
                        }
                        // load the database information
                        SpecDatabase = new SqlDatabase();
                        SpecDatabase.SqlDatabaseID = Guid.NewGuid();
                        SpecDatabase.Solution      = Solution;
                        SpecDatabase.LoadMySQLDatabase(connection);
                        connection.Close();
                    }
                    break;

                default:
                    throw new NotImplementedException("DatabaseTypeCode value " + DatabaseTypeCode + " not implemented!");
                }
            }
            catch (ApplicationAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                bool reThrow = BusinessConfiguration.HandleException(ex);
                Solution.ShowIssue(ex.ToString());
            }
        }
Пример #6
0
        private void RestartReceiveLoop()
        {
            if (_receiveCancellation != null)
            {
                _receiveCancellation.Cancel();
                _receiveCancellation = new CancellationTokenSource();
            }
            var cancellationToken = _receiveCancellation.Token;

            Task.Run(async() => {
                while (!cancellationToken.IsCancellationRequested)
                {
                    using (var memStream = new MemoryStream()) {
                        byte[] data = new byte[4096];
                        ArraySegment <byte> buffer = new ArraySegment <byte>(data);
                        WebSocketReceiveResult result;
                        do
                        {
                            result = await _websocket.ReceiveAsync(buffer, cancellationToken);
                            if (result.Count > 0)
                            {
                                memStream.Write(buffer.Array, buffer.Offset, result.Count);
                            }
                            else
                            {
                                break;
                            }
                        } while (!result.EndOfMessage);
                        memStream.Seek(0, SeekOrigin.Begin);

                        // Parse json here.
                        string json = string.Empty;
                        using (var sr = new StreamReader(memStream)) {
                            json = sr.ReadToEnd();
                        }

                        Console.WriteLine("Incoming JSON Response:\r\n==========\r\n{0}\r\n==========\r\n", json);

                        JObject resultJson = JObject.Parse(json);
                        var id             = resultJson["id"].Value <int>();
                        if (id == 0 || !_pendingRequests.ContainsKey(id))
                        {
                            // Ignore!
                        }
                        else
                        {
                            var tcs = _pendingRequests[id];
                            var t   = tcs.GetType();
                            Type[] typeParameters = t.GetGenericArguments();

                            Console.WriteLine("Type: {0}<{1}>", t.Name, typeParameters[0].Name);

                            if (!resultJson["error"].IsNullOrEmpty())
                            {
                                Console.WriteLine("Setting exception...");
                                var exception = new ApplicationException(resultJson["error"].Value <string>());
                                Console.WriteLine("Exception is {0}", exception.ToString());
                                try {
                                    MethodInfo methodInfo = t.GetMethod("SetException", new[] { typeof(Exception) });
                                    methodInfo.Invoke(tcs, new object[] { exception });
                                } catch (Exception ex) {
                                    Console.WriteLine("Exception while setting exception: {0}", ex.ToString());
                                }
                                Console.WriteLine("Done!");
                            }
                            else
                            {
                                try {
                                    MethodInfo methodInfo = t.GetMethod("SetResult");
                                    var obj = JsonConvert.DeserializeObject(resultJson["result"].ToString(), typeParameters[0]);
                                    methodInfo.Invoke(tcs, new object[] { obj });
                                } catch (Exception ex) {
                                    MethodInfo methodInfo = t.GetMethod("SetException", new[] { typeof(Exception) });
                                    methodInfo.Invoke(tcs, new object[] { ex });
                                }
                            }
                        }
                    }
                }
            }, cancellationToken);
        }