public void Init()
 {
     this.connectionHelper = new ConnectionHelper();
     this.factoryMock = new Mock<IApiObjectsFactory>();
     this.positionStorage = new PositionsStorage(this.connectionHelper.Connection(), this.factoryMock.Object,
         "testaccount");
 }
    public static bool AddLibrariandetails(TMSLibrianDetails objLib, TMSAddressDetails objAddress)
    {
        ConnectionHelper CHelper = new ConnectionHelper();
        DbTransaction _SqlTrans = null;
        SqlConnection _connection = null; ;
        bool flag = false;
        try
        {
            _connection = CHelper.GetConnection();
            _SqlTrans = _connection.BeginTransaction();
            objAddress.Insert(_SqlTrans);

            objLib.LDAddressId = objAddress.ADAddressId;
            objLib.Insert(_SqlTrans);
            flag = true;
            _SqlTrans.Commit();
        }
        catch (Exception ex)
        {
            flag = false;
            _SqlTrans.Rollback();
        }
        finally
        {
            CHelper.CloseConnection(_connection);
        }
        return flag;
    }
Exemple #3
0
 public void Init()
 {
     this.connectionHelper = new ConnectionHelper();
     this.factoryMock = new Mock<IApiObjectsFactory>();
     this.order = new Order(1, "testaccount", this.connectionHelper.Connection(), this.factoryMock.Object,
         new CancellationTokenSource());
 }
Exemple #4
0
        public void Init()
        {
            this.connectionHelper = new ConnectionHelper();

            this.executionsStorageMock = new Mock<IExecutionStorageInternal>();
            this.positionsStorageMock = new Mock<IPositionsStorageInternal>();
            this.ordersStorageMock = new Mock<IOrdersStorageInternal>();
            this.ordersIdsDispenserMock = new Mock<IIdsDispenser>();
            this.factoryMock = new Mock<IApiObjectsFactory>();

            this.account = new Account("testaccount", this.connectionHelper.Connection(), this.factoryMock.Object,
                this.executionsStorageMock.Object
                , this.positionsStorageMock.Object, this.ordersStorageMock.Object, this.ordersIdsDispenserMock.Object,
                new CancellationTokenSource(),
                new AccountCurrenciesFields());
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="locLat"></param>
        /// <param name="locLong"></param>
        /// <returns></returns>
        public List <Practicien> GetPracticiensAround15km(Dictionary <Practicien.Criteria, object> filter)
        {
            // Initialisation
            QueryBuilder       qb        = new QueryBuilder();
            List <DbParameter> sqlParams = new List <DbParameter>();
            List <Practicien>  result    = new List <Practicien>();

            // Construction de la requête
            qb.AddSelect(
                @" PRA.ID,
            PRA.Nom,
            PRA.Prenom,
            PRA.Specialite1,
            PRA.accepteCarteVitale,
            PRA.Ville,
            PRA.Adresse,
            PRA.CP,
            PRA.LocLat,
            PRA.LocLong,
            PRA.refSecteurTarifaire
            ")
            .AddFrom(ConstDb.Tables.Practicien, "PRA");

            if (filter != null)
            {
                if (filter.ContainsKey(Practicien.Criteria.Specialite))
                {
                    qb.AddWhere("( PRA.specialite1 = @PRA_SPE1 OR PRA.specialite2 = @PRA_SPE2 OR PRA.specialite3 = @PRA_SPE3 )");
                    SqlServerConnectionHelper.AddParamToList(sqlParams, "@PRA_SPE1", filter[Practicien.Criteria.Specialite]);
                    SqlServerConnectionHelper.AddParamToList(sqlParams, "@PRA_SPE2", filter[Practicien.Criteria.Specialite]);
                    SqlServerConnectionHelper.AddParamToList(sqlParams, "@PRA_SPE3", filter[Practicien.Criteria.Specialite]);
                }

                if (filter.ContainsKey(Practicien.Criteria.SortBySecteur1))
                {
                    if (filter[Practicien.Criteria.SortBySecteur1].ToString().Equals("True"))
                    {
                        qb.AddWhere("PRA.refSecteurTarifaire LIKE @PRA_Secteur1");
                        SqlServerConnectionHelper.AddParamToList(sqlParams, "@PRA_Secteur1", 1);
                    }
                }
            }

            // Exécution de la requête
            using (IDataReader reader = SqlServerConnectionHelper.GetReader(qb.ToSql(), this.Connection, sqlParams))
            {
                while (ConnectionHelper.LimitedRead(reader, result.Count))
                {
                    double locLat   = double.Parse(filter[Practicien.Criteria.LocLat].ToString());
                    double locLong  = double.Parse(filter[Practicien.Criteria.LocLong].ToString());
                    int    distance = Convert.ToInt32(Util.Distance(locLat, locLong, SqlServerConnectionHelper.ToDouble(reader["LocLat"]), SqlServerConnectionHelper.ToDouble(reader["LocLong"])));

                    if (distance <= 15)
                    {
                        Practicien practicient = new Practicien();

                        practicient.Id                = SqlServerConnectionHelper.ToInt(reader["ID"]);
                        practicient.Nom               = SqlServerConnectionHelper.ToString(reader["Nom"]);
                        practicient.Prenom            = SqlServerConnectionHelper.ToString(reader["Prenom"]);
                        practicient.Specialite1       = SqlServerConnectionHelper.ToString(reader["Specialite1"]);
                        practicient.Ville             = SqlServerConnectionHelper.ToString(reader["Ville"]);
                        practicient.AcceptCarteVitale = SqlServerConnectionHelper.ToBool(reader["accepteCarteVitale"]);
                        practicient.Adresse           = SqlServerConnectionHelper.ToString(reader["Adresse"]);
                        practicient.SecteurTarifaire  = SqlServerConnectionHelper.ToString(reader["refSecteurTarifaire"]);
                        practicient.CP                = SqlServerConnectionHelper.ToInt(reader["CP"]);
                        practicient.Distance          = distance;

                        result.Add(practicient);
                    }
                }
            }

            return(result);
        }
Exemple #6
0
 public void Init()
 {
     this.connectionHelper = new ConnectionHelper();
     this.observerMock = new Mock<IQuoteObserver>();
 }
 public static void SendAddMessage(string zoneName, double x, double y, double z, int size)
 {
     ConnectionHelper.SendMessageToServer(new MessageConqExclude {
         CommandType = ExcludeManage.Add, ZoneName = zoneName, X = x, Y = y, Z = z, Size = size
     });
 }
        //添加砍价商品/优惠券
        public static int AddSharBargainProduct(ShareBargainProductModel request, string Operator)
        {
            string sql    = @"INSERT INTO Configuration..BargainProduct
                                       ([PID]
                                       ,[productName]
                                       ,[OriginalPrice]
                                       ,[FinalPrice]
                                       ,[Sequence]
                                       ,[Image1]
                                       ,[WXShareTitle]
                                       ,[APPShareId]
                                       ,[Times]
                                       ,[BeginDateTime]
                                       ,[EndDateTime]
                                       ,[TotalStockCount]
                                       ,[CurrentStockCount]
                                       ,[Operator]
                                       ,[CreateDateTime] 
                                       ,[PageName]
                                       ,[SuccessfulHint]
                                       ,[ShowBeginTime]
                                       ,[ProductType]
                                       ,[SimpleDisplayName]
                                       ,[HelpCutPriceTimes]
                                       ,[CutPricePersonLimit]
                                       ,BigCutBeforeCount
                                       ,BigCutPriceRate
                                       ,ProductDetailImg1
                                       ,ProductDetailImg2
                                       ,ProductDetailImg3
                                       ,ProductDetailImg4
                                       ,ProductDetailImg5
                                       ,[IsDelete])
                                 VALUES
                                       (@PID
                                       ,@ProductName
                                       ,@OriginalPrice
                                       ,@FinalPrice
                                       ,@Sequence
                                       ,@Image1
                                       ,@WXShareTitle
                                       ,@APPShareId
                                       ,@Times
                                       ,@BeginDateTime
                                       ,@EndDateTime
                                       ,@TotalStockCount
                                       ,@TotalStockCount
                                       ,@Operator
                                       ,GETDATE() 
                                       ,@PageName
                                       ,@SuccessfulHint
                                       ,@ShowBeginTime
                                       ,@ProductType
                                       ,@SimpleDisplayName
                                       ,@HelpCutPriceTimes
                                       ,@CutPricePersonLimit
                                       ,@BigCutBeforeCount
                                       ,@BigCutPriceRate
                                       ,@ProductDetailImg1
                                       ,@ProductDetailImg2
                                       ,@ProductDetailImg3
                                       ,@ProductDetailImg4
                                       ,@ProductDetailImg5
                                       ,0);
                                       SELECT SCOPE_IDENTITY()";
            var    result = 0;

            try
            {
                using (var dbHelper = new SqlDbHelper(ConnectionHelper.GetDecryptConn("Gungnir")))
                {
                    var sqlPrams = new SqlParameter[]
                    {
                        new SqlParameter("@PID", request.PID),
                        new SqlParameter("@ProductName", request.ProductName),
                        new SqlParameter("@OriginalPrice", request.OriginalPrice),
                        new SqlParameter("@FinalPrice", request.FinalPrice),
                        new SqlParameter("@Sequence", request.Sequence),
                        new SqlParameter("@Image1", request.Image1 ?? ""),
                        new SqlParameter("@WXShareTitle", request.WXShareTitle),
                        new SqlParameter("@APPShareId", request.APPShareId),
                        new SqlParameter("@Times", request.Times),
                        new SqlParameter("@BeginDateTime", request.BeginDateTime),
                        new SqlParameter("@EndDateTime", request.EndDateTime),
                        new SqlParameter("@TotalStockCount", request.TotalStockCount),
                        new SqlParameter("@Operator", Operator),
                        new SqlParameter("@PageName", request.PageName),
                        new SqlParameter("@SuccessfulHint", request.SuccessfulHint),
                        new SqlParameter("@ShowBeginTime", request.ShowBeginTime),
                        new SqlParameter("@ProductType", request.ProductType),
                        new SqlParameter("@SimpleDisplayName", request.SimpleDisplayName),
                        new SqlParameter("@HelpCutPriceTimes", request.HelpCutPriceTimes),
                        new SqlParameter("@CutPricePersonLimit", request.CutPricePersonLimit),
                        new SqlParameter("@BigCutBeforeCount", request.BigCutBeforeCount),
                        new SqlParameter("@BigCutPriceRate", request.BigCutPriceRate),
                        new SqlParameter("@ProductDetailImg1", request.ProductDetailImg1),
                        new SqlParameter("@ProductDetailImg2", request.ProductDetailImg2),
                        new SqlParameter("@ProductDetailImg3", request.ProductDetailImg3),
                        new SqlParameter("@ProductDetailImg4", request.ProductDetailImg4),
                        new SqlParameter("@ProductDetailImg5", request.ProductDetailImg5),
                    };
                    int.TryParse(dbHelper.ExecuteScalar(sql, CommandType.Text, sqlPrams).ToString(), out result);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return(result);
        }
Exemple #9
0
 /// <summary>
 /// Change collation clicked.
 /// </summary>
 protected void btnChangeCollation_Click(object sender, EventArgs e)
 {
     ConnectionHelper.ChangeDatabaseCollation(ConnectionString, Database, COLLATION_CASE_INSENSITIVE);
     lblCompleted.ResourceString = "separationDB.OK";
     btnChangeCollation.Visible  = false;
 }
    /// <summary>
    /// Takes the existing value and sets the Category Tree
    /// </summary>
    protected void setCategoryTree()
    {
        tvwCategoryTree.Nodes.Clear();

        // Grab Current Categories
        CurrentCategories = new List <CategoryInfo>();
        if (SaveModeVal == SaveType.ToJoinTable)
        {
            // Get initial categories from Join Table.
            if (!IsPostBack)
            {
                // Get the CategoryNames currently in the join table.
                int    totalRecords        = 0;
                var    currentCategoriesDS = ConnectionHelper.ExecuteQuery(JoinTableName + ".selectall", null, string.Format("{0} = '{1}'", JoinTableLeftFieldName, CurrentItemIdentification), null, -1, null, -1, -1, ref totalRecords);
                string CategoryFieldName   = "";
                switch (FieldSaveModeVal)
                {
                case FieldSaveType.ID:
                    CategoryFieldName = "CategoryID";
                    break;

                case FieldSaveType.GUID:
                    CategoryFieldName = "CategoryGUID";
                    break;

                case FieldSaveType.CategoryName:
                    CategoryFieldName = "CategoryName";
                    break;
                }
                List <string> currentCategories = new List <string>();
                foreach (DataRow dr in currentCategoriesDS.Tables[0].Rows)
                {
                    currentCategories.Add(ValidationHelper.GetString(dr[JoinTableRightFieldName], ""));
                }

                var CurrentCategoryObjects = CategoryInfoProvider.GetCategories(null, null, -1, null, SiteContext.CurrentSiteID).WhereIn(CategoryFieldName, currentCategories).Select(x => CategoryInfo.New(x));
                if (CurrentCategoryObjects != null)
                {
                    CurrentCategories.AddRange(CurrentCategoryObjects);
                }
            }
        }
        else
        {
            // Get initial categories from Document listing.
            if (!IsPostBack)
            {
                // Will set the txtValue to the current proper categories after the first setup.
                var CurrentCategoriesOfDoc = DocumentCategoryInfoProvider.GetDocumentCategories(ValidationHelper.GetInteger(PageDocument.GetValue("DocumentID"), -1));
                if (CurrentCategoriesOfDoc != null)
                {
                    CurrentCategories.AddRange(CurrentCategoriesOfDoc);
                }

                /*
                 * // Handle default if new form and no categories
                 * if (Form.Mode != FormModeEnum.Update && CurrentCategories.Count == 0 && !string.IsNullOrWhiteSpace(txtValue.Text))
                 * {
                 *  // Don't know if default is CodeName, Guid, or ID, so cover all
                 *  string[] DelimitedValues = SplitAndSecure(txtValue.Text);
                 *  string DefaultValueWhereCondition = "";
                 *  int[] intArray = StringArrayToIntArray(DelimitedValues);
                 *  Guid[] guidArray = StringArrayToGuidArray(DelimitedValues);
                 *  DefaultValueWhereCondition = SqlHelper.AddWhereCondition(DefaultValueWhereCondition, string.Format("CategoryName in ('{0}')", string.Join("','", DelimitedValues)), "OR");
                 *  if (intArray.Length > 0)
                 *  {
                 *      DefaultValueWhereCondition = SqlHelper.AddWhereCondition(DefaultValueWhereCondition, string.Format("CategoryID in ('{0}')", string.Join("','", intArray)), "OR");
                 *  }
                 *  if (guidArray.Length > 0)
                 *  {
                 *      DefaultValueWhereCondition = SqlHelper.AddWhereCondition(DefaultValueWhereCondition, string.Format("CategoryGUID in ('{0}')", string.Join("','", guidArray)), "OR");
                 *  }
                 *  foreach (CategoryInfo catInfo in CategoryInfoProvider.GetCategories().Where(DefaultValueWhereCondition))
                 *  {
                 *      CurrentCategories.Add(catInfo);
                 *  }
                 * }*/
            }
            else
            {
                /*
                 * var CurrentCategoriesOfDoc = CategoryInfoProvider.GetCategories("CategoryID in ('" + string.Join("','", SplitAndSecure(initialCategories)) + "')", null, -1, null, SiteContext.CurrentSiteID);
                 * if (CurrentCategoriesOfDoc != null)
                 * {
                 *  CurrentCategories.AddRange(CurrentCategoriesOfDoc);
                 * }
                 */
            }
        }


        if (OnlyLeafSelectable)
        {
            if (ParentSelectsChildren)
            {
                tvwCategoryTree.ShowCheckBoxes = TreeNodeTypes.All;
            }
            else
            {
                tvwCategoryTree.ShowCheckBoxes = TreeNodeTypes.Leaf;
            }
        }
        else
        {
            tvwCategoryTree.ShowCheckBoxes = TreeNodeTypes.All;
        }

        // Root Category given, all items must be under that root
        // If Tree Structure, must go through all children of root and then compare to the "Where" List of items, if where is set
        // If List, display all valid categories under the root.

        int RootCategoryID = 0;
        var rootCategory   = CategoryInfoProvider.GetCategoryInfo(RootCategory, SiteContext.CurrentSiteName);

        if (rootCategory == null && int.TryParse(RootCategory, out RootCategoryID))
        {
            rootCategory = CategoryInfoProvider.GetCategoryInfo(RootCategoryID);
        }


        // Grab allowable Categories if user sets a WHERE
        string TempWhere = "CategoryNamePath like " + (rootCategory == null ? "'/%'" : "'" + rootCategory.CategoryNamePath + "/%'") + (string.IsNullOrWhiteSpace(WhereFilter) ? "" : " and " + WhereFilter);

        DefaultSortOrder = (string.IsNullOrWhiteSpace(OrderBy) ? (DisplayMode == DisplayType.List ? "CategoryDisplayName" : "CategoryLevel, CategoryOrder") : OrderBy);
        var AllowableCategoryList = CategoryInfoProvider.GetCategories(TempWhere, DefaultSortOrder, -1, null, SiteContext.CurrentSiteID);

        if (AllowableCategoryList.Count > 0)
        {
            AllowableCategoryIDWhere = "CategoryID in (" + string.Join(",", AllowableCategoryList.Select(x => new CategoryInfo(x).CategoryID)) + ")";
        }
        else
        {
            AllowableCategoryIDWhere = "";
        }

        if (DisplayMode == DisplayType.Tree)
        {
            pnlSearchFilter.Visible   = false;
            tvwCategoryTree.ShowLines = true;
            TreeNode rootNode = null;
            if (rootCategory == null)
            {
                rootNode = new TreeNode("Root", GetNodeValue(rootCategory));
                rootNode.ShowCheckBox = (OnlyLeafSelectable && ParentSelectsChildren);
                rootNode.SelectAction = TreeNodeSelectAction.None;
                // Expand to the nth level from the Category Level.
                ExpandCategoryLevel = 0 + ExpandToLevel;
                rootNode.Expanded   = (0 < ExpandCategoryLevel);
                SetNodeChecked(rootNode, rootCategory);
            }
            else
            {
                rootNode = new TreeNode(GetInputDataPrepend(rootCategory), GetNodeValue(rootCategory));
                rootNode.SelectAction = TreeNodeSelectAction.None;
                // Expand to the nth level from the Category Level.
                ExpandCategoryLevel = rootCategory.CategoryLevel + ExpandToLevel;
                rootNode.Expanded   = (rootCategory.CategoryLevel < ExpandCategoryLevel);
                SetNodeChecked(rootNode, rootCategory);

                // If either all items selectable, or if only leaf selectable and this is a leaf node, save to the possible categories list.
                if (rootCategory.Children.Count == 0 || !OnlyLeafSelectable)
                {
                    PossibleCategories.Add(rootCategory);
                }
            }
            CreateChildTreeNodes(rootCategory, ref rootNode, ref CurrentCategories);
            tvwCategoryTree.Nodes.Add(rootNode);
        }
        else if (DisplayMode == DisplayType.List)
        {
            pnlTreeButtons.Visible = false;
            // Just loop through allowable Categories and add to list.
            foreach (CategoryInfo CategoryItem in AllowableCategoryList)
            {
                TreeNode childNode = new TreeNode(GetInputDataPrepend(CategoryItem), GetNodeValue(CategoryItem));
                childNode.SelectAction = TreeNodeSelectAction.None;
                childNode.Expanded     = (CategoryItem.CategoryLevel < ExpandCategoryLevel);
                SetNodeChecked(childNode, CategoryItem);

                PossibleCategories.Add(CategoryItem);
                tvwCategoryTree.Nodes.Add(childNode);
            }
        }
    }
Exemple #11
0
        /// <summary>
        /// Generic save|update
        /// </summary>
        /// <typeparam name="T">Tipo de entidad</typeparam>
        /// <param name="entitySave">objeto a guardar</param>
        /// <param name="enumMode">
        /// Add. Agrega
        /// Edit. Actualiza
        /// Delete. Elimina
        /// </param>
        /// <returns>0. No se guardó | 1. Se guardó | -1 Existe un registro con el mismo ID</returns>
        /// <history>
        /// [emoguel] created 25/04/2016
        /// </history>
        public async static Task <int> OperationEntity <T>(T entitySave, EnumMode enumMode) where T : class
        {
            int nRes = 0;

            nRes = await Task.Run(() =>
            {
                using (var dbContext = new IMEntities(ConnectionHelper.ConnectionString()))
                {
                    switch (enumMode)
                    {
                        #region Delete
                    case EnumMode.Delete:
                        {
                            dbContext.Entry(entitySave).State = EntityState.Deleted;
                            break;
                        }

                        #endregion
                        #region Edit
                    case EnumMode.Edit:
                        {
                            dbContext.Entry(entitySave).State = EntityState.Modified;
                            break;
                        }

                        #endregion
                        #region Add
                    case EnumMode.Add:
                        {
                            var objContext = ((IObjectContextAdapter)dbContext).ObjectContext;
                            var objSet     = objContext.CreateObjectSet <T>();
                            #region Buscar si tiene Llave identity
                            bool blIdentity = false;
                            foreach (EdmProperty edm in objSet.EntitySet.ElementType.KeyMembers)
                            {
                                var a = edm.MetadataProperties.Where(item => item.Name == "http://schemas.microsoft.com/ado/2009/02/edm/annotation:StoreGeneratedPattern").FirstOrDefault();
                                if (a != null)
                                {
                                    if (a.Value.ToString() == "Identity")
                                    {
                                        blIdentity = true;
                                        break;
                                    }
                                }
                            }
                            #endregion

                            if (blIdentity == true)//Si es campo autoincremental
                            {
                                dbContext.Entry(entitySave).State = EntityState.Added;
                            }
                            else
                            {
                                var keyNames  = objSet.EntitySet.ElementType.KeyMembers.Select(edmMember => edmMember.Name);
                                var keyValues = keyNames.Select(name => entitySave.GetType().GetProperty(name).GetValue(entitySave, null)).ToArray();
                                var exists    = dbContext.Set <T>().Find(keyValues);
                                if (exists != null)//Validamos si existe un registro con el mismo ID
                                {
                                    return(-1);
                                }
                                else//Agrega
                                {
                                    dbContext.Entry(entitySave).State = EntityState.Added;
                                }
                            }
                            break;
                        }
                        #endregion
                    }
                    return(dbContext.SaveChanges());
                }
            });

            return(nRes);
        }
 public IQueryable <BaseDocument> GetLinkedDocuments([FromODataUri] int key)
 {
     Session = ConnectionHelper.CreateSession();
     return(Session.Query <Order>().AsWrappedQuery().Where(m => m.ID == key).SelectMany(t => t.LinkedDocuments));
 }
 public App()
 {
     ConnectionHelper.Connect();
     DemoDataHelper.Seed();
 }
 public IQueryable <Order> Get()
 {
     Session = ConnectionHelper.CreateSession();
     return(Session.Query <Order>().AsWrappedQuery());
 }
 public IQueryable <OrderDetail> GetOrderDetails([FromODataUri] int key)
 {
     Session = ConnectionHelper.CreateSession();
     return(Session.Query <OrderDetail>().AsWrappedQuery().Where(t => t.Order.ID == key));
 }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            if (!ConnectionHelper.CheckNetworkConnection())
            {
                CreateConnectionDialog().Show();
            }
            else
            {
                // Set our view from the "main" layout resource
                SetContentView(Resource.Layout.Main);

                DataExtractor extractor        = new DataExtractor();
                var           halfDayForecast  = extractor.HalfDayForecast();
                var           fiveDaysForecast = extractor.FiveDayForecast();

                #region FindView
                windmillBigTop      = FindViewById <ImageView>(Resource.Id.windmill_big_top);
                windmillBigBottom   = FindViewById <ImageView>(Resource.Id.windmill_big_bottom);
                windmillSmallTop    = FindViewById <ImageView>(Resource.Id.windmill_small_top);
                windmillSmallBottom = FindViewById <ImageView>(Resource.Id.windmill_small_bottom);
                circle             = FindViewById <Circle>(Resource.Id.humidity_circle);
                percentageIncrease = FindViewById <TextView>(Resource.Id.humidity_number);
                currentTemp        = FindViewById <TextView>(Resource.Id.current_temp);
                minTemp            = FindViewById <TextView>(Resource.Id.min_temp);
                maxTemp            = FindViewById <TextView>(Resource.Id.max_temp);
                uvIndex            = FindViewById <TextView>(Resource.Id.uv_index_value);
                windSpeed          = FindViewById <TextView>(Resource.Id.wind_speed);
                windDirection      = FindViewById <TextView>(Resource.Id.wind_direction);
                realFeelTemp       = FindViewById <TextView>(Resource.Id.feels_like_value);
                weatherPhrase      = FindViewById <TextView>(Resource.Id.weather_phrase);
                mainLayout         = FindViewById <RelativeLayout>(Resource.Id.main_layout);
                dailyForecastList  = FindViewById <NotScrollableGridView>(Resource.Id.daily_forecast_list);
                hourlyForecastList = FindViewById <RecyclerView>(Resource.Id.hourly_forecast_list);
                #endregion

                hfCollection    = new HourlyForecastCollection(HalfDayForecast(halfDayForecast));
                hfLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.Horizontal, false);
                hourlyForecastList.SetLayoutManager(hfLayoutManager);
                hourlyForecastList.SetAdapter(new HourlyAdapter(hfCollection));
                dailyForecastList.Adapter = new DailyForecastAdapter(this, FiveDayForecast(fiveDaysForecast));

                windmillBigTop.SetImageResource(Resource.Drawable.windmill_top);
                windmillBigBottom.SetImageResource(Resource.Drawable.windmill_bottom);
                windmillSmallTop.SetImageResource(Resource.Drawable.windmill_top);
                windmillSmallBottom.SetImageResource(Resource.Drawable.windmill_bottom);

                currentTemp.Text   = " " + Math.Round(halfDayForecast[0].Temperature.Value) + "\u00B0";
                maxTemp.Text       = Math.Round(halfDayForecast[0].RealFeelTemperature.Value) + "\u00B0";
                minTemp.Text       = "/" + Math.Round(halfDayForecast[0].DewPoint.Value) + "\u00B0";
                weatherPhrase.Text = halfDayForecast[0].IconPhrase;

                uvIndex.Text       = halfDayForecast[0].UVIndex + " " + halfDayForecast[0].UVIndexText;
                realFeelTemp.Text  = Math.Round(halfDayForecast[0].RealFeelTemperature.Value) + "\u00B0";
                windSpeed.Text     = halfDayForecast[0].Wind.Speed.Value + " " + halfDayForecast[0].Wind.Speed.Unit;
                windDirection.Text = halfDayForecast[0].Wind.Direction.Degrees + "\u00B0" + " " + halfDayForecast[0].Wind.Direction.Localized;

                var animation = AnimationUtils.LoadAnimation(Application.Context, Resource.Animation.rotate_animation);
                animation.Duration = 4000;
                windmillBigTop.StartAnimation(animation);
                var animation2 = AnimationUtils.LoadAnimation(Application.Context, Resource.Animation.rotate_animation_2);
                animation2.Duration = 4000;
                windmillSmallTop.StartAnimation(animation2);

                var humidityPercentage = halfDayForecast[0].RelativeHumidity;
                var circleDegrees      = Convert.ToInt32(3.6 * humidityPercentage);

                CircleAngleAnimation circleAnimation = new CircleAngleAnimation(circle, circleDegrees);
                circleAnimation.Duration = 1000;
                circle.StartAnimation(circleAnimation);
                StartCountAnimation(humidityPercentage);

                circle.Touch += (o, e) =>
                {
                    circle.StartAnimation(circleAnimation);
                    StartCountAnimation(humidityPercentage);
                };


                SetBackgroundImage();
            }
        }
Exemple #17
0
        /// 静态构造函数
        static CCTDContext()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
            string connectionString = Config.IsDebug
                ? (Config.IsProduct? ConnectionHelper.GetOracleConnectionString("CCTDEV"):ConnectionHelper.GetOracleConnectionString("CTOSU"))
                : ConnectionHelper.GetOracleConnectionString("CCTD");

            dbContext = new DBContext(connectionString);
        }
        /// <summary>
        /// Récupération de la liste des practiciens en fonctions des criteres de la recherche
        /// </summary>
        /// <param name="filter">Critères de filtre</param>
        /// <returns>Liste des practiciens</returns>
        public List <Practicien> ListPracticiens(Dictionary <Practicien.Criteria, object> filter)
        {
            // Initialisation
            QueryBuilder       qb        = new QueryBuilder();
            List <DbParameter> sqlParams = new List <DbParameter>();
            List <Practicien>  result    = new List <Practicien>();

            // Construction de la requête
            qb.AddSelect(
                @" PRA.ID,
            PRA.Nom,
            PRA.Prenom,
            PRA.Specialite1,
            PRA.accepteCarteVitale,
            PRA.Ville,
            PRA.Adresse,
            PRA.CP,
            PRA.refSecteurTarifaire
            ")
            .AddFrom(ConstDb.Tables.Practicien, "PRA");

            if (filter != null)
            {
                // Ajout des critères de filtre
                if (filter.ContainsKey(Practicien.Criteria.Lieu))
                {
                    qb.AddWhere("PRA.Ville LIKE @PRA_VILLE");
                    SqlServerConnectionHelper.AddParamToList(sqlParams, "@PRA_VILLE", "%" + filter[Practicien.Criteria.Lieu] + "%");
                }

                if (filter.ContainsKey(Practicien.Criteria.Specialite))
                {
                    qb.AddWhere("( PRA.specialite1 = @PRA_SPE1 OR PRA.specialite2 = @PRA_SPE2 OR PRA.specialite3 = @PRA_SPE3 )");
                    SqlServerConnectionHelper.AddParamToList(sqlParams, "@PRA_SPE1", filter[Practicien.Criteria.Specialite]);
                    SqlServerConnectionHelper.AddParamToList(sqlParams, "@PRA_SPE2", filter[Practicien.Criteria.Specialite]);
                    SqlServerConnectionHelper.AddParamToList(sqlParams, "@PRA_SPE3", filter[Practicien.Criteria.Specialite]);
                }

                if (filter.ContainsKey(Practicien.Criteria.SortBySecteur1))
                {
                    if (filter[Practicien.Criteria.SortBySecteur1].ToString().Equals("True"))
                    {
                        qb.AddWhere("PRA.refSecteurTarifaire LIKE @PRA_Secteur1");
                        SqlServerConnectionHelper.AddParamToList(sqlParams, "@PRA_Secteur1", 1);
                    }
                }
            }

            // Exécution de la requête
            using (IDataReader reader = SqlServerConnectionHelper.GetReader(qb.ToSql(), this.Connection, sqlParams))
            {
                while (ConnectionHelper.LimitedRead(reader, result.Count))
                {
                    Practicien practicient = new Practicien();

                    practicient.Id                = SqlServerConnectionHelper.ToInt(reader["ID"]);
                    practicient.Nom               = SqlServerConnectionHelper.ToString(reader["Nom"]);
                    practicient.Prenom            = SqlServerConnectionHelper.ToString(reader["Prenom"]);
                    practicient.Specialite1       = SqlServerConnectionHelper.ToString(reader["Specialite1"]);
                    practicient.Ville             = SqlServerConnectionHelper.ToString(reader["Ville"]);
                    practicient.AcceptCarteVitale = SqlServerConnectionHelper.ToBool(reader["accepteCarteVitale"]);
                    practicient.SecteurTarifaire  = SqlServerConnectionHelper.ToString(reader["refSecteurTarifaire"]);
                    practicient.Adresse           = SqlServerConnectionHelper.ToString(reader["Adresse"]);
                    practicient.CP                = SqlServerConnectionHelper.ToInt(reader["CP"]);

                    result.Add(practicient);
                }
            }

            return(result);
        }
        public void RunHandler()
        {
            HTTPManager.Logger.Information("HTTP2Handler", "Processing thread up and running!");

            Thread.CurrentThread.Name = "HTTP2 Process";

            PlatformSupport.Threading.ThreadedRunner.RunLongLiving(ReadThread);

            try
            {
                bool atLeastOneStreamHasAFrameToSend = true;

                this.HPACKEncoder = new HPACKEncoder(this.settings);

                // https://httpwg.org/specs/rfc7540.html#InitialWindowSize
                // The connection flow-control window is also 65,535 octets.
                this.remoteWindow = this.settings.RemoteSettings[HTTP2Settings.INITIAL_WINDOW_SIZE];

                // we want to pack as many data as we can in one tcp segment, but setting the buffer's size too high
                //  we might keep data too long and send them in bursts instead of in a steady stream.
                // Keeping it too low might result in a full tcp segment and one with very low payload
                // Is it possible that one full tcp segment sized buffer would be the best, or multiple of it.
                // It would keep the network busy without any fragments. The ethernet layer has a maximum of 1500 bytes,
                // but there's two layers of 20 byte headers each, so as a theoretical maximum it's 1500-20-20 bytes.
                // On the other hand, if the buffer is small (1-2), that means that for larger data, we have to do a lot
                // of system calls, in that case a larger buffer might be better. Still, if we are not cpu bound,
                // a well saturated network might serve us better.
                using (WriteOnlyBufferedStream bufferedStream = new WriteOnlyBufferedStream(this.conn.connector.Stream, 1024 * 1024 /*1500 - 20 - 20*/))
                {
                    // The client connection preface starts with a sequence of 24 octets
                    bufferedStream.Write(MAGIC, 0, MAGIC.Length);

                    // This sequence MUST be followed by a SETTINGS frame (Section 6.5), which MAY be empty.
                    // The client sends the client connection preface immediately upon receipt of a
                    // 101 (Switching Protocols) response (indicating a successful upgrade)
                    // or as the first application data octets of a TLS connection

                    // Set streams' initial window size to its maximum.
                    this.settings.InitiatedMySettings[HTTP2Settings.INITIAL_WINDOW_SIZE]    = HTTPManager.HTTP2Settings.InitialStreamWindowSize;
                    this.settings.InitiatedMySettings[HTTP2Settings.MAX_CONCURRENT_STREAMS] = HTTPManager.HTTP2Settings.MaxConcurrentStreams;
                    this.settings.SendChanges(this.outgoingFrames);

                    // The default window size for the whole connection is 65535 bytes,
                    // but we want to set it to the maximum possible value.
                    Int64 diff = HTTPManager.HTTP2Settings.InitialConnectionWindowSize - 65535;
                    if (diff > 0)
                    {
                        this.outgoingFrames.Add(HTTP2FrameHelper.CreateWindowUpdateFrame(0, (UInt32)diff));
                    }

                    this.pingFrequency = HTTPManager.HTTP2Settings.PingFrequency;

                    while (this.isRunning)
                    {
                        if (!atLeastOneStreamHasAFrameToSend)
                        {
                            // buffered stream will call flush automatically if its internal buffer is full.
                            // But we have to make it sure that we flush remaining data before we go to sleep.
                            bufferedStream.Flush();

                            // Wait until we have to send the next ping, OR a new frame is received on the read thread.
                            //   Sent      Now  Sent+frequency
                            //-----|--------|----|------------
                            int wait = (int)((this.lastPingSent + this.pingFrequency) - DateTime.UtcNow).TotalMilliseconds;

                            wait = (int)Math.Min(wait, this.MaxGoAwayWaitTime.TotalMilliseconds);

                            if (wait >= 1)
                            {
                                if (HTTPManager.Logger.Level <= Logger.Loglevels.All)
                                {
                                    HTTPManager.Logger.Information("HTTP2Handler", string.Format("Sleeping for {0:N0}ms", wait));
                                }
                                this.newFrameSignal.WaitOne(wait);
                            }
                        }

                        DateTime now = DateTime.UtcNow;

                        if (now - this.lastPingSent >= this.pingFrequency)
                        {
                            this.lastPingSent = now;

                            var frame = HTTP2FrameHelper.CreatePingFrame(HTTP2PingFlags.None);
                            BufferHelper.SetLong(frame.Payload, 0, now.Ticks);

                            this.outgoingFrames.Add(frame);
                        }

                        // Process received frames
                        HTTP2FrameHeaderAndPayload header;
                        while (this.newFrames.TryDequeue(out header))
                        {
                            if (header.StreamId > 0)
                            {
                                HTTP2Stream http2Stream = FindStreamById(header.StreamId);

                                // Add frame to the stream, so it can process it when its Process function is called
                                if (http2Stream != null)
                                {
                                    http2Stream.AddFrame(header, this.outgoingFrames);
                                }
                                else
                                {
                                    // Error? It's possible that we closed and removed the stream while the server was in the middle of sending frames
                                    //HTTPManager.Logger.Warning("HTTP2Handler", string.Format("No stream found for id: {0}! Can't deliver frame: {1}", header.StreamId, header));
                                }
                            }
                            else
                            {
                                switch (header.Type)
                                {
                                case HTTP2FrameTypes.SETTINGS:
                                    this.settings.Process(header, this.outgoingFrames);
                                    break;

                                case HTTP2FrameTypes.PING:
                                    var pingFrame = HTTP2FrameHelper.ReadPingFrame(header);

                                    // if it wasn't an ack for our ping, we have to send one
                                    if ((pingFrame.Flags & HTTP2PingFlags.ACK) == 0)
                                    {
                                        var frame = HTTP2FrameHelper.CreatePingFrame(HTTP2PingFlags.ACK);
                                        Array.Copy(pingFrame.OpaqueData, 0, frame.Payload, 0, pingFrame.OpaqueDataLength);

                                        this.outgoingFrames.Add(frame);
                                    }
                                    break;

                                case HTTP2FrameTypes.WINDOW_UPDATE:
                                    var windowUpdateFrame = HTTP2FrameHelper.ReadWindowUpdateFrame(header);
                                    this.remoteWindow += windowUpdateFrame.WindowSizeIncrement;
                                    break;

                                case HTTP2FrameTypes.GOAWAY:
                                    // parse the frame, so we can print out detailed information
                                    HTTP2GoAwayFrame goAwayFrame = HTTP2FrameHelper.ReadGoAwayFrame(header);

                                    HTTPManager.Logger.Warning("HTTP2Handler", "Received GOAWAY frame: " + goAwayFrame.ToString());

                                    string msg = string.Format("Server closing the connection! Error code: {0} ({1})", goAwayFrame.Error, goAwayFrame.ErrorCode);
                                    for (int i = 0; i < this.clientInitiatedStreams.Count; ++i)
                                    {
                                        this.clientInitiatedStreams[i].Abort(msg);
                                    }

                                    // set the running flag to false, so the thread can exit
                                    this.isRunning = false;

                                    this.conn.State = HTTPConnectionStates.Closed;
                                    break;

                                case HTTP2FrameTypes.ALT_SVC:
                                    //HTTP2AltSVCFrame altSvcFrame = HTTP2FrameHelper.ReadAltSvcFrame(header);

                                    // Implement
                                    //HTTPManager.EnqueuePluginEvent(new PluginEventInfo(PluginEvents.AltSvcHeader, new AltSvcEventInfo(altSvcFrame.Origin, ))
                                    break;
                                }
                            }
                        }

                        UInt32 maxConcurrentStreams = Math.Min(HTTPManager.HTTP2Settings.MaxConcurrentStreams, this.settings.RemoteSettings[HTTP2Settings.MAX_CONCURRENT_STREAMS]);

                        // pre-test stream count to lock only when truly needed.
                        if (this.clientInitiatedStreams.Count < maxConcurrentStreams && this.isRunning)
                        {
                            // grab requests from queue
                            HTTPRequest request;
                            while (this.clientInitiatedStreams.Count < maxConcurrentStreams && this.requestQueue.TryDequeue(out request))
                            {
#if !BESTHTTP_DISABLE_CACHING
                                // If possible load the full response from cache.
                                if (Caching.HTTPCacheService.IsCachedEntityExpiresInTheFuture(request))
                                {
                                    PlatformSupport.Threading.ThreadedRunner.RunShortLiving <HTTP2Handler, HTTPRequest>((handler, req) =>
                                    {
                                        if (ConnectionHelper.TryLoadAllFromCache("HTTP2Handler", req))
                                        {
                                            req.State = HTTPRequestStates.Finished;
                                        }
                                        else
                                        {
                                            // If for some reason it couldn't load we place back the request to the queue.

                                            handler.requestQueue.Enqueue(req);
                                            handler.newFrameSignal.Set();
                                        }
                                    }, this, request);
                                }
                                else
#endif
                                {
                                    // create a new stream
                                    var newStream = new HTTP2Stream(this.settings, this.HPACKEncoder);

                                    // process the request
                                    newStream.Assign(request);

                                    this.clientInitiatedStreams.Add(newStream);
                                }
                            }
                        }

                        // send any settings changes
                        this.settings.SendChanges(this.outgoingFrames);

                        atLeastOneStreamHasAFrameToSend = false;

                        // process other streams
                        // Room for improvement Streams should be processed by their priority!
                        for (int i = 0; i < this.clientInitiatedStreams.Count; ++i)
                        {
                            var stream = this.clientInitiatedStreams[i];
                            stream.Process(this.outgoingFrames);

                            // remove closed, empty streams (not enough to check the closed flag, a closed stream still can contain frames to send)
                            if (stream.State == HTTP2StreamStates.Closed && !stream.HasFrameToSend)
                            {
                                this.clientInitiatedStreams.RemoveAt(i--);
                                stream.Removed();
                            }

                            atLeastOneStreamHasAFrameToSend |= stream.HasFrameToSend;

                            this.lastInteraction = DateTime.UtcNow;
                        }

                        // If we encounter a data frame that too large for the current remote window, we have to stop
                        // sending all data frames as we could send smaller data frames before the large ones.
                        // Room for improvement: An improvement would be here to stop data frame sending per-stream.
                        bool haltDataSending = false;

                        if (this.ShutdownType == ShutdownTypes.Running && now - this.lastInteraction >= HTTPManager.HTTP2Settings.MaxIdleTime)
                        {
                            this.lastInteraction = DateTime.UtcNow;
                            HTTPManager.Logger.Information("HTTP2Handler", "Reached idle time, sending GoAway frame!");
                            this.outgoingFrames.Add(HTTP2FrameHelper.CreateGoAwayFrame(0, HTTP2ErrorCodes.NO_ERROR));
                            this.goAwaySentAt = DateTime.UtcNow;
                        }

                        // https://httpwg.org/specs/rfc7540.html#GOAWAY
                        // Endpoints SHOULD always send a GOAWAY frame before closing a connection so that the remote peer can know whether a stream has been partially processed or not.
                        if (this.ShutdownType == ShutdownTypes.Gentle)
                        {
                            HTTPManager.Logger.Information("HTTP2Handler", "Connection abort requested, sending GoAway frame!");

                            this.outgoingFrames.Clear();
                            this.outgoingFrames.Add(HTTP2FrameHelper.CreateGoAwayFrame(0, HTTP2ErrorCodes.NO_ERROR));
                            this.goAwaySentAt = DateTime.UtcNow;
                        }

                        if (this.isRunning && now - goAwaySentAt >= this.MaxGoAwayWaitTime)
                        {
                            HTTPManager.Logger.Information("HTTP2Handler", "No GoAway frame received back. Really quitting now!");
                            this.isRunning = false;
                            conn.State     = HTTPConnectionStates.Closed;
                        }

                        uint streamWindowUpdates = 0;

                        // Go through all the collected frames and send them.
                        for (int i = 0; i < this.outgoingFrames.Count; ++i)
                        {
                            var frame = this.outgoingFrames[i];

                            if (HTTPManager.Logger.Level <= Logger.Loglevels.All && frame.Type != HTTP2FrameTypes.DATA /*&& frame.Type != HTTP2FrameTypes.PING*/)
                            {
                                HTTPManager.Logger.Information("HTTP2Handler", "Sending frame: " + frame.ToString());
                            }

                            // post process frames
                            switch (frame.Type)
                            {
                            case HTTP2FrameTypes.DATA:
                                if (haltDataSending)
                                {
                                    continue;
                                }

                                // if the tracked remoteWindow is smaller than the frame's payload, we stop sending
                                // data frames until we receive window-update frames
                                if (frame.PayloadLength > this.remoteWindow)
                                {
                                    haltDataSending = true;
                                    HTTPManager.Logger.Warning("HTTP2Handler", string.Format("Data sending halted for this round. Remote Window: {0:N0}, frame: {1}", this.remoteWindow, frame.ToString()));
                                    continue;
                                }

                                break;

                            case HTTP2FrameTypes.WINDOW_UPDATE:
                                if (frame.StreamId > 0)
                                {
                                    streamWindowUpdates += BufferHelper.ReadUInt31(frame.Payload, 0);
                                }
                                break;
                            }

                            this.outgoingFrames.RemoveAt(i--);

                            using (var buffer = HTTP2FrameHelper.HeaderAsBinary(frame))
                                bufferedStream.Write(buffer.Data, 0, buffer.Length);

                            if (frame.PayloadLength > 0)
                            {
                                bufferedStream.Write(frame.Payload, (int)frame.PayloadOffset, (int)frame.PayloadLength);

                                if (!frame.DontUseMemPool)
                                {
                                    BufferPool.Release(frame.Payload);
                                }
                            }

                            if (frame.Type == HTTP2FrameTypes.DATA)
                            {
                                this.remoteWindow -= frame.PayloadLength;
                            }
                        }

                        if (streamWindowUpdates > 0)
                        {
                            var frame = HTTP2FrameHelper.CreateWindowUpdateFrame(0, streamWindowUpdates);

                            if (HTTPManager.Logger.Level <= Logger.Loglevels.All)
                            {
                                HTTPManager.Logger.Information("HTTP2Handler", "Sending frame: " + frame.ToString());
                            }

                            using (var buffer = HTTP2FrameHelper.HeaderAsBinary(frame))
                                bufferedStream.Write(buffer.Data, 0, buffer.Length);

                            bufferedStream.Write(frame.Payload, (int)frame.PayloadOffset, (int)frame.PayloadLength);
                        }
                    } // while (this.isRunning)

                    bufferedStream.Flush();
                }
            }
            catch (Exception ex)
            {
                // Log out the exception if it's a non-expected one.
                if (this.ShutdownType == ShutdownTypes.Running && this.goAwaySentAt == DateTime.MaxValue)
                {
                    HTTPManager.Logger.Exception("HTTP2Handler", "Sender thread", ex);
                }
            }
            finally
            {
                if (this.ShutdownType == ShutdownTypes.Running)
                {
                    // Room for improvement: Do something with the unfinished requests...
                }
                else
                {
                    this.requestQueue.Clear();
                }

                HTTPManager.Logger.Information("HTTP2Handler", "Sender thread closing");
            }

            if (this.conn.connector.Stream != null)
            {
                try
                {
                    this.conn.connector.Stream.Dispose();
                    //this.conn.connector.Stream = null;
                }
                catch
                { }
            }

            if (Interlocked.Increment(ref this.threadExitCount) == 2 /*&& this.ShutdownType != ShutdownTypes.Immediate*/)
            {
                ConnectionEventHelper.EnqueueConnectionEvent(new ConnectionEventInfo(this.conn, HTTPConnectionStates.Closed));
            }
        }
 public static void SendMessage(bool showOre, bool showIngot, bool showComponent, bool showAmmo, bool showTools, bool showSupplies, bool showGasses, string findMarket)
 {
     ConnectionHelper.SendMessageToServer(new MessageMarketPriceList {
         ShowAmmo = showAmmo, ShowComponent = showComponent, ShowIngot = showIngot, ShowOre = showOre, ShowTools = showTools, ShowSupplies = showSupplies, ShowGasses = showGasses, FindMarket = findMarket
     });
 }
 public IQueryable <BaseDocument> Get()
 {
     Session = ConnectionHelper.CreateSession();
     return(Session.Query <BaseDocument>());
 }
Exemple #22
0
        /// <summary>
        /// Converts a <see cref="CircuitDocument"/> to an <see cref="IODocument"/>.
        /// </summary>
        /// <param name="document">The CircuitDocument to convert.</param>
        /// <returns>An IODocument constructed from the CircuitDocument.</returns>
        public static IODocument ToIODocument(this CircuitDocument document, out IDictionary <IOComponentType, EmbedComponentData> embedComponents)
        {
            IODocument ioDocument = new IODocument();

            ioDocument.Size = document.Size;

            // Set metadata
            ioDocument.Metadata = document.Metadata;

            // Get connections
            Dictionary <Component, Dictionary <string, string> > connections = ConnectionHelper.RemoveWires(document);

            // Generate types
            Dictionary <ComponentIdentifier, IOComponentType> componentTypes = new Dictionary <ComponentIdentifier, IOComponentType>();

            foreach (Component component in document.Components)
            {
                if (ComponentHelper.IsWire(component))
                {
                    continue; // Skip wires
                }
                ComponentIdentifier identifier = new ComponentIdentifier(component.Description, component.Configuration());
                if (!componentTypes.ContainsKey(identifier))
                {
                    IOComponentType ioType = new IOComponentType(component.Description.Metadata.ImplementSet,
                                                                 (identifier.Configuration != null && !String.IsNullOrEmpty(identifier.Configuration.ImplementationName) ? identifier.Configuration.ImplementationName : component.Description.Metadata.ImplementItem));
                    ioType.Name = component.Description.ComponentName;
                    ioType.GUID = component.Description.Metadata.GUID;
                    componentTypes.Add(identifier, ioType);
                }
            }

            // Add visible components
            int idCounter = 0; // generate component IDs

            foreach (IComponentElement component in document.Elements.Where(component => component is IComponentElement && !ComponentHelper.IsWire(component)))
            {
                IOComponent ioComponent = new IOComponent();
                ioComponent.ID          = idCounter.ToString();
                ioComponent.Size        = component.Size;
                ioComponent.Location    = new Point(component.Location.X, component.Location.Y);
                ioComponent.IsFlipped   = component.IsFlipped;
                ioComponent.Orientation = component.Orientation;
                IOComponentType ioType = new IOComponentType(component.ImplementationCollection, component.ImplementationItem);

                if (component is Component)
                {
                    Component cComponent = component as Component;
                    ioType.Name      = cComponent.Description.ComponentName;
                    ioType.GUID      = cComponent.Description.Metadata.GUID;
                    ioComponent.Type = ioType;

                    // Set connections
                    if (connections.ContainsKey(cComponent))
                    {
                        foreach (var connection in connections[cComponent])
                        {
                            ioComponent.Connections.Add(connection.Key, connection.Value);
                        }
                    }
                }

                // Set properties
                foreach (var property in component.Properties)
                {
                    ioComponent.Properties.Add(new IOComponentProperty(property.Key, property.Value, true)); // TODO: implement IsStandard
                }
                ioDocument.Components.Add(ioComponent);

                idCounter++;
            }

            // Add unavailable components
            foreach (DisabledComponent component in document.DisabledComponents)
            {
                Point?location = null;
                if (component.Location.HasValue)
                {
                    location = new Point(component.Location.Value.X, component.Location.Value.Y);
                }

                IOComponent ioComponent = new IOComponent();
                ioComponent.ID          = idCounter.ToString();
                ioComponent.Location    = location;
                ioComponent.Size        = component.Size;
                ioComponent.IsFlipped   = component.IsFlipped;
                ioComponent.Orientation = component.Orientation;

                IOComponentType ioType = new IOComponentType(component.ImplementationCollection, component.ImplementationItem);

                // Set name
                if (!String.IsNullOrEmpty(component.Name))
                {
                    ioType.Name = component.Name;
                }

                // Set GUID
                if (component.GUID.HasValue)
                {
                    ioType.GUID = component.GUID.Value;
                }

                ioComponent.Type = ioType;

                // Set properties
                foreach (var property in component.Properties)
                {
                    ioComponent.Properties.Add(new IOComponentProperty(property.Key, property.Value, true));
                }

                ioDocument.Components.Add(ioComponent);

                idCounter++;
            }

            // Add wires
            foreach (IComponentElement wire in document.Components.Where(component => ComponentHelper.IsWire(component)))
            {
                IOWire ioWire = new IOWire(new Point(wire.Location.X, wire.Location.Y), wire.Size, wire.Orientation);
                ioDocument.Wires.Add(ioWire);
            }

            // Embed components
            embedComponents = new Dictionary <IOComponentType, EmbedComponentData>();
            foreach (EmbedDescription embedItem in document.Metadata.EmbedComponents.Where(item => item.IsEmbedded == true))
            {
                if (!String.IsNullOrEmpty(embedItem.Description.Source.Path) && System.IO.File.Exists(embedItem.Description.Source.Path))
                {
                    EmbedComponentData embedData = new EmbedComponentData();
                    embedData.Stream        = System.IO.File.OpenRead(embedItem.Description.Source.Path);
                    embedData.FileExtension = System.IO.Path.GetExtension(embedItem.Description.Source.Path);

                    switch (embedData.FileExtension)
                    {
                    case ".xml":
                        embedData.ContentType = "application/xml";
                        break;

                    case ".cdcom":
                        embedData.ContentType = IO.CDDX.ContentTypeNames.BinaryComponent;
                        break;
                    }

                    List <IOComponentType> associatedTypes = new List <IOComponentType>();
                    foreach (var item in componentTypes)
                    {
                        if (item.Key.Description == embedItem.Description && !embedComponents.ContainsKey(item.Value))
                        {
                            embedComponents.Add(item.Value, embedData);
                        }
                    }
                }
            }

            return(ioDocument);
        }
    /// <summary>
    /// Figure out using the Join Table which categories need to be removed and which added
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void SaveToJoinTable()
    {
        SetPossibleAndSelectedCategories();

        // Do check of min/max here
        if (MinimumCategories > 0 && SelectedCategories.Count() < MinimumCategories)
        {
            AddError("Must select at least " + MinimumCategories + " " + (MinimumCategories == 1 ? "category" : "categories"));
            return;
        }
        if (MaximumCategories > 0 && SelectedCategories.Count() > MaximumCategories)
        {
            AddError("Can select no more than " + MaximumCategories + " " + (MaximumCategories == 1 ? "category" : "categories"));
            return;
        }

        // filter with only the possible categories
        DataClassInfo JoinTableClassInfo = DataClassInfoProvider.GetDataClassInfo(JoinTableName);

        if (JoinTableClassInfo != null)
        {
            List <int> DocumentCategoryIds = new List <int>();

            // Get all the categories the current entity has
            int          totalRecords        = 0;
            var          currentCategoriesDS = ConnectionHelper.ExecuteQuery(JoinTableName + ".selectall", null, string.Format("{0} = '{1}'", JoinTableLeftFieldName, CurrentItemIdentification), null, -1, null, -1, -1, ref totalRecords);
            CategoryInfo catObject           = null;
            string       FieldSaveColumnName = "";
            // Convert to CategoryID
            switch (FieldSaveModeVal)
            {
            case FieldSaveType.ID:
                FieldSaveColumnName = "CategoryID";
                break;

            case FieldSaveType.GUID:
                FieldSaveColumnName = "CategoryGUID";
                break;

            case FieldSaveType.CategoryName:
                FieldSaveColumnName = "CategoryName";
                break;
            }

            foreach (DataRow dr in currentCategoriesDS.Tables[0].Rows)
            {
                // Convert to CategoryID
                switch (FieldSaveModeVal)
                {
                case FieldSaveType.ID:
                    catObject = CategoryInfoProvider.GetCategoryInfo(ValidationHelper.GetInteger(dr[JoinTableRightFieldName], 0));
                    if (catObject != null)
                    {
                        DocumentCategoryIds.Add(catObject.CategoryID);
                    }
                    break;

                case FieldSaveType.GUID:
                    var ClassObject = CategoryInfoProvider.GetCategories().WhereEquals("CategoryGUID", ValidationHelper.GetGuid(dr[JoinTableRightFieldName], new Guid())).FirstOrDefault();
                    if (ClassObject != null)
                    {
                        DocumentCategoryIds.Add(ValidationHelper.GetInteger(ClassObject["CategoryID"], 0));
                    }
                    break;

                case FieldSaveType.CategoryName:
                    catObject = CategoryInfoProvider.GetCategoryInfo(ValidationHelper.GetString(dr[JoinTableRightFieldName], ""), SiteContext.CurrentSiteName);
                    if (catObject != null)
                    {
                        DocumentCategoryIds.Add(catObject.CategoryID);
                    }
                    break;
                }
            }

            // Find IDs we need to add and remove.
            List <int> NotSelectedIds = PossibleCategoryIDs.Except(SelectedCategoryIDs).ToList();
            List <int> DeselectIds    = DocumentCategoryIds.Intersect(NotSelectedIds).ToList();
            List <int> SelectIds      = SelectedCategoryIDs.Except(DocumentCategoryIds).ToList();

            if (DeselectIds.Count > 0)
            {
                foreach (int DeselectId in DeselectIds)
                {
                    if (JoinTableClassInfo.ClassIsCustomTable)
                    {
                        CustomTableItemProvider.GetItems(JoinTableClassInfo.ClassName).WhereEquals(JoinTableLeftFieldName, CurrentItemIdentification)
                        .WhereEquals(JoinTableRightFieldName, CategoryInfoProvider.GetCategoryInfo(DeselectId).GetValue(FieldSaveColumnName))
                        .ToList().ForEach(x => ((CustomTableItem)x).Delete());
                    }
                    else
                    {
                        new ObjectQuery(JoinTableClassInfo.ClassName)
                        .WhereEquals(JoinTableLeftFieldName, CurrentItemIdentification)
                        .WhereEquals(JoinTableRightFieldName, CategoryInfoProvider.GetCategoryInfo(DeselectId).GetValue(FieldSaveColumnName))
                        .ToList().ForEach(x => x.Delete());
                    }
                }
            }
            if (SelectIds.Count > 0)
            {
                foreach (int SelectId in SelectIds)
                {
                    if (JoinTableClassInfo.ClassIsCustomTable)
                    {
                        CustomTableItem newCustomTableItem = CustomTableItem.New(JoinTableName);
                        SetBaseInfoItemValues(newCustomTableItem, CategoryInfoProvider.GetCategoryInfo(SelectId).GetValue(FieldSaveColumnName), JoinTableClassInfo.ClassName);
                        InsertObjectHandler(newCustomTableItem);
                    }
                    else
                    {
                        // Create a dynamic BaseInfo object of the right type.
                        var JoinTableClassFactory = new InfoObjectFactory(JoinTableClassInfo.ClassName);
                        if (JoinTableClassFactory.Singleton == null)
                        {
                            AddError("Class does not have TypeInfo and TypeInfoProvider generated.  Must generate " + JoinTableClassInfo.ClassName + " Code before can bind.");
                            return;
                        }
                        BaseInfo newJoinObj = ((BaseInfo)JoinTableClassFactory.Singleton);
                        SetBaseInfoItemValues(newJoinObj, CategoryInfoProvider.GetCategoryInfo(SelectId).GetValue(FieldSaveColumnName), JoinTableClassInfo.ClassName);
                        InsertObjectHandler(newJoinObj);
                    }
                }
            }

            AddConfirmation(string.Format("{0} Categories Added, {1} Categories Removed.", SelectIds.Count, DeselectIds.Count));
        }
    }
Exemple #24
0
        private IEnumerable <KeyValuePair <string, string> > GetMetricData()
        {
            string stringData = null;
            IEnumerable <KeyValuePair <string, string> > tupleData = null;

            // Gather data for each row, return special message if data is null
            switch (MetricCodeName)
            {
            // Categories
            case MetricDataEnum.support_metrics:
            case MetricDataEnum.support_metrics_system:
            case MetricDataEnum.support_metrics_environment:
            case MetricDataEnum.support_metrics_counters:
            case MetricDataEnum.support_metrics_ecommerce:
            case MetricDataEnum.support_metrics_tasks:
            case MetricDataEnum.support_metrics_eventlog:
                return(null);

                #region System

            case MetricDataEnum.support_metrics_system_version:
                stringData = CMSVersion.GetVersion(true, true, true, true);
                break;

            case MetricDataEnum.support_metrics_system_appname:
                stringData = SettingsHelper.AppSettings["CMSApplicationName"];
                break;

            case MetricDataEnum.support_metrics_system_instancename:
                stringData = SystemContext.InstanceName;
                break;

            case MetricDataEnum.support_metrics_system_physicalpath:
                stringData = SystemContext.WebApplicationPhysicalPath;
                break;

            case MetricDataEnum.support_metrics_system_apppath:
                stringData = SystemContext.ApplicationPath;
                break;

            case MetricDataEnum.support_metrics_system_uiculture:
                stringData = LocalizationContext.CurrentUICulture.CultureName;
                break;

            case MetricDataEnum.support_metrics_system_installtype:
                stringData = SystemContext.IsWebApplicationProject ? "Web App" : "Web site";
                break;

            case MetricDataEnum.support_metrics_system_portaltemplatepage:
                stringData = URLHelper.PortalTemplatePage;
                break;

            case MetricDataEnum.support_metrics_system_timesinceapprestart:
                stringData = (DateTime.Now - CMSApplication.ApplicationStart).ToString(@"dd\:hh\:mm\:ss");
                break;

            case MetricDataEnum.support_metrics_system_discoveredassemblies:
                tupleData = AssemblyDiscoveryHelper.GetAssemblies(true).Select((a, i) => GetKeyValuePair(i, a.FullName));
                break;

            case MetricDataEnum.support_metrics_system_targetframework:
                HttpRuntimeSection httpRuntime = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
                stringData = httpRuntime.TargetFramework;
                break;

            case MetricDataEnum.support_metrics_system_authmode:
                AuthenticationSection Authentication = ConfigurationManager.GetSection("system.web/authentication") as AuthenticationSection;
                stringData = Authentication?.Mode.ToString();
                break;

            case MetricDataEnum.support_metrics_system_sessionmode:
                SessionStateSection SessionState = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;
                stringData = SessionState?.Mode.ToString();
                break;

            case MetricDataEnum.support_metrics_system_debugmode:
                CompilationSection Compilation = ConfigurationManager.GetSection("system.web/compilation") as CompilationSection;
                stringData = Compilation?.Debug.ToString();
                break;

            case MetricDataEnum.support_metrics_system_runallmanagedmodules:
                var xmlDoc = new System.Xml.XmlDocument();
                xmlDoc.Load(URLHelper.GetPhysicalPath("~/Web.config"));
                stringData = xmlDoc.SelectSingleNode("/configuration/system.webServer/modules").Attributes["runAllManagedModulesForAllRequests"]?.Value;
                break;

                #endregion System

                #region Environment

            case MetricDataEnum.support_metrics_environment_trustlevel:

                AspNetHostingPermissionLevel trustLevel = AspNetHostingPermissionLevel.None;

                if (!SystemContext.IsWebSite)
                {
                    trustLevel = AspNetHostingPermissionLevel.Unrestricted;
                }

                // Check the trust level by evaluation of levels
                foreach (AspNetHostingPermissionLevel permissionLevel in new[] {
                    AspNetHostingPermissionLevel.Unrestricted,
                    AspNetHostingPermissionLevel.High,
                    AspNetHostingPermissionLevel.Medium,
                    AspNetHostingPermissionLevel.Low,
                    AspNetHostingPermissionLevel.Minimal
                })
                {
                    try
                    {
                        new AspNetHostingPermission(permissionLevel).Demand();
                    }
                    catch (SecurityException)
                    {
                        continue;
                    }

                    trustLevel = permissionLevel;
                    break;
                }

                stringData = trustLevel.ToString();
                break;

            case MetricDataEnum.support_metrics_environment_iisversion:
                stringData = MetricServerVariables["SERVER_SOFTWARE"];
                break;

            case MetricDataEnum.support_metrics_environment_https:
                stringData = MetricServerVariables["HTTPS"];
                break;

            case MetricDataEnum.support_metrics_environment_windowsversion:
                using (RegistryKey versionKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
                {
                    var productName  = versionKey?.GetValue("ProductName");
                    var currentBuild = versionKey?.GetValue("CurrentBuild");
                    var releaseId    = versionKey?.GetValue("ReleaseId");

                    stringData = String.Format("{0}, build {1}, release {2}", productName.ToString(), currentBuild.ToString(), releaseId.ToString());
                }
                break;

            case MetricDataEnum.support_metrics_environment_netversion:
                using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"))
                {
                    var keyValue = ndpKey?.GetValue("Release");
                    if (keyValue != null)
                    {
                        var releaseKey = (int)keyValue;
                        if (releaseKey >= 461808)
                        {
                            stringData = "4.7.2 or later";
                        }
                        else
                        if (releaseKey >= 461308)
                        {
                            stringData = "4.7.1";
                        }
                        else
                        if (releaseKey >= 460798)
                        {
                            stringData = "4.7";
                        }
                        else
                        if (releaseKey >= 394802)
                        {
                            stringData = "4.6.2";
                        }
                        else
                        if (releaseKey >= 394254)
                        {
                            stringData = "4.6.1";
                        }
                        else
                        if (releaseKey >= 393295)
                        {
                            stringData = "4.6";
                        }
                        else
                        if (releaseKey >= 379893)
                        {
                            stringData = "4.5.2";
                        }
                        else
                        if (releaseKey >= 378675)
                        {
                            stringData = "4.5.1";
                        }
                        else
                        if (releaseKey >= 378389)
                        {
                            stringData = "4.5";
                        }
                    }
                }
                break;

            case MetricDataEnum.support_metrics_environment_sqlserverversion:
                var dtm = new TableManager(null);
                stringData = dtm.DatabaseServerVersion;
                break;

            case MetricDataEnum.support_metrics_environment_azure:
                var azureStats = new Dictionary <string, string>(4)
                {
                    { "Is a Cloud Service", (SettingsHelper.AppSettings["CMSAzureProject"] == "true").ToString("false") },
                    { "Is file system on Azure", (SettingsHelper.AppSettings["CMSExternalStorageName"] == "azure").ToString("false") },
                    { "Azure storage account", SettingsHelper.AppSettings["CMSAzureAccountName"] ?? String.Empty },
                    { "Azure CDN endpoint", SettingsHelper.AppSettings["CMSAzureCDNEndpoint"] ?? String.Empty }
                };

                tupleData = azureStats.Select(s => GetKeyValuePair(s.Key, s.Value));
                break;

            case MetricDataEnum.support_metrics_environment_amazon:
                var amazonStats = new Dictionary <string, string>(3)
                {
                    { "Is file system on Amazon", (SettingsHelper.AppSettings["CMSExternalStorageName"] == "amazon").ToString() },
                    { "Amazon bucket name", SettingsHelper.AppSettings["CMSAmazonBucketName"] ?? String.Empty },
                    { "Amazon public access", SettingsHelper.AppSettings["CMSAmazonPublicAccess"] ?? String.Empty },
                };

                tupleData = amazonStats.Select(s => GetKeyValuePair(s.Key, s.Value));
                break;

            case MetricDataEnum.support_metrics_environment_services:
                tupleData = ServiceManager.GetServices().Select(s => GetKeyValuePair(s.ServiceName, s.Status));
                break;

                #endregion Environment

                #region Counters

            case MetricDataEnum.support_metrics_counters_webfarmservers:
                stringData = CoreServices.WebFarm.GetEnabledServerNames().Count().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_stagingservers:
                stringData = ServerInfoProvider.GetServers().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_pagemostchildren:
                CMS.DocumentEngine.TreeProvider tree = new CMS.DocumentEngine.TreeProvider();

                var pageWithMostChildren = tree.SelectNodes().OnCurrentSite().Published()
                                           .ToDictionary(n => n, n => n.Children.Count)
                                           .Aggregate((l, r) => l.Value > r.Value ? l : r);

                tupleData = new[] { GetKeyValuePair(URLHelper.GetAbsoluteUrl("~" + pageWithMostChildren.Key.NodeAliasPath), pageWithMostChildren.Value) };
                break;

            case MetricDataEnum.support_metrics_counters_modules:
                stringData = ResourceInfoProvider.GetResources().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_medialibraries:
                stringData = MediaLibraryInfoProvider.GetMediaLibraries().WhereNull("LibraryGroupID").GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_activities:
                stringData = ActivityInfoProvider.GetActivities().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_contacts:
                stringData = ContactInfoProvider.GetContacts().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_contactgroups:
                stringData = ContactGroupInfoProvider.GetContactGroups().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_omrules:
                stringData = RuleInfoProvider.GetRules().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_products:
                stringData = SKUInfoProvider.GetSKUs(SiteContext.CurrentSiteID).WhereNull("SKUOptionCategoryID").GetCount().ToString();
                break;

                #endregion Counters

                #region Tasks

            case MetricDataEnum.support_metrics_tasks_webfarm:
                stringData = WebFarmTaskInfoProvider.GetWebFarmTasks()
                             .WhereLessThan("TaskCreated", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_staging:
                stringData = StagingTaskInfoProvider.GetTasks()
                             .WhereLessThan("TaskTime", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_integration:
                stringData = IntegrationTaskInfoProvider.GetIntegrationTasks()
                             .WhereLessThan("TaskTime", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_scheduled:
                stringData = TaskInfoProvider.GetTasks()
                             .WhereTrue("TaskDeleteAfterLastRun")
                             .WhereLessThan("TaskNextRunTime", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_search:
                stringData = SearchTaskInfoProvider.GetSearchTasks()
                             .WhereLessThan("SearchTaskCreated", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_email:
                stringData = EmailInfoProvider.GetEmailCount("EmailStatus = 1 AND EmailLastSendResult IS NOT NULL").ToString();
                break;

                #endregion Tasks

                #region Event log

            case MetricDataEnum.support_metrics_eventlog_macroerrors:
                var macroErrors = EventLogProvider.GetEvents()
                                  .WhereEquals("Source", "MacroResolver")
                                  .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                  .OrderByDescending("EventTime")
                                  .TopN(10);

                tupleData = macroErrors.Select(e =>
                                               GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                               e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                               );
                break;

            case MetricDataEnum.support_metrics_eventlog_stagingerrors:
                var stagingErrors = EventLogProvider.GetEvents()
                                    .WhereEquals("Source", "staging")
                                    .WhereIn("EventType", new[] { "E", "W" })
                                    .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                    .OrderByDescending("EventTime")
                                    .TopN(10);

                tupleData = stagingErrors.Select(e =>
                                                 GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                                 e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                                 );
                break;

            case MetricDataEnum.support_metrics_eventlog_searcherrors:
                var searchErrors = EventLogProvider.GetEvents()
                                   .WhereEquals("Source", "search")
                                   .WhereIn("EventType", new[] { "E", "W" })
                                   .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                   .OrderByDescending("EventTime")
                                   .TopN(10);

                tupleData = searchErrors.Select(e =>
                                                GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                                e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                                );
                break;

            case MetricDataEnum.support_metrics_eventlog_contenterrors:
                var contentErrors = EventLogProvider.GetEvents()
                                    .WhereEquals("Source", "content")
                                    .WhereIn("EventType", new[] { "E", "W" })
                                    .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                    .OrderByDescending("EventTime")
                                    .TopN(10);

                tupleData = contentErrors.Select(e =>
                                                 GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                                 e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                                 );
                break;

            case MetricDataEnum.support_metrics_eventlog_exceptions:
                var exceptions = EventLogProvider.GetEvents()
                                 .WhereEquals("EventCode", "exception")
                                 .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                 .OrderByDescending("EventTime")
                                 .TopN(10);

                tupleData = exceptions.Select(e =>
                                              GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                              e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                              );
                break;

            case MetricDataEnum.support_metrics_eventlog_upgrade:

                EventLogInfo upgrade = EventLogProvider.GetEvents().WhereLike("Source", "upgrade%").FirstOrDefault();
                var          version = upgrade?.Source.Split(' ')[2];

                if (!String.IsNullOrEmpty(version))
                {
                    var parameters = new QueryDataParameters
                    {
                        { "@versionnumber", version }
                    };

                    var events = ConnectionHelper.ExecuteQuery("SupportHelper.CustomMetric.checkupgrade", parameters);

                    tupleData = (from DataRow row in events.Tables[0]?.Rows select row)
                                .Select(r => new EventLogInfo(r)).Select(e =>
                                                                         GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                                                         e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                                                         );
                }
                break;

                #endregion Event log
            }

            if (tupleData?.Count() > 0)
            {
                return(tupleData);
            }

            if (stringData != null)
            {
                return(new[] { GetKeyValuePair(0, stringData) });
            }

            return(new[] { GetKeyValuePair(0, ResHelper.GetStringFormat("support.metrics.invalid", MetricDisplayName, MetricCodeName)) });
        }
 /// <summary>
 /// Returns connection string used throughout the application.
 /// </summary>
 public static string GetConnectionString()
 {
     return(ConnectionHelper.GetSqlConnectionString());
 }
Exemple #26
0
 public static void SendMessage(string toUserName, decimal itemQuantity, string itemTypeId, string itemSubTypeName, decimal itemPrice, bool useBankBuyPrice, bool sellToMerchant, bool offerToMarket)
 {
     ConnectionHelper.SendMessageToServer(new MessageBuy {
         FromUserName = toUserName, ItemQuantity = itemQuantity, ItemTypeId = itemTypeId, ItemSubTypeName = itemSubTypeName, ItemPrice = itemPrice, UseBankSellPrice = useBankBuyPrice, BuyFromMerchant = sellToMerchant, FindOnMarket = offerToMarket
     });
 }
Exemple #27
0
        static void Main()
        {
            try
            {
                bool bCreate;
                System.Threading.Mutex mutex = new System.Threading.Mutex(false, "SINGILE_INSTANCE_MUTEX", out bCreate);

                if (!bCreate)
                {
                    MessageBox.Show("程序已经启动!只能运行一个实例", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Application.Exit();
                    return;
                }

                //Xpo连接数据库
                ConnectionHelper.Connect(AutoCreateOption.DatabaseAndSchema);

                //设置应用程序处理异常方式:ThreadException处理
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                //处理UI线程异常
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                //处理非UI线程异常
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                #region 应用程序的主入口点
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                BonusSkins.Register();
                SkinManager.EnableFormSkins();

                //UserLookAndFeel.Default.SetSkinStyle("Darkroom");

                ///// 连接数据库 //////
                SqlAssist.ConnectDb();

                ///// 检查版本  ///////
                //string curNewestVersion = Tools.getNewVersion();
                //if (string.Compare(curNewestVersion, AppInfo.AppVersion) > 0)
                //{
                //	MessageBox.Show("服务器发现更新的版本!系统需要升级", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //	Tools.DownloadNew(curNewestVersion);
                //	SqlAssist.DisConnect();

                //	//启动升级拷贝 //////

                //	try
                //	{
                //		Process.Start("Upgrade.exe", curNewestVersion);
                //	}
                //	catch (Exception e)
                //	{
                //		Console.WriteLine(e.Message);
                //	}

                //	Application.Exit();
                //	return;
                //}


                // 检查 工作站是否进行登记
                Envior.WORKSTATIONID = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath).AppSettings.Settings["workstationID"].Value.ToString();
                string hostname  = string.Empty;
                string ipaddress = string.Empty;
                Tools.GetIpAddress(out hostname, out ipaddress);
                if (!string.IsNullOrEmpty(Envior.WORKSTATIONID))
                {
                    switch (MiscAction.WorkStationIsRegistered(Envior.WORKSTATIONID, hostname, ipaddress))
                    {
                    case 0:                              //未登记
                        XtraMessageBox.Show("此工作站尚未登记!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Application.Exit();
                        return;

                    case 2:                              //主机名不符
                        XtraMessageBox.Show("此工作站【计算机名称】与登记不符!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Application.Exit();
                        return;

                    case 3:                              //ip地址不符
                        XtraMessageBox.Show("此工作站【IP地址】与登记不符!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Application.Exit();
                        return;

                    default:
                        break;
                    }
                }
                else
                {
                    XtraMessageBox.Show("未设置工作站ID!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    Application.Exit();
                    return;
                }

                Application.Run(new Frm_main());
                #endregion
            }
            catch (Exception ex)
            {
                string str = GetExceptionMsg(ex, string.Empty);
                LogUtils.Error(str);
                XtraMessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #28
0
 public void Init()
 {
     this.connectionHelper = new ConnectionHelper();
     this.observerMock = new Mock<IMarketDepthObserver>();
 }
    /// <summary>
    /// Runs edited view or stored procedure.
    /// </summary>
    public void SaveQuery()
    {
        string objName = txtObjName.Text.Trim();
        string body    = txtSQLText.Text.Trim();

        string result = new Validator().NotEmpty(objName, GetString("systbl.viewproc.objectnameempty"))
                        .NotEmpty(body, GetString("systbl.viewproc.bodyempty")).Result;

        if (String.IsNullOrEmpty(result))
        {
            // Use special prefix for user created views or stored procedures
            if (!SystemContext.DevelopmentMode)
            {
                if (State == STATE_CREATE_VIEW)
                {
                    objName = VIEW_CUSTOM_PREFIX + objName;
                    result  = new Validator().IsIdentifier(objName, GetString("systbl.viewproc.viewnotidentifierformat")).Result;
                }
                if (State == STATE_CREATE_PROCEDURE)
                {
                    objName = PROCEDURE_CUSTOM_PREFIX + objName;
                    result  = new Validator().IsIdentifier(objName, GetString("systbl.viewproc.procnotidentifierformat")).Result;
                }
            }

            if (String.IsNullOrEmpty(result))
            {
                try
                {
                    // Retrieve user friendly name
                    string schema, name;
                    ParseName(objName, out schema, out name);

                    // Prepare parameters for stored procedure
                    string param   = txtParams.Text.Trim();
                    string query   = "";
                    bool   binding = chkWithBinding.Checked;

                    TableManager tm = new TableManager(null);

                    switch (State)
                    {
                    case STATE_CREATE_VIEW:
                        query = String.Format("CREATE VIEW {0}{1}\nAS\n{2}", objName, (binding ? " WITH SCHEMABINDING" : ""), body);
                        // Check if view exists
                        if (tm.ViewExists(objName))
                        {
                            result = String.Format(GetString("systbl.view.alreadyexists"), objName);
                        }
                        break;

                    case STATE_ALTER_VIEW:
                        query = String.Format("ALTER VIEW {0}{1}\nAS\n{2}", objName, (binding ? " WITH SCHEMABINDING" : ""), body);
                        break;

                    case STATE_CREATE_PROCEDURE:
                        query = String.Format("CREATE PROCEDURE {0}\n{1}\nAS\nBEGIN\n{2}\nEND\n", objName, param, body);
                        // Check if stored procedure exists
                        if (tm.GetCode(objName) != null)
                        {
                            result = String.Format(GetString("systbl.proc.alreadyexists"), objName);
                        }
                        break;

                    case STATE_ALTER_PROCEDURE:
                        query = String.Format("ALTER PROCEDURE {0}\n{1}\nAS\nBEGIN\n{2}\nEND\n", objName, param, body);
                        break;
                    }

                    if (String.IsNullOrEmpty(result))
                    {
                        ConnectionHelper.ExecuteQuery(query, null, QueryTypeEnum.SQLQuery);

                        ObjectName = name;

                        if (OnSaved != null)
                        {
                            OnSaved(this, EventArgs.Empty);
                        }
                    }
                }
                catch (Exception e)
                {
                    result = e.Message;
                }
            }
        }

        // Show error message if any
        if (!String.IsNullOrEmpty(result))
        {
            ShowError(result);
        }
    }
 public static void SendRemoveMessage(string zoneName)
 {
     ConnectionHelper.SendMessageToServer(new MessageConqExclude {
         CommandType = ExcludeManage.Remove, ZoneName = zoneName
     });
 }
Exemple #31
0
        public void AddConnection()
        {
            int currentRole = 0;
            using (Synchronizer.Lock(this.m_Model.ViewerState.SyncRoot)) {
                currentRole = this.m_Model.ViewerState.iRole;
            }
            if (currentRole == 0)//Disconnected
                    {
                if (this.Controls.Contains(this.m_TabGroupBox)) {
                    this.Controls.Remove(this.m_TabGroupBox);
                    if (this.m_TabGroupBox.Controls.Contains(this.m_TabControl)) {
                        this.m_TabGroupBox.Controls.Remove(this.m_TabControl);
                    }
                    this.m_ButtonGroupBox.Text = Strings.StandAloneInstrStartupStepTwo;
                }
                /*if (this.m_TabControl.Controls.Contains(this.m_TabControl.m_UDPTab))
                    {
                    this.m_TabControl.Controls.Remove(this.m_TabControl.m_UDPTab);
                    }
                if(this.m_TabControl.Controls.Contains(this.m_TabControl.m_AdvancedTab))
                    {
                    this.m_TabControl.Controls.Remove(this.m_TabControl.m_AdvancedTab);
                    }*/
            }
            else if (currentRole == 2) {//Presenter
                /*if (!(this.Controls.Contains(this.m_TabGroupBox))) {
                   this.Controls.Add(this.m_TabGroupBox);
                   }*/
                this.m_TabGroupBox.Text = Strings.PresenterStartupStepTwo;
                this.m_ButtonGroupBox.Text = Strings.PresenterStartupStepThree;
                this.m_Connection = new InstructorConnection(this, this.m_Model, this.m_EventQueue);

            }
            else if ((currentRole == 1) ||//Viewer
              (currentRole == 3)) {//Public Display
                /* if (!(this.Controls.Contains(this.m_TabGroupBox))) {
                     this.Controls.Add(this.m_TabGroupBox);
                     }*/
                this.m_TabGroupBox.Text = Strings.ViewerStartupStepTwo;
                this.m_ButtonGroupBox.Text = Strings.ViewerStartupStepThree;
                this.m_Connection = new ViewerConnection(this, this.m_Model, this.m_EventQueue);
            }
        }
Exemple #32
0
 public static void SendMessage(long entityId)
 {
     ConnectionHelper.SendMessageToServer(new MessageWorth {
         EntityId = entityId
     });
 }
        public HttpResponseMessage Scores()
        {
            var connectionFactory = new HelperConnectionFactory(ConnectionHelper.Helper());
            var sqlRepo           = new SqlServerRepository(connectionFactory);
            var svc = new BestInServiceReportingService(sqlRepo);

            var queryParams    = this.requestService.GetQueryParamsDecoded(Request);
            var timezoneOffset = QueryParamsParsingService.TimeZoneOffset(queryParams);
            var scores         = svc.GetScoreHistory(queryParams);

            var hours = scores.OrderBy(x => x.SummaryDayHour)
                        .Select(x => x.SummaryDayHour)
                        .Distinct();
            var model = new ScoreChartViewModel
            {
                Labels = hours.Select(x => x.AddMinutes(timezoneOffset).ToString("g"))
            };

            var dataSets = (from score in scores
                            group score by score.ServerArtifactId into serverScores
                            orderby serverScores.Key
                            select new ScoreChartDataSet
            {
                label = "Quarterly Recoverability/Integrity Score",
                data = from hour in hours select(int?)
                           (serverScores.FirstOrDefault(x => x.SummaryDayHour.Equals(hour))
                           ?? new ScoreChartModel()).BackupDbccScore,
                sample = from hour in hours
                         select(bool?) false
            }).ToArray();

            int max = 0, min = 100;

            for (var i = 0; i < dataSets.Count(); i++)
            {
                var localMin = dataSets[i].data.Min(x => x.GetValueOrDefault(100));
                if (localMin < min)
                {
                    min = localMin;
                }
                var localMax = dataSets[i].data.Max(x => x.GetValueOrDefault(100));
                if (localMax > max)
                {
                    max = localMax;
                }

                var color = ChartColorExtensions.ChartColorHex(i);
                dataSets[i].pointColor  = color;
                dataSets[i].strokeColor = color;
            }
            if (min > max)
            {
                min = max;
            }

            model.DataSets = dataSets.Take(1);
            model.MinValue = min;
            model.MaxValue = max;

            //Serialize response
            var json     = model.ToJson();
            var response = Request.CreateResponse(HttpStatusCode.OK);

            response.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
            return(response);
        }
 public static void SendListMessage()
 {
     ConnectionHelper.SendMessageToServer(new MessageConqExclude {
         CommandType = ExcludeManage.List
     });
 }
        public int SaveUpdate(PriceList objPL, SqlConnection con)
        {
            int            ID    = 0;
            SqlTransaction trans = null;

            try
            {
                SqlCommand com = new SqlCommand();


                trans           = con.BeginTransaction();
                com.Connection  = con;
                com.Transaction = trans;
                com.CommandText = "spInsertUpdatePriceList";
                com.CommandType = CommandType.StoredProcedure;

                com.Parameters.Add("@PriceID", SqlDbType.Int).Value = objPL.PriceID;
                if (objPL.CustomerID <= 0)
                {
                    com.Parameters.Add("@customerID", SqlDbType.Int).Value = DBNull.Value;
                }
                else
                {
                    com.Parameters.Add("@customerID", SqlDbType.Int).Value = objPL.CustomerID;
                }
                com.Parameters.Add("@itemID", SqlDbType.Int).Value           = objPL.ItemID;
                com.Parameters.Add("@unitID", SqlDbType.Int).Value           = objPL.UnitID;
                com.Parameters.Add("@price", SqlDbType.Money).Value          = objPL.Price;
                com.Parameters.Add("@vat", SqlDbType.Money).Value            = objPL.VAT;
                com.Parameters.Add("@setupDate", SqlDbType.DateTime).Value   = objPL.SetupDate;
                com.Parameters.Add("@remarks", SqlDbType.VarChar, 500).Value = objPL.Remarks;

                if (objPL.CountID <= 0)
                {
                    com.Parameters.Add("@CountID", SqlDbType.Int).Value = DBNull.Value;
                }
                else
                {
                    com.Parameters.Add("@CountID", SqlDbType.Int).Value = objPL.CountID;
                }
                if (objPL.SizeID <= 0)
                {
                    com.Parameters.Add("@SizeID", SqlDbType.Int).Value = DBNull.Value;
                }
                else
                {
                    com.Parameters.Add("@SizeID", SqlDbType.Int).Value = objPL.SizeID;
                }
                if (objPL.ColorID <= 0)
                {
                    com.Parameters.Add("@ColorID", SqlDbType.Int).Value = DBNull.Value;
                }
                else
                {
                    com.Parameters.Add("@ColorID", SqlDbType.Int).Value = objPL.ColorID;
                }

                com.ExecuteNonQuery();
                trans.Commit();
                if (objPL.PriceID == 0)
                {
                    ID = ConnectionHelper.GetID(con, "PriceID", "T_Price_List");
                }
                else
                {
                    ID = objPL.PriceID;
                }
            }
            catch (Exception ex)
            {
                if (trans != null)
                {
                    trans.Rollback();
                }
                throw ex;
            }
            return(ID);
        }
 public static void SendMessage(ulong steamId, string title, string prefix, string content)
 {
     ConnectionHelper.SendMessageToPlayer(steamId, new MessageClientDialogMessage {
         Title = title, Prefix = prefix, Content = content
     });
 }
 public void Init()
 {
     this.connectionHelper = new ConnectionHelper();
 }
    /// <summary>
    /// Returns DataSet according to filter settings.
    /// </summary>
    private DataSet GetData()
    {
        string filterWhere = null;
        string filterText  = txtFilter.Text.Trim();

        // Filter by culture name
        if (!String.IsNullOrEmpty(filterText))
        {
            filterWhere = "UICultureName LIKE '%" + SqlHelperClass.GetSafeQueryString(filterText, false) + "%'";
        }

        // Filter by site cultures
        if (chkSiteCultures.Checked)
        {
            filterWhere = SqlHelperClass.AddWhereCondition(filterWhere, "UICultureCode IN (SELECT CultureCode FROM CMS_Culture WHERE CultureID IN (SELECT CultureID FROM CMS_SiteCulture WHERE SiteID = " + CMSContext.CurrentSiteID + "))");
        }

        // Filter by string key
        filterWhere = SqlHelperClass.AddWhereCondition("(StringID = " + hdnID.Value + ")", filterWhere);

        // Get translated strings
        DataSet result = ConnectionHelper.ExecuteQuery("cms.resourcestring.selecttranslated", null, filterWhere, null, -1, "UICultureName, UICultureCode, TranslationText");

        DataSet missingCultures = null;

        string existingTranslations = TextHelper.Join("', '", SqlHelperClass.GetStringValues(result.Tables[0], "UICultureCode"));

        existingTranslations = "'" + existingTranslations + "'";

        // Add missing site cultures' translations
        if (chkSiteCultures.Checked)
        {
            filterWhere = "UICultureCode IN (SELECT CultureCode FROM CMS_Culture WHERE CultureID IN (SELECT CultureID FROM CMS_SiteCulture WHERE SiteID = " + CMSContext.CurrentSiteID + ")) AND UICultureCode NOT IN (" + existingTranslations + ")";
        }
        // Add all missing cultures' tranlsations
        else
        {
            filterWhere = "UICultureCode NOT IN (" + existingTranslations + ")";
        }

        // Add filter from header
        if (!String.IsNullOrEmpty(filterText))
        {
            filterWhere = SqlHelperClass.AddWhereCondition(filterWhere, "UICultureName LIKE '%" + SqlHelperClass.GetSafeQueryString(filterText, false) + "%'");
        }

        // Get missing translations
        missingCultures = ConnectionHelper.ExecuteQuery("cms.uiculture.selectall", null, filterWhere, null, -1, "UICultureName, UICultureCode");

        // Add missing translations to result
        if (!DataHelper.DataSourceIsEmpty(missingCultures))
        {
            foreach (DataRow dr in missingCultures.Tables[0].Rows)
            {
                result.Tables[0].Rows.Add(dr[0], dr[1], null);
            }
        }

        // Sort and bind dataset
        result.Tables[0].DefaultView.Sort = "UICultureName";
        return(result);
    }