/// <summary>
 /// Constructor used to inject dependencies
 /// </summary>
 /// <param name="fileStreamFactory">The file stream factory used to open files</param>
 public CountProjectsByProjectTypeProvider(IFileStreamFactory fileStreamFactory)
 {
     _fileStreamFactory = fileStreamFactory;
 }
Пример #2
0
        public Query CreateAndExecuteQuery(string queryText, ConnectionInfo connectionInfo, IFileStreamFactory fileStreamFactory)
        {
            Query query = new Query(queryText, connectionInfo, new QueryExecutionSettings(), fileStreamFactory);

            query.Execute();
            query.ExecutionTask.Wait();
            return(query);
        }
Пример #3
0
        /// <summary>
        /// Saves the contents of this result set to a file using the IFileStreamFactory provided
        /// </summary>
        /// <param name="saveParams">Parameters for saving the results to a file</param>
        /// <param name="fileFactory">
        /// Factory for creating a stream reader/writer combo for writing results to disk
        /// </param>
        /// <param name="successHandler">Handler for a successful write of all rows</param>
        /// <param name="failureHandler">Handler for unsuccessful write of all rows</param>
        public void SaveAs(SaveResultsRequestParams saveParams, IFileStreamFactory fileFactory,
                           SaveAsAsyncEventHandler successHandler, SaveAsFailureAsyncEventHandler failureHandler)
        {
            // Sanity check the save params and file factory
            Validate.IsNotNull(nameof(saveParams), saveParams);
            Validate.IsNotNull(nameof(fileFactory), fileFactory);

            // Make sure the resultset has finished being read
            if (!hasCompletedRead)
            {
                throw new InvalidOperationException(SR.QueryServiceSaveAsResultSetNotComplete);
            }

            // Make sure there isn't a task for this file already
            Task existingTask;

            if (SaveTasks.TryGetValue(saveParams.FilePath, out existingTask))
            {
                if (existingTask.IsCompleted)
                {
                    // The task has completed, so let's attempt to remove it
                    if (!SaveTasks.TryRemove(saveParams.FilePath, out existingTask))
                    {
                        throw new InvalidOperationException(SR.QueryServiceSaveAsMiscStartingError);
                    }
                }
                else
                {
                    // The task hasn't completed, so we shouldn't continue
                    throw new InvalidOperationException(SR.QueryServiceSaveAsInProgress);
                }
            }

            // Create the new task
            Task saveAsTask = new Task(async() =>
            {
                try
                {
                    // Set row counts depending on whether save request is for entire set or a subset
                    long rowEndIndex  = RowCount;
                    int rowStartIndex = 0;
                    if (saveParams.IsSaveSelection)
                    {
                        // ReSharper disable PossibleInvalidOperationException  IsSaveSelection verifies these values exist
                        rowEndIndex   = saveParams.RowEndIndex.Value + 1;
                        rowStartIndex = saveParams.RowStartIndex.Value;
                        // ReSharper restore PossibleInvalidOperationException
                    }

                    using (var fileReader = fileFactory.GetReader(outputFileName))
                        using (var fileWriter = fileFactory.GetWriter(saveParams.FilePath))
                        {
                            // Iterate over the rows that are in the selected row set
                            for (long i = rowStartIndex; i < rowEndIndex; ++i)
                            {
                                var row = fileReader.ReadRow(fileOffsets[i], i, Columns);
                                fileWriter.WriteRow(row, Columns);
                            }
                            if (successHandler != null)
                            {
                                await successHandler(saveParams);
                            }
                        }
                }
                catch (Exception e)
                {
                    fileFactory.DisposeFile(saveParams.FilePath);
                    if (failureHandler != null)
                    {
                        await failureHandler(saveParams, e.Message);
                    }
                }
            });

            // Add exception handling to the save task
            Task taskWithHandling = saveAsTask.ContinueWithOnFaulted(async t =>
            {
                if (failureHandler != null)
                {
                    await failureHandler(saveParams, t.Exception.Message);
                }
            });

            // If saving the task fails, return a failure
            if (!SaveTasks.TryAdd(saveParams.FilePath, taskWithHandling))
            {
                throw new InvalidOperationException(SR.QueryServiceSaveAsMiscStartingError);
            }

            // Task was saved, so start up the task
            saveAsTask.Start();
        }
 /// <summary>
 /// Constructor for production code.
 /// </summary>
 public InspectCodeProvider()
 {
     _fileStreamFactory = new FileStreamFactory();
 }
 /// <summary>
 /// Constructor used to inject dependencies
 /// </summary>
 /// <param name="fileStreamFactory">The file stream factory used to open files</param>
 public CountLOCProvider(IFileStreamFactory fileStreamFactory)
 {
     _fileStreamFactory = fileStreamFactory;
 }
Пример #6
0
 /// <summary>
 /// Constructor used to inject dependencies
 /// </summary>
 /// <param name="streamFactory">the file stream factory</param>
 public CodeMetrics(IFileStreamFactory streamFactory)
 {
     _streamFactory = streamFactory;
 }
Пример #7
0
 internal Batch(string batchText, SelectionData selection, int ordinalId,
                IFileStreamFactory outputFileFactory, SqlCmdCommand sqlCmdCommand, int executionCount = 1, bool getFullColumnSchema = false) : this(batchText, selection, ordinalId,
                                                                                                                                                    outputFileFactory, executionCount, getFullColumnSchema)
 {
     this.SqlCmdCommand = sqlCmdCommand;
 }
Пример #8
0
 public CompoundFile(string path, CompoundFileOptions options, IFileStreamFactory fileStreamFactory)
 {
     Debug.Assert(UINT_ZERO.Length == sizeof(uint));
     FileOptions foptions;
     if (options.UseWriteCache)
         foptions = FileOptions.RandomAccess;
     else
         foptions = FileOptions.RandomAccess | FileOptions.WriteThrough;
     _options = options;
     bool fileExists = File.Exists(path);
     lock (_sync)
     {
         _stream = fileStreamFactory.Create(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, options.BufferSize, foptions);
         if (!TryLoadFileHeader())
         {
             if (fileExists)
             {
                 if (_header.Version < FILE_VERSION) throw new InvalidDataException("File version is not supported");
                 if (!new System.Text.ASCIIEncoding().GetString(_header.Magic).Equals(MAGIC_STRING)) throw new InvalidDataException("Corrupt file");
                 throw new Exception("Failed to open file. Possible corrupt file");
             }
             InitializeFile();
         }            
     }
 }
Пример #9
0
 public ImageService(IHostingEnvironment environment, IFileSystemProvider fileProvider, IFileStreamFactory fileStreamFactory)
 {
     _environment       = environment;
     _fileProvider      = fileProvider;
     _fileStreamFactory = fileStreamFactory;
 }
Пример #10
0
        /// <summary>
        /// Constructor for a query
        /// </summary>
        /// <param name="queryText">The text of the query to execute</param>
        /// <param name="connection">The information of the connection to use to execute the query</param>
        /// <param name="settings">Settings for how to execute the query, from the user</param>
        /// <param name="outputFactory">Factory for creating output files</param>
        public Query(string queryText, ConnectionInfo connection, QueryExecutionSettings settings, IFileStreamFactory outputFactory, bool getFullColumnSchema = false)
        {
            // Sanity check for input
            Validate.IsNotNull(nameof(queryText), queryText);
            Validate.IsNotNull(nameof(connection), connection);
            Validate.IsNotNull(nameof(settings), settings);
            Validate.IsNotNull(nameof(outputFactory), outputFactory);

            // Initialize the internal state
            QueryText          = queryText;
            editorConnection   = connection;
            cancellationSource = new CancellationTokenSource();

            // Process the query into batches
            BatchParserWrapper     parser       = new BatchParserWrapper();
            List <BatchDefinition> parserResult = parser.GetBatches(queryText);

            var batchSelection = parserResult
                                 .Select((batchDefinition, index) =>
                                         new Batch(batchDefinition.BatchText,
                                                   new SelectionData(
                                                       batchDefinition.StartLine - 1,
                                                       batchDefinition.StartColumn - 1,
                                                       batchDefinition.EndLine - 1,
                                                       batchDefinition.EndColumn - 1),
                                                   index, outputFactory,
                                                   batchDefinition.BatchExecutionCount,
                                                   getFullColumnSchema));

            Batches = batchSelection.ToArray();

            // Create our batch lists
            BeforeBatches = new List <Batch>();
            AfterBatches  = new List <Batch>();

            if (DoesSupportExecutionPlan(connection))
            {
                // Checking settings for execution plan options
                if (settings.ExecutionPlanOptions.IncludeEstimatedExecutionPlanXml)
                {
                    // Enable set showplan xml
                    AddBatch(string.Format(SetShowPlanXml, On), BeforeBatches, outputFactory);
                    AddBatch(string.Format(SetShowPlanXml, Off), AfterBatches, outputFactory);
                }
                else if (settings.ExecutionPlanOptions.IncludeActualExecutionPlanXml)
                {
                    AddBatch(string.Format(SetStatisticsXml, On), BeforeBatches, outputFactory);
                    AddBatch(string.Format(SetStatisticsXml, Off), AfterBatches, outputFactory);
                }
            }
        }
Пример #11
0
 ResourceLoadProvider(IFile fileWrapper, IFileStreamFactory fileStreamFactory, IStreamReaderFactory streamReaderFactory)
 {
     _dev2FileWrapper     = fileWrapper;
     _fileStreamFactory   = fileStreamFactory;
     _streamReaderFactory = streamReaderFactory;
 }
Пример #12
0
        public ResourceLoadProvider(ConcurrentDictionary <Guid, List <IResource> > workspaceResources, IServerVersionRepository serverVersionRepository, IEnumerable <DynamicService> managementServices = null, IFile dev2FileWrapper = null, IFileStreamFactory fileStreamFactory = null, IStreamReaderFactory streamReaderFactory = null)
            : this(dev2FileWrapper ?? new FileWrapper(), fileStreamFactory ?? new FileStreamFactory(), streamReaderFactory ?? new StreamReaderFactory())
        {
            try
            {
                _perfCounter = CustomContainer.Get <IWarewolfPerformanceCounterLocater>().GetCounter("Count of requests for workflows which don't exist");
            }
            catch (Exception e)
            {
                Dev2Logger.Warn("Error getting perf counters. " + e.Message, "Warewolf Warn");
            }
            if (managementServices != null)
            {
                foreach (var service in managementServices)
                {
                    var resource = new ManagementServiceResource(service);
                    ManagementServices.TryAdd(resource.ResourceID, resource);
                }
            }
            _workspaceResources      = workspaceResources;
            _serverVersionRepository = serverVersionRepository;
            LoadFrequentlyUsedServices();

            _typeCache = new TypeCache();
            LoadResourceTypeCache();
        }
 /// <summary>
 /// Constructor used in tests for mocking IFileStreamFactory
 /// </summary>
 /// <param name="fileStreamFactory"></param>
 public InspectCodeProvider(IFileStreamFactory fileStreamFactory)
 {
     _fileStreamFactory = fileStreamFactory;
 }
Пример #14
0
        /// <summary>
        /// Constructor for a query
        /// </summary>
        /// <param name="queryText">The text of the query to execute</param>
        /// <param name="connection">The information of the connection to use to execute the query</param>
        /// <param name="settings">Settings for how to execute the query, from the user</param>
        /// <param name="outputFactory">Factory for creating output files</param>
        public Query(string queryText, ConnectionInfo connection, QueryExecutionSettings settings, IFileStreamFactory outputFactory)
        {
            // Sanity check for input
            Validate.IsNotNullOrEmptyString(nameof(queryText), queryText);
            Validate.IsNotNull(nameof(connection), connection);
            Validate.IsNotNull(nameof(settings), settings);
            Validate.IsNotNull(nameof(outputFactory), outputFactory);

            // Initialize the internal state
            QueryText          = queryText;
            editorConnection   = connection;
            cancellationSource = new CancellationTokenSource();

            // Process the query into batches
            ParseResult parseResult = Parser.Parse(queryText, new ParseOptions
            {
                BatchSeparator = settings.BatchSeparator
            });
            // NOTE: We only want to process batches that have statements (ie, ignore comments and empty lines)
            var batchSelection = parseResult.Script.Batches
                                 .Where(batch => batch.Statements.Count > 0)
                                 .Select((batch, index) =>
                                         new Batch(batch.Sql,
                                                   new SelectionData(
                                                       batch.StartLocation.LineNumber - 1,
                                                       batch.StartLocation.ColumnNumber - 1,
                                                       batch.EndLocation.LineNumber - 1,
                                                       batch.EndLocation.ColumnNumber - 1),
                                                   index, outputFactory));

            Batches = batchSelection.ToArray();
        }
 /// <summary>
 /// Constructor used for test purposes
 /// </summary>
 /// <param name="fileStreamFactory"></param>
 public DotCoverProvider(IFileStreamFactory fileStreamFactory)
 {
     _fileStreamFactory = fileStreamFactory;
 }
Пример #16
0
 public FileSystem(IFileStreamFactory streamFactory)
 {
     _streamFactory = streamFactory;
 }
 /// <summary>
 /// Main constructor.
 /// </summary>
 public DotCoverProvider()
 {
     _fileStreamFactory = new FileStreamFactory();
 }
 /// <summary>
 /// Default constructor
 /// </summary>
 public CountLOCProvider()
 {
     _fileStreamFactory = new FileStreamFactory();
 }
Пример #19
0
 /// <summary>
 /// Function to add a new batch to a Batch set
 /// </summary>
 private static void AddBatch(string query, ICollection <Batch> batchSet, IFileStreamFactory outputFactory)
 {
     batchSet.Add(new Batch(query, null, batchSet.Count, outputFactory, 1));
 }
Пример #20
0
 /// <summary>
 /// Default constructor
 /// </summary>
 public CodeMetrics()
 {
     _streamFactory = new FileStreamFactory();
 }
Пример #21
0
        private void ApplyExecutionSettings(
            ConnectionInfo connection,
            QueryExecutionSettings settings,
            IFileStreamFactory outputFactory)
        {
            outputFactory.QueryExecutionSettings = settings;
            QuerySettingsHelper helper = new QuerySettingsHelper(settings);

            // set query execution plan options
            if (DoesSupportExecutionPlan(connection))
            {
                // Checking settings for execution plan options
                if (settings.ExecutionPlanOptions.IncludeEstimatedExecutionPlanXml)
                {
                    // Enable set showplan xml
                    AddBatch(string.Format(SetShowPlanXml, On), BeforeBatches, outputFactory);
                    AddBatch(string.Format(SetShowPlanXml, Off), AfterBatches, outputFactory);
                }
                else if (settings.ExecutionPlanOptions.IncludeActualExecutionPlanXml)
                {
                    AddBatch(string.Format(SetStatisticsXml, On), BeforeBatches, outputFactory);
                    AddBatch(string.Format(SetStatisticsXml, Off), AfterBatches, outputFactory);
                }
            }

            StringBuilder builderBefore = new StringBuilder(512);
            StringBuilder builderAfter  = new StringBuilder(512);

            if (!connection.IsSqlDW)
            {
                // "set noexec off" should be the very first command, cause everything after
                // corresponding "set noexec on" is not executed until "set noexec off"
                // is encounted
                if (!settings.NoExec)
                {
                    builderBefore.AppendFormat("{0} ", helper.SetNoExecString);
                }

                if (settings.StatisticsIO)
                {
                    builderBefore.AppendFormat("{0} ", helper.GetSetStatisticsIOString(true));
                    builderAfter.AppendFormat("{0} ", helper.GetSetStatisticsIOString(false));
                }

                if (settings.StatisticsTime)
                {
                    builderBefore.AppendFormat("{0} ", helper.GetSetStatisticsTimeString(true));
                    builderAfter.AppendFormat("{0} ", helper.GetSetStatisticsTimeString(false));
                }
            }

            if (settings.ParseOnly)
            {
                builderBefore.AppendFormat("{0} ", helper.GetSetParseOnlyString(true));
                builderAfter.AppendFormat("{0} ", helper.GetSetParseOnlyString(false));
            }

            // append first part of exec options
            builderBefore.AppendFormat("{0} {1} {2}",
                                       helper.SetRowCountString, helper.SetTextSizeString, helper.SetNoCountString);

            if (!connection.IsSqlDW)
            {
                // append second part of exec options
                builderBefore.AppendFormat(" {0} {1} {2} {3} {4} {5} {6}",
                                           helper.SetConcatenationNullString,
                                           helper.SetArithAbortString,
                                           helper.SetLockTimeoutString,
                                           helper.SetQueryGovernorCostString,
                                           helper.SetDeadlockPriorityString,
                                           helper.SetTransactionIsolationLevelString,
                                           // We treat XACT_ABORT special in that we don't add anything if the option
                                           // isn't checked. This is because we don't want to be overwriting the server
                                           // if it has a default of ON since that's something people would specifically
                                           // set and having a client change it could be dangerous (the reverse is much
                                           // less risky)

                                           // The full fix would probably be to make the options tri-state instead of
                                           // just on/off, where the default is to use the servers default. Until that
                                           // happens though this is the best solution we came up with. See TFS#7937925

                                           // Note that users can always specifically add SET XACT_ABORT OFF to their
                                           // queries if they do truly want to set it off. We just don't want  to
                                           // do it silently (since the default is going to be off)
                                           settings.XactAbortOn ? helper.SetXactAbortString : string.Empty);

                // append Ansi options
                builderBefore.AppendFormat(" {0} {1} {2} {3} {4} {5} {6}",
                                           helper.SetAnsiNullsString, helper.SetAnsiNullDefaultString, helper.SetAnsiPaddingString,
                                           helper.SetAnsiWarningsString, helper.SetCursorCloseOnCommitString,
                                           helper.SetImplicitTransactionString, helper.SetQuotedIdentifierString);

                // "set noexec on" should be the very last command, cause everything after it is not
                // being executed unitl "set noexec off" is encounered
                if (settings.NoExec)
                {
                    builderBefore.AppendFormat("{0} ", helper.SetNoExecString);
                }
            }

            // add connection option statements before query execution
            if (builderBefore.Length > 0)
            {
                AddBatch(builderBefore.ToString(), BeforeBatches, outputFactory);
            }

            // add connection option statements after query execution
            if (builderAfter.Length > 0)
            {
                AddBatch(builderAfter.ToString(), AfterBatches, outputFactory);
            }
        }
Пример #22
0
        private async Task SaveResultsHelper(SaveResultsRequestParams saveParams,
                                             RequestContext <SaveResultRequestResult> requestContext, IFileStreamFactory fileFactory)
        {
            // retrieve query for OwnerUri
            Query query;

            if (!ActiveQueries.TryGetValue(saveParams.OwnerUri, out query))
            {
                await requestContext.SendError(SR.QueryServiceQueryInvalidOwnerUri);

                return;
            }

            //Setup the callback for completion of the save task
            ResultSet.SaveAsAsyncEventHandler successHandler = async parameters =>
            {
                await requestContext.SendResult(new SaveResultRequestResult());
            };
            ResultSet.SaveAsFailureAsyncEventHandler errorHandler = async(parameters, reason) =>
            {
                string message = SR.QueryServiceSaveAsFail(Path.GetFileName(parameters.FilePath), reason);
                await requestContext.SendError(message);
            };

            try
            {
                // Launch the task
                query.SaveAs(saveParams, fileFactory, successHandler, errorHandler);
            }
            catch (Exception e)
            {
                await errorHandler(saveParams, e.Message);
            }
        }
 /// <summary>
 /// Default constructor
 /// </summary>
 public CountProjectsByProjectTypeProvider()
 {
     _fileStreamFactory = new FileStreamFactory();
 }
Пример #24
0
 public FileSystem(IFileStreamFactory streamFactory)
 {
     _streamFactory = streamFactory;
 }
Пример #25
0
 public DoPutAction(Stream currentStream, IActivityIOPath destination, IDev2CRUDOperationTO crudArgument, string whereToPut, IDev2LogonProvider logOnProvider, IFile fileWrapper, IFileStreamFactory fileStreamFactory, IFilePath pathWrapper, IMemoryStreamFactory memoryStreamFactory, ImpersonationDelegate impersonationDelegate)
     : base(impersonationDelegate)
 {
     _logOnProvider       = logOnProvider;
     _pathWrapper         = pathWrapper;
     _fileWrapper         = fileWrapper;
     _fileStreamFactory   = fileStreamFactory;
     _memoryStreamFactory = memoryStreamFactory;
     _currentStream       = currentStream;
     _destination         = destination;
     _arguments           = crudArgument;
     _impersonatedUser    = _impersonationDelegate(_destination, _logOnProvider);
     _whereToPut          = whereToPut;
 }