Exemple #1
0
        private string MergeWorkingFiles(MergeData mergeData, string fileInstructionsKey, Language language)
        {
            var workingPath = ParameterUtils.GetParameter <string>(mergeData.WorkingFilePathKey) + "/" + GetWorkingPathLanguageString(language);

            Log.Info("MergeWorkingFiles working path: " + workingPath);

            var fileList = Directory.EnumerateFiles(workingPath);

            fileList = fileList.OrderBy(fileName => fileName, FileNameComparerObject);

            string languageString = GetLanguageString(language);

            var outputPath = OutputFolderPath + "/" + ParameterUtils.GetParameter <string>(mergeData.OutputFileBaseNameKey) + "_" + fileInstructionsKey + "_" + languageString +
                             DateTime.Now.ToString("yyyy_MM_dd") + ".txt";

            using (var writer = new StreamWriter(outputPath))
            {
                writer.WriteLine(mergeData.FeedTypeFileHeader);

                foreach (string filePath in fileList)
                {
                    using (var reader = new StreamReader(filePath))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            writer.WriteLine(line);
                        }
                    }
                }
            }

            return(outputPath);
        }
Exemple #2
0
        /// <summary>
        /// 针对<see cref="System.Data.IDbConnection"/>执行<see cref="System.Data.IDbCommand.CommandText"/>,并生成
        /// <see cref="System.Data.IDataReader"/>
        /// </summary>
        /// <param name="connString">A ConnectionString.</param>
        /// <param name="commandType">the CommandType.</param>
        /// <param name="commandText">A execute Sql.</param>
        /// <param name="timeoutInSeconds">the dbcommand timeout.</param>
        /// <param name="parameterValues">the sql parameters.</param>
        /// <returns>a datareader.</returns>
        public IDataReader ExecuteReader(string connString, CommandType commandType, string commandText,
                                         int timeoutInSeconds, IDbParameters parameterValues)
        {
            AssertUtils.StringNotNullOrEmpty(connString, "connString");

            ConnectionTxPair connectionTxPair = GetConnectionTxPair(connString);

            try
            {
                IDbCommand dbCommand = DbProvider.CreateCommand();

                PrepareCommand(dbCommand, connectionTxPair.Connection, connectionTxPair.Transaction, commandType, commandText,
                               parameterValues);

                ApplyTransactionTimeout(dbCommand, timeoutInSeconds);

                IDataReader executeReader = dbCommand.ExecuteReader();

                ParameterUtils.CopyParameters(parameterValues, dbCommand);

                return(executeReader);
            }
            catch (Exception)
            {
                ConnectionUtils.DisposeConnection(connectionTxPair.Connection, DbProvider);
                connectionTxPair.Connection = null;
                throw;
            }
            finally
            {
                //ConnectionUtils.DisposeConnection(connectionTxPair.Connection, DbProvider);
            }
        }
Exemple #3
0
        private void RemoveExecutionFiles()
        {
            try
            {
                if (!ParameterUtils.GetParameter <bool>("DeleteWorkingFiles"))
                {
                    return;
                }

                Directory.Delete(ParameterUtils.GetParameter <string>("WorkingDirectory"), recursive: true);

                if (!ZipFiles)
                {
                    return;
                }

                IEnumerable <string> outputTextFiles = Directory.EnumerateFileSystemEntries(OutputFolderPath,
                                                                                            "*.txt");
                outputTextFiles.ForEach(File.Delete);
            }
            catch (Exception ex)
            {
                const string message = "Error during cleanup working file deletion.";
                Log.Error(message, ex);
                _executionLogLogger.AddCustomMessage(message);
            }
        }
Exemple #4
0
        public override string Parse(IDictionary <string, object> parameterDictionary, Expression expressionNode)
        {
            var expressionBuilder = new StringBuilder();
            var exp = expressionNode as ConstantExpression;

            if (exp.Value == null)
            {
                expressionBuilder.Append("NULL");
            }
            else
            {
                // create parameter.
                string pname = ParameterUtils.CreateNewParameter(ref parameterDictionary);
                parameterDictionary[pname] = exp.Value.ToString();
                expressionBuilder.Append("@" + pname);

                //if (exp.Value.GetType() == typeof(string))
                //{
                //    ParameterDictionary[pname] = exp.Value.ToString();
                //    expressionBuilder.Append("@" + pname);
                //}
                //else if (exp.Value.GetType() == typeof(DateTime))
                //{
                //    ParameterDictionary[pname] = Convert.ToDateTime(exp.Value);
                //    expressionBuilder.Append("@" + pname);
                //}
                //else
            }

            return(expressionBuilder.ToString());
        }
Exemple #5
0
        /// <summary>
        /// 执行SQL,并返回影响的行数
        /// </summary>
        /// <param name="connString">A ConnectionString.</param>
        /// <param name="commandType">the Sql CommandType.</param>
        /// <param name="commandText">the execute Sql.</param>
        /// <param name="timeOutInSeconds">the dbcommand timeout.</param>
        /// <param name="parameters">the sql parameters.</param>
        /// <returns>返回受影响的行数.</returns>
        public int ExecuteNonQuery(string connString, CommandType commandType, string commandText, int timeOutInSeconds,
                                   IDbParameters parameters)
        {
            AssertUtils.StringNotNullOrEmpty(connString, "connString");

            ConnectionTxPair connectionTxPair = GetConnectionTxPair(connString);

            try
            {
                using (IDbCommand dbCommand = DbProvider.CreateCommand())
                {
                    PrepareCommand(dbCommand, connectionTxPair.Connection, connectionTxPair.Transaction, CommandType.Text, commandText,
                                   parameters);

                    ApplyTransactionTimeout(dbCommand, timeOutInSeconds);

                    int rowCount = dbCommand.ExecuteNonQuery();

                    ParameterUtils.CopyParameters(parameters, dbCommand);

                    return(rowCount);
                }
            }
            catch (Exception ex)
            {
                ConnectionUtils.DisposeConnection(connectionTxPair.Connection, DbProvider);
                connectionTxPair.Connection = null;
                throw ex;
            }
            finally
            {
                ConnectionUtils.DisposeConnection(connectionTxPair.Connection, DbProvider);
            }
        }
Exemple #6
0
        /// <summary>
        /// 设置<see cref="DbCommand"/>.
        /// </summary>
        /// <param name="dbCommand">The command.</param>
        /// <param name="dbConnection">The connection.</param>
        /// <param name="dbTransaction">The transaction</param>
        /// <param name="commandType">The<see cref="CommandType"/>.</param>
        /// <param name="commandText">The commandText</param>
        /// <param name="commandParameters">The SQL Parameters</param>
        private void PrepareCommand(IDbCommand dbCommand, IDbConnection dbConnection, IDbTransaction dbTransaction,
                                    CommandType commandType, string commandText,
                                    IDbParameters commandParameters)
        {
            AssertUtils.StringNotNullOrEmpty(commandText, "commandText", "commandText must not be Null or Empty.");
            AssertUtils.ArgumentNotNull(dbCommand, "dbCommand");
            AssertUtils.ArgumentNotNull(dbConnection, "dbConnection");

            if (dbConnection.State != ConnectionState.Open)
            {
                dbConnection.Open();
            }
            dbCommand.Connection = dbConnection;
            if (dbTransaction != null)
            {
                AssertUtils.ArgumentNotNull(dbTransaction.Connection, "dbTransaction.Connection",
                                            "The transaction was rollbacked or commited, please provide an open transaction.");
                dbCommand.Transaction = dbTransaction;
            }
            dbCommand.CommandType = commandType;
            dbCommand.CommandText = commandText;

            if (commandParameters != null)
            {
                ParameterUtils.CopyParameters(dbCommand, commandParameters);
            }
        }
        /// <summary>
        /// 执行查询,并返回查询所返回的结果集中第一行的第一列。所有其他的列和行将被忽略。
        /// </summary>
        /// <param name="cmdText">sql语句</param>
        /// <param name="commandType">指定如何解释命令字符串</param>
        /// <param name="parameters">DbCommand 的参数</param>
        /// <returns>结果集中第一行的第一列</returns>
        public object ExecuteScalar(System.Data.CommandType cmdType, string cmdText, IDbParameters parameters)
        {
            object result = null;

            try
            {
                DbConnection connection = (DbConnection)this.Session.Connection;
                ITransaction trans      = this.Session.Transaction;
                DbCommand    command    = connection.CreateCommand();
                command.CommandText = cmdText;
                command.CommandType = cmdType;
                if (null != parameters)
                {
                    ParameterUtils.CopyParameters(command, parameters);
                }
                trans.Enlist(command);
                result = command.ExecuteScalar();
            }
            catch (DbException e)
            {
                ExceptionHandler.AsynchronousThreadExceptionHandler = new DbExceptionHandler();
                ExceptionHandler.AsynchronousThreadExceptionHandler.HandleException(e);
            }
            return(result);
        }
Exemple #8
0
        /// <summary>
        /// Compares two <see cref="LogLevel"/> objects
        /// and returns a value indicating whether
        /// the first one is less than or equal to the second one.
        /// </summary>
        /// <param name="level1">The first level.</param>
        /// <param name="level2">The second level.</param>
        /// <returns>The value of <c>level1.Ordinal &lt;= level2.Ordinal</c>.</returns>
        public static bool operator <=(LogLevel level1, LogLevel level2)
        {
            ParameterUtils.AssertNotNull(level1, "level1");
            ParameterUtils.AssertNotNull(level2, "level2");

            return(level1.Ordinal <= level2.Ordinal);
        }
        private string GetParameterValueById(Element element, ElementId paramId)
        {
            if (element == null)
            {
                return(string.Empty);
            }

            Parameter parameter = null;

            if (ParameterUtils.IsBuiltInParameter(paramId))
            {
                parameter = element.get_Parameter((BuiltInParameter)paramId.IntegerValue);
            }
            else
            {
                ParameterElement parameterElem = element.Document.GetElement(paramId) as ParameterElement;
                if (parameterElem == null)
                {
                    return(string.Empty);
                }
                parameter = element.get_Parameter(parameterElem.GetDefinition());
            }

            return(parameter?.AsValueString() ?? string.Empty);
        }
Exemple #10
0
        public virtual IDataParameter CreateDbParameter(string name, Enum dbType, int size, object value)
        {
            var dbParameters = new DbParameters(DbProvider);
            IDbDataParameter dbDataParameter = dbParameters.Add(name, dbType, size);

            dbDataParameter.Value = value;
            return(ParameterUtils.CloneParameter(dbDataParameter));
        }
        public void Build(string[] args)
        {
            var startTime = DateTime.Now;

            Log.Info("Execution started.");

            if (ParameterUtils.GetParameter <bool>("EnableCategoryUpdates"))
            {
                try
                {
                    DoCategoryUpdates();
                }
                catch (Exception ex)
                {
                    Log.Error("An error occurred during processing of categories.", ex);
                }
            }

            if (ParameterUtils.GetParameter <bool>("EnableBrandUpdates"))
            {
                try
                {
                    DoBrandUpdates();
                }
                catch (Exception ex)
                {
                    Log.Error("An error occurred during processing of brands.", ex);
                }
            }

            if (ParameterUtils.GetParameter <bool>("EnableCmsProductListArchiving"))
            {
                try
                {
                    DoCmsProductListArchiving();
                }
                catch (Exception ex)
                {
                    Log.Error("An error occurred during processing of CMS Product Lists.", ex);
                }
            }

            if (ParameterUtils.GetParameter <bool>("EnableDefaultRecosUpdates"))
            {
                try
                {
                    DoDefaultRecosUpdates();
                }
                catch (Exception ex)
                {
                    Log.Error("An error occurred while generation default recommendations.", ex);
                }
            }

            var elapsedTime = DateTime.Now - startTime;

            Log.InfoFormat("Execution completed. Elapsed time: {0}", elapsedTime.ToString(@"dd\.hh\:mm\:ss"));
        }
        /// <summary>
        /// Gets the CMS content IDs of the product lists to use for default recommendations.
        /// </summary>
        private long[] GetNewProductListIds(int allowedDefaultRecommendationLanguageId)
        {
            // Load Rewards Centre config from CMS
            // It contains a setting specifying the product lists to use for default recos

            IDictionary <string, string> rewardsCentreSettings;

            try
            {
                var cmsRewardsCentreConfigId = ParameterUtils.GetParameter <int>("CmsRewardsCentreConfigId");

                Log.InfoFormat("Loading Rewards Centre config from CMS using content ID {0} for language id of {1}.", cmsRewardsCentreConfigId, allowedDefaultRecommendationLanguageId);

                using (var merchandisingService = _merchandisingServiceFactory.Create())
                {
                    rewardsCentreSettings = merchandisingService.ServiceClient.GetSettingsNoCache(cmsRewardsCentreConfigId, false);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to load Rewards Centre config from CMS", ex);
            }

            // Get the product list IDs setting
            var    setting = GetProductListSetting(allowedDefaultRecommendationLanguageId);
            string productListIdsSetting;

            rewardsCentreSettings.TryGetValue(setting, out productListIdsSetting);

            if (string.IsNullOrWhiteSpace(productListIdsSetting))
            {
                // All list ids have been removed from CMS config. log a message and delete all the entries in recosdb
                Log.InfoFormat("All product list ids have been removed from CMS configuration for language id of {0}. Removing all entries in recosdb as a result.", allowedDefaultRecommendationLanguageId);

                return(new long[0]);
            }

            Log.InfoFormat("Found setting of {0}: {1} for language id of {2}", setting, productListIdsSetting, allowedDefaultRecommendationLanguageId);

            // Parse ints

            try
            {
                var productListIds = productListIdsSetting
                                     .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                     .Select(long.Parse)
                                     .ToArray();

                Log.InfoFormat("Parsed product list IDs: {0} for {1}", string.Join(", ", productListIds), allowedDefaultRecommendationLanguageId);

                return(productListIds);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Failed to parse product list IDs ({0})", productListIdsSetting), ex);
            }
        }
Exemple #13
0
        public void RepeatableEnum_SinglePropertySet()
        {
            var request = new RepeatableEnumRequest {
                Mode = FileMode.Open
            };
            var dictionary = ParameterUtils.CreateParameterDictionary(request);

            Assert.Equal(FileMode.Open, dictionary["mode"]);
        }
Exemple #14
0
        /// <summary>Creates a <see cref="System.Uri"/> which is used to request the authorization code.</summary>
        public Uri Build()
        {
            var builder = new RequestBuilder()
            {
                BaseUri = AuthorizationServerUrl
            };

            ParameterUtils.InitParameters(builder, this);
            return(builder.BuildUri());
        }
            public System.Uri Build()
            {
                var builder = new RequestBuilder()
                {
                    BaseUri = new System.Uri("//revokeTokenUrl")
                };

                ParameterUtils.InitParameters(builder, this);
                return(builder.BuildUri());
            }
Exemple #16
0
        public void RepeatableEnum_BothPropertiesSet()
        {
            var request = new RepeatableEnumRequest
            {
                Mode     = FileMode.Open,
                ModeList = new[] { FileMode.Create, FileMode.Append }
            };

            Assert.Throws <InvalidOperationException>(() => ParameterUtils.CreateParameterDictionary(request));
        }
        /// <summary>Creates a <see cref="System.Uri"/> which is used to request the authorization code.</summary>
        public Uri Build()
        {
            var builder = new RequestBuilder()
            {
                BaseUri = revokeTokenUrl
            };

            ParameterUtils.InitParameters(builder, this);
            return(builder.BuildUri());
        }
Exemple #18
0
        public void RepeatableEnum_NoPropertiesSet()
        {
            var request    = new RepeatableEnumRequest();
            var dictionary = ParameterUtils.CreateParameterDictionary(request);
            // For historical reasons, we end up with a null value from the "FileMode? Mode" property.
            // That's fixable, but not worth the worry about whether it would break things.
            var pair = Assert.Single(dictionary);

            Assert.Equal("mode", pair.Key);
            Assert.Null(pair.Value);
        }
Exemple #19
0
        internal static async Task <TokenResponse> ExecuteAsync(this TokenRequest request, HttpClient httpClient,
                                                                string tokenServerUrl, CancellationToken taskCancellationToken, IClock clock, ILogger logger)
        {
            var httpRequest = new HttpRequestMessage(HttpMethod.Post, tokenServerUrl)
            {
                Content = ParameterUtils.CreateFormUrlEncodedContent(request)
            };

            var response = await httpClient.SendAsync(httpRequest, taskCancellationToken).ConfigureAwait(false);

            return(await TokenResponse.FromHttpResponseAsync(response, clock, logger).ConfigureAwait(false));
        }
Exemple #20
0
        public void RepeatableEnum_ListPropertySet()
        {
            var request = new RepeatableEnumRequest {
                ModeList = new[] { FileMode.Open, FileMode.Append }
            };
            var dictionary = ParameterUtils.CreateParameterDictionary(request);
            var pair       = Assert.Single(dictionary);

            Assert.Equal("mode", pair.Key);
            var repeatable = (Repeatable <FileMode>)pair.Value;

            Assert.Equal(new[] { FileMode.Open, FileMode.Append }, repeatable.ToArray());
        }
        public void DoUpdateDataSet()
        {
            String  sql     = "select TestObjectNo, Age, Name from TestObjects";
            DataSet dataSet = new DataSet();

            adoOperations.DataSetFill(dataSet, CommandType.Text, sql, new string[] { "TestObjects" });

            //Create and add new row.
            DataRow myDataRow = dataSet.Tables["TestObjects"].NewRow();

            myDataRow["Age"]  = 101;
            myDataRow["Name"] = "OldManWinter";
            dataSet.Tables["TestObjects"].Rows.Add(myDataRow);


            IDbCommand insertCommand = dbProvider.CreateCommand();

            insertCommand.CommandText = "insert into TestObjects(Age,Name) values (@Age,@Name)";
            IDbParameters parameters = adoOperations.CreateDbParameters();

            parameters.Add("Name", DbType.String, 12, "Name");
            //TODO - remembering the -1 isn't all that natural... add string name, dbtype, string sourceCol)
            //or AddSourceCol("Age", SqlDbType.Int);  would copy into source col?
            parameters.Add("Age", SqlDbType.Int, -1, "Age");

            //TODO - this isn't all that natural...
            ParameterUtils.CopyParameters(insertCommand, parameters);

            //insertCommand.Parameters.Add()

            adoOperations.DataSetUpdate(dataSet, "TestObjects",
                                        insertCommand,
                                        null,
                                        null);

            //TODO avoid param Utils copy by adding argument...

            //adoOperations.DataSetUpdate(dataSet, "TestObjects",
            //                            insertCommand, parameters,
            //                            null, null,
            //                            null, null);

            //adoOperations.DataSetUpdate(dataSet, "TestObjects",
            //                            CommandType type, string sql, parameters,
            //                            null, null,
            //                            null, null);

            //TODO how about breaking up the operations...
        }
Exemple #22
0
        /// <summary>
        /// Creates the <see cref="Google.Apis.Requests.RequestBuilder"/> which is used to generate a request.
        /// </summary>
        /// <returns>
        /// A new builder instance which contains the HTTP method and the right Uri with its path and query parameters.
        /// </returns>
        private RequestBuilder CreateBuilder()
        {
            var builder = new RequestBuilder()
            {
                BaseUri = new Uri(Service.BaseUri),
                Path    = RestPath,
                Method  = HttpMethod,
            };

            // Init parameters.
            builder.AddParameter(RequestParameterType.Query, "key", service.ApiKey);
            var parameters = ParameterUtils.CreateParameterDictionary(this);

            AddParameters(builder, ParameterCollection.FromDictionary(parameters));
            return(builder);
        }
        /// <summary>
        /// 执行查询,将结果集返回到一个DataTable
        /// </summary>
        /// <param name="commandType">指定如何解释命令字符串</param>
        /// <param name="cmdText">sql语句</param>
        /// <param name="parameters">DbCommand 的参数</param>
        /// <returns>结果集</returns>
        public System.Data.DataTable QueryDataTable(System.Data.CommandType commandType, string cmdText, IDbParameters parameters)
        {
            System.Data.DataTable result = null;
            try
            {
                DbConnection connection = (DbConnection)this.Session.Connection;
                ITransaction trans      = this.Session.Transaction;

                DbCommand command = connection.CreateCommand();
                command.CommandText = cmdText;
                command.CommandType = commandType;
                if (null != parameters)
                {
                    ParameterUtils.CopyParameters(command, parameters);
                }
                trans.Enlist(command);
                result = new System.Data.DataTable();
                System.Data.DataRow dt_dr = null;
                using (DbDataReader dr = command.ExecuteReader())
                {
                    int index = 0;
                    while (dr.Read())
                    {
                        if (index == 0)
                        {
                            for (int i = 0; i < dr.FieldCount; i++)
                            {
                                result.Columns.Add(dr.GetName(i), dr.GetFieldType(i));
                            }
                        }
                        dt_dr = result.NewRow();
                        for (int i = 0; i < dr.FieldCount; i++)
                        {
                            dt_dr[i] = dr[i];
                        }
                        result.Rows.Add(dt_dr);
                        index++;
                    }
                }
            }
            catch (DbException e)
            {
                ExceptionHandler.AsynchronousThreadExceptionHandler = new DbExceptionHandler();
                ExceptionHandler.AsynchronousThreadExceptionHandler.HandleException(e);
            }
            return(result);
        }
Exemple #24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SitemapWriter"/> class using
        /// the specified <see cref="XmlWriter"/> and site host URL.
        /// </summary>
        /// <param name="writer">The XmlWriter to write to.</param>
        /// <param name="siteHostUrl">The site host appended to the beginning of non-rooted URLs.</param>
        public SitemapWriter(XmlWriter writer, string siteHostUrl)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            ParameterUtils.ValidateStringNotNullOrEmpty(siteHostUrl, "siteHostUrl");

            if (siteHostUrl.IndexOf(':') == -1)
            {
                throw new ArgumentException("Invalid host url");
            }

            _writer      = writer;
            _siteHostUrl = siteHostUrl;
        }
Exemple #25
0
        private void DataGrid_OnCellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            if (!(e.EditingElement is TextBox textBox))
            {
                return;
            }
            if (textBox.DataContext is RuleValidationOutput ruleValidationOutput)
            {
                // 1. Try to change actual parameter value
                Document  document  = RegularApp.DocumentCacheService.GetDocument(RuleManagerViewModel.DocumentGuid);
                Element   element   = document.GetElement(ruleValidationOutput.ElementId);
                RegexRule regexRule = RuleManagerViewModel.SelectedRegexRule;
                Parameter parameter = ParameterUtils.GetParameterById
                                      (
                    document,
                    element,
                    regexRule.TrackingParameterObject.ParameterObjectId
                                      );
                if (parameter == null || parameter.IsReadOnly)
                {
                    return;
                }

                using (Transaction transaction = new Transaction(document, $"DataSpec User Modifying Element {element.Id}"))
                {
                    transaction.Start();
                    parameter.Set(textBox.Text);
                    transaction.Commit();

                    RuleValidationResult ruleValidationResult = RuleExecutionUtils.ExecuteRegexRule
                                                                (
                        RuleManagerViewModel.DocumentGuid,
                        regexRule.RuleGuid,
                        element
                                                                );

                    ruleValidationOutput.RuleValidationResult = ruleValidationResult;
                    ruleValidationOutput.ValidationText       = ruleValidationResult.GetEnumDescription();
                    if (ruleValidationOutput.RuleValidationResult != RuleValidationResult.Valid)
                    {
                        return;
                    }
                    ruleValidationOutput.CompliantExample = "";
                }
            }
        }
        public SearchListResponse Search(SearchResource.ListRequest request)
        {
            var parameters = ParameterUtils.CreateParameterKeyValuePairs(request);

            parameters.Add(new KeyValuePair <string, string>("key", _apiKey));

            var queryString = string.Join("&",
                                          parameters.Select(
                                              p =>
                                              string.IsNullOrEmpty(p.Value)
                            ? Uri.EscapeDataString(p.Key)
                            : string.Format("{0}={1}", Uri.EscapeDataString(p.Key),
                                            Uri.EscapeDataString(p.Value))));
            var url      = _restApiUrl + "/youtube/v3/search?" + queryString;
            var response = DoRestCall(url, "GET");

            return(JsonHelper.Deserialize <SearchListResponse>(response));
        }
        private HttpContent GetContent(SerializerResolver serializer)
        {
            switch (BodyType)
            {
            case BodyType.Encoded:
                return(new FormUrlEncodedContent(ParameterUtils.GetParameter <FormParameter>(this, RequestCulture)));

            case BodyType.Serialized:
                return(serializer.Resolve(GetType(), DataDirection.Out).Serialize(this));

            case BodyType.SerializedProperty:
                var body = serializer.Resolve(GetType(), DataDirection.Out).Serialize(ParameterUtils.GetSingleParameterObject <RequestBody>(this));
                return(body);

            case BodyType.Custom:
                return(BodyContent);

            default:
                //todo custom exception - there should have been a datatype specified
                throw new ArgumentOutOfRangeException();
            }
        }
 public RevitElement(Element element)
 {
     if (ProjectModelConnect.SelectedRevitModel != null && ProjectModelConnect.SelectedProject != null)
     {
         project            = ProjectProvider.Instance.CurrentProject._id;
         version            = ProjectProvider.Instance.CurrentVersion._id;
         guid               = element.UniqueId;
         name               = element.Name;
         elementId          = element.Id.IntegerValue.ToString();
         category           = element.Category.Name;
         level              = ElementUtils.GetElementLevel(ModelProvider.Levels, element);
         parameters         = ParameterUtils.SerializeRevitParameters(element);
         geometryParameters = ParameterUtils.SerializeGeoParameters(element);
         sharedParameters   = ParameterUtils.SerializeSharedParameters(element, ProjectModelConnect.SelectedRevitModel);
         worksetId          = element.WorksetId.ToString();
         location           = ElementUtils.SerializeLocation(element);
         boundingBox        = ElementUtils.SerializeBoundingBox(element.get_BoundingBox(null));
         centroid           = ElementUtils.SerializePoint(ElementUtils.GetCentroid(element));
         volume             = ElementUtils.GetAllSolidVolume(element).ToString();
         typeId             = element.GetTypeId().ToString();
     }
 }
Exemple #29
0
        /// <summary>
        /// 执行SQL, 返回Dataset
        /// </summary>
        /// <param name="connString">the ConnectionString</param>
        /// <param name="commandType">the sql CommandType.</param>
        /// <param name="commandText">the execute sql</param>
        /// <param name="timeoutInSeconds">the dbcommand timeout.</param>
        /// <param name="parameterValues">the sql parameters</param>
        /// <returns>return a Dataset</returns>
        /// <exception cref="ArgumentNullException">如果参数connString为null或空,则抛出此异常</exception>
        public DataSet ExecuteDataset(string connString, CommandType commandType, string commandText,
                                      int timeoutInSeconds, IDbParameters parameterValues)
        {
            AssertUtils.StringNotNullOrEmpty(connString, "connString");

            ConnectionTxPair connectionTxPair = GetConnectionTxPair(connString);

            try
            {
                using (IDbCommand dbCommand = DbProvider.CreateCommand())
                {
                    PrepareCommand(dbCommand, connectionTxPair.Connection, connectionTxPair.Transaction, commandType, commandText,
                                   parameterValues);

                    ApplyTransactionTimeout(dbCommand, timeoutInSeconds);

                    IDbDataAdapter dbDataAdapter = DbProvider.CreateDataAdapter();

                    dbDataAdapter.SelectCommand = dbCommand;
                    var ds = new DataSet();
                    dbDataAdapter.Fill(ds);

                    ParameterUtils.CopyParameters(parameterValues, dbCommand);

                    return(ds);
                }
            }
            catch (Exception)
            {
                ConnectionUtils.DisposeConnection(connectionTxPair.Connection, DbProvider);
                connectionTxPair.Connection = null;
                throw;
            }
            finally
            {
                ConnectionUtils.DisposeConnection(connectionTxPair.Connection, DbProvider);
            }
        }
        /// <summary>
        /// Executes the token request in order to receive a
        /// <see cref="Google.Apis.Auth.OAuth2.Responses.TokenResponse"/>. In case the token server returns an
        /// error, a <see cref="Google.Apis.Auth.OAuth2.Responses.TokenResponseException"/> is thrown.
        /// </summary>
        /// <param name="request">The token request.</param>
        /// <param name="httpClient">The HTTP client used to create an HTTP request.</param>
        /// <param name="tokenServerUrl">The token server URL.</param>
        /// <param name="taskCancellationToken">Cancellation token to cancel operation.</param>
        /// <param name="clock">
        /// The clock which is used to set the
        /// <see cref="Google.Apis.Auth.OAuth2.Responses.TokenResponse.Issued"/> property.
        /// </param>
        /// <returns>Token response with the new access token.</returns>
        public static async Task <TokenResponse> ExecuteAsync(this TokenRequest request, HttpClient httpClient,
                                                              string tokenServerUrl, CancellationToken taskCancellationToken, IClock clock)
        {
            var httpRequest = new HttpRequestMessage(HttpMethod.Post, tokenServerUrl);

            httpRequest.Content = ParameterUtils.CreateFormUrlEncodedContent(request);

            var response = await httpClient.SendAsync(httpRequest, taskCancellationToken).ConfigureAwait(false);

            var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            if (!response.IsSuccessStatusCode)
            {
                var error = NewtonsoftJsonSerializer.Instance.Deserialize <TokenErrorResponse>(content);
                throw new TokenResponseException(error);
            }

            // Gets the token and sets its issued time.
            var newToken = NewtonsoftJsonSerializer.Instance.Deserialize <TokenResponse>(content);

            newToken.Issued = clock.Now;
            return(newToken);
        }