Example #1
0
        /// <summary>
        /// 获取数据。此数据会持续增长,所以不建议一次性缓存。建议单个Model实体缓存。
        /// </summary>
        public BaseResult GetUser(TestTableParam param)
        {
            var where = new Where<TestTable>();
            #region 模糊搜索条件
            if (!string.IsNullOrWhiteSpace(param.SearchName))
            {
                where.And(d => d.Name.Like(param.SearchName));
            }
            if (!string.IsNullOrWhiteSpace(param.SearchIDNumber))
            {
                where.And(d => d.IDNumber.Like(param.SearchIDNumber));
            }
            if (!string.IsNullOrWhiteSpace(param.SearchMobilePhone))
            {
                where.And(d => d.MobilePhone.Like(param.SearchMobilePhone));
            }
            #endregion

            #region 是否分页
            var dateCount = 0;
            if (param._PageIndex != null && param._PageSize != null)
            {
                //取总数,以计算共多少页。自行考虑将总数缓存。
                dateCount = TestTableRepository.Count(where);//.SetCacheTimeOut(10)
            }
            #endregion
            var list = TestTableRepository.Query(where, d => d.CreateTime, "desc", null, param._PageSize, param._PageIndex);
            return new BaseResult(true, list, "", dateCount);
        }
Example #2
0
 /// <summary>
 /// 获取数据。
 /// </summary>
 public BaseResult GetUser(TestTableParam param)
 {
     var where = new Where<TestTable>();
     #region 模糊搜索条件
     if (!string.IsNullOrWhiteSpace(param.SearchName))
     {
         where.And(d => d.Name.Like(param.SearchName));
     }
     if (!string.IsNullOrWhiteSpace(param.SearchIDNumber))
     {
         where.And(d => d.IDNumber.Like(param.SearchIDNumber));
     }
     if (!string.IsNullOrWhiteSpace(param.SearchMobilePhone))
     {
         where.And(d => d.MobilePhone.Like(param.SearchMobilePhone));
     }
     #endregion
     var fs = DB.Context.From<TestTable>()
         .Where(where)
         .OrderByDescending(d => d.CreateTime);
     #region 是否分页
     var dateCount = 0;
     if (param.pageIndex != null && param.pageSize != null)
     {
         //取总数,以计算共多少页。自行考虑将总数缓存。
         dateCount = fs.Count();//.SetCacheTimeOut(10)
         fs.Page(param.pageSize.Value, param.pageIndex.Value);
     }
     #endregion
     var list = fs.ToList();
     return new BaseResult(true, list, "", dateCount);
 }
Example #3
0
        /// <summary>
        /// Define com as propriedades serão dispostas na grid
        /// </summary>
        /// <param name="where">Filtros a serem informados</param>
        /// <returns></returns>
        public override IDisplayValues GetDisplayValues(Where where = null)
        {
            IDisplayValues result = base.GetDisplayValues(where);
            result.Columns.Clear();
            result.Columns.Add(new Parameter("GUID", GenericDbType.String, "sis_log.guid"));
            result.Columns.Add(new Parameter("IP", GenericDbType.String, "sis_log.ip"));
            result.Columns.Add(new Parameter("Nome do computador", GenericDbType.String, "sis_log.nomemaquina"));
            result.Columns.Add(new Parameter("Data do evento", GenericDbType.Date, "sis_log.datahoraevento"));
            result.Columns.Add(new Parameter("Evento", GenericDbType.String, "sis_log.evento"));
            result.Columns.Add(new Parameter("MD5", GenericDbType.String, "sis_logibpt.md5"));
            result.Columns.Add(new Parameter("Caminho", GenericDbType.String, "sis_logibpt.caminho"));

            result.DynamicPaging = (w) =>
            {
                result = DbContext.GetDisplayValues(this, w);
                DataReader dataReader = result.DataReader;

                result.Values = (from x in dataReader
                                     select new object[]
                                     {
                                         x["p_GUID"],
                                         x["p_ip"],
                                         x["p_nomemaquina"],
                                         x["p_datahoraevento"],
                                         x["p_evento"],
                                         x["p_md5"],
                                         x["p_caminho"]
                                     }).ToList();
                return result;
            };

            return result;
        }
Example #4
0
        public override IDisplayValues GetDisplayValues(Where where = null)
        {
            IDisplayValues result = DbContext.GetDisplayValues(this, where);
            result.Columns.Clear();
            result.Columns = new List<Parameter> {
                new Parameter {
                    ParameterName = "GUID"
                },
                new Parameter {
                    ParameterName = "Código",
                    SourceColumn = "EGUID",
                },
                new Parameter {
                    ParameterName = "Estado",
                    SourceColumn = "Nome",
                },
                new Parameter{
                ParameterName = "UF",
                SourceColumn = "UF"

                }
            };

            result.Values = (from x in result.DataReader
                             select new[]{
                                 x["p_GUID"],
                                 x["p_EGUID"],
                                 x["p_Nome"],
                                 x["p_UF"]
                             }).ToList();

            return result;
        }
Example #5
0
        public override IDisplayValues GetDisplayValues(Where where = null)
        {
            IDisplayValues result = base.GetDisplayValues(where);
            result.Columns.Clear();
            result.Columns.Add(new Parameter("GUID", GenericDbType.String, "fat_Lan.GUID"));
            result.Columns.Add(new Parameter("Código", GenericDbType.String, "fat_LanMOVPV.EGUID"));
            result.Columns.Add(new Parameter("Cliente", GenericDbType.String, "fat_LanMovDadoPessoa.NomeFantasia"));
            result.Columns.Add(new Parameter("Valor", GenericDbType.String, "fat_LanMov.vlrtotalliquido"));

            result.DynamicPaging = (w) =>
            {
                result = DbContext.GetDisplayValues(this, w);
                DataReader dr = result.DataReader;

                result.Values = (from x in dr
                                 select new object[] {
                                 x["p_GUID"],
                                 x["p_EGUID"],
                                 x["p_DPNomeFantasia"],
                                 Unimake.Format.Currency(x["p_VlrTotalLiquido"])
                             }).ToList();

                return result;
            };

            return result;
        }
Example #6
0
 public Select(Expression selectItem, From.From from, Where.Where where)
 {
     SelectList = new List<Expression>();
     SelectList.Add(selectItem);
     From = from;
     Where = where;
 }
Example #7
0
    private void CreateNewEvent()
    {
        //Set Event Entry
        Google.GData.Calendar.EventEntry oEventEntry = new Google.GData.Calendar.EventEntry();
        oEventEntry.Title.Text = "Test Calendar Entry From .Net for testing";
        oEventEntry.Content.Content = "Hurrah!!! I posted my second Google calendar event through .Net";

        //Set Event Location
        Where oEventLocation = new Where();
        oEventLocation.ValueString = "Mumbai";
        oEventEntry.Locations.Add(oEventLocation);

        //Set Event Time
        When oEventTime = new When(new DateTime(2012, 8, 05, 9, 0, 0), new DateTime(2012, 8, 05, 9, 0, 0).AddHours(1));
        oEventEntry.Times.Add(oEventTime);

        //Set Additional Properties
        ExtendedProperty oExtendedProperty = new ExtendedProperty();
        oExtendedProperty.Name = "SynchronizationID";
        oExtendedProperty.Value = Guid.NewGuid().ToString();
        oEventEntry.ExtensionElements.Add(oExtendedProperty);

        CalendarService oCalendarService = GAuthenticate();
        Uri oCalendarUri = new Uri("http://www.google.com/calendar/feeds/[email protected]/private/full");

        //Prevents This Error
        //{"The remote server returned an error: (417) Expectation failed."}
        System.Net.ServicePointManager.Expect100Continue = false;

        //Save Event
        oCalendarService.Insert(oCalendarUri, oEventEntry);
    }
Example #8
0
 /// <summary>
 /// Instancia uma nova MappingEngine pelo nó definido no XML. Se o nó não existir será retornado um erro
 /// </summary>
 ///<param name="typeMapping">tipo que será mapeado pelo ETLMapping.xml</param>
 ///<param name="executing">Ação que deverá ser chamada ao executar algo</param>
 ///<param name="onEnd">Ação executada ao terminar a integração do registro</param>
 ///<param name="onStart">Ação executada ao iniciar a integração do registro</param>
 ///<param name="where">Filtro que será usado pelo select, se existir. Pode ser nulo</param>
 public void Execute(Type typeMapping,
         Action<ExecuteEventArgs> executing,
         Action<ExecuteEventArgs> onStart,
         Action<ExecuteEventArgs> onEnd,
         Where where)
 {
     Execute(typeMapping, executing, onStart, onEnd, "", where);
 }
Example #9
0
        /// <summary>
        /// Instancia este objeto e filtra pelo número do Pedido
        /// </summary>
        /// <param name="orderId"></param>
        public ImportOrder(string orderId)
        {
            Where = new Where();

            Where.Parameters.Add(new Parameter("@value", GenericDbType.String)
                {
                    Value = orderId
                });

            Tag = "Pedido";
        }
        /// <summary>
        /// Create a new <see cref="Target"/>.
        /// </summary>
        /// <param name="expression">
        /// The <see cref="EffectExpression"/> this is part of. This cannot be null.
        /// </param>
        /// <param name="targetType">
        /// The actual target of the <see cref="EffectComponent"/>.
        /// </param>
        /// <param name="where">
        /// Where the target is, or null if that is unspecified.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///  <paramref name="expression"/> cannot be null.
        /// </exception>
        public Target(EffectExpression expression, TargetType targetType, Where where)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            this.Expression = expression;
            this.TargetType = targetType;
            this.Where = where;
        }
Example #11
0
        public void And_Expression_2()
        {
            var expr =
                new Where<TestClass>().Group(g => g.Like(x => x.A, "Alice").And().SmallerThan(x => x.B, 2));

            var param = new Dictionary<string, object>();

            var sql = expr.Build(param).ToString();

            Assert.AreEqual(
                "WHERE ([AA] LIKE @A AND [B]<@B)",
                sql);

            Assert.AreEqual(2, param.Count);
        }
Example #12
0
        public void Or_Expression()
        {
            var expr =
                    new Where<TestClass>().Like(x => x.A, "Alice").Or().SmallerThan(x => x.B, 2);

            var param = new Dictionary<string, object>();

            var sql = expr.Build(param).ToString();

            Assert.AreEqual(
                "WHERE [AA] LIKE @A OR [B]<@B",
                sql);

            Assert.AreEqual(2, param.Count);
        }
        /// <summary>
        /// Handles the Click event of the btnAdd control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            try {
            int attributeId = 0;
            int attributeItemId = 0;
            int.TryParse(lblAttributeId.Text, out attributeId);
            int.TryParse(lblAttributeItemId.Text, out attributeItemId);
            AttributeItem attributeItem;
            if (attributeId > 0) {
              Where where = new Where();
              where.ColumnName = AttributeItem.Columns.AttributeId;
              where.DbType = DbType.Int32;
              where.ParameterValue = attributeId;
              Query query = new Query(AttributeItem.Schema);
              object strSortOrder = query.GetMax(AttributeItem.Columns.SortOrder, where);
              int maxSortOrder = 0;
              int.TryParse(strSortOrder.ToString(), out maxSortOrder);

              if (attributeItemId > 0) {
            attributeItem = new AttributeItem(attributeItemId);
              }
              else {
            attributeItem = new AttributeItem();
            attributeItem.SortOrder = maxSortOrder + 1;
              }

              attributeItem.AttributeId = attributeId;
              attributeItem.Name = Server.HtmlEncode(txtAttributeItemName.Text.Trim());
              decimal adjustment = 0;
              decimal.TryParse(txtAdjustment.Text, out adjustment);
              attributeItem.Adjustment = adjustment;
              if (!string.IsNullOrEmpty(txtSkuSuffix.Text)) {
            attributeItem.SkuSuffix = txtSkuSuffix.Text;
              }
              else {
            attributeItem.SkuSuffix = CoreUtility.GenerateRandomString(3);
              }

              attributeItem.Save(WebUtility.GetUserName());
              LoadAttributeItems();
              ResetAttributeItem();
            }
              }
              catch (Exception ex) {
            Logger.Error(typeof(attributeedit).Name + ".btnAdd_Click", ex);
            Master.MessageCenter.DisplayCriticalMessage(ex.Message);
              }
        }
Example #14
0
        public void Complex_Expression_1()
        {
            var expr =
                    new Where<TestClass>().IsEqual(x => x.A, "Bob")
                        .And(g => g.Like(x => x.B, "Alice").Or().SmallerThan(x => x.C, 2))
                        .And(g => g.GreaterThanOrEqualTo(x => x.C, 3).Or().IsEqual(x => x.D, "Chris"));

            var param = new Dictionary<string, object>();

            var sql = expr.Build(param).ToString();

            Assert.AreEqual(
                "WHERE [AA]=@A AND ([B] LIKE @B OR [CC]<@C) AND ([CC]>=@C2 OR [D]=@D)",
                sql);

            Assert.AreEqual(5, param.Count);
        }
        /// <summary>
        /// Close burst n (where N is a positive integer).
        /// </summary>
        /// <param name="powerName">
        /// The <see cref="Power"/> this is for. This cannot be null or empty.
        /// </param>
        /// <param name="size">
        /// The size of the burst in squares. This must be positive.
        /// </param>
        /// <param name="where">
        /// Where the burst occurs. This cannot be null.
        /// </param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">
        /// Neither <paramref name="powerName"/> nor <paramref name="where"/> can be null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="size"/> must be positive.
        /// </exception>
        public static AttackTypeAndRange AreaBurst(string powerName, int size,  Where where)
        {
            if (string.IsNullOrEmpty(powerName))
            {
                throw new ArgumentNullException("powerName");
            }
            if (where == null)
            {
                throw new ArgumentNullException("where");
            }
            if (size <= 0)
            {
                throw new ArgumentException("range must be positive", "size");
            }

            return new AttackTypeAndRange(powerName, AttackType.Area,
                "burst " + size.ToString() + " " + where.ToString().ToLower());
        }
Example #16
0
        /// <summary>
        /// Instancia este objeto e carrega o mesmo com os dados de número de série e data informados
        /// <param name="dataEmissao">Data de emissão do documentos</param>
        /// <param name="numeroSerie">Número de série do ECF</param>
        /// </summary>
        public SintegraReg60M(DateTime dataEmissao, string numeroSerie)
            : this()
        {
            Where w = new Where {
                { "DataEmissao = @p1", new Parameter{
                    ParameterName = "@p1",
                    Value = dataEmissao ,
                    GenericDbType = GenericDbType.Date}
                },

                { "NumSerie = @p2", new Parameter{
                    ParameterName = "@p2",
                    Value = numeroSerie}
                }
            };

            DbContext.Populate(this, w);
        }
Example #17
0
        public override IDisplayValues GetDisplayValues(Where where = null)
        {
            IDisplayValues result = DbContext.GetDisplayValues(this, where);
            DataReader dataReader = result.DataReader;

            result.Columns.Add("GUID");
            result.Columns.Add("EGUID");
            result.Columns.Add("Nível");
            result.Columns.Add("Descricao");

            result.Values = (from x in dataReader
                             select new object[] {
                                        x["p_GUID"],
                                        x["p_EGUID"],
                                        x["p_Nivel"],
                                        x["p_Descricao"]}).ToList();

            return result;
        }
Example #18
0
        public void Query_SelectTop()
        {
            Where LikeUnitTestTerritory = new Where();
            LikeUnitTestTerritory.TableName = Territory.Schema.TableName;
            LikeUnitTestTerritory.ColumnName = Territory.Columns.TerritoryDescription;
            LikeUnitTestTerritory.Comparison = Comparison.Like;
            LikeUnitTestTerritory.ParameterValue = "%ville%";

            Query qry = new Query(Territory.Schema);
            qry.Top = "3";
            qry.AddWhere(LikeUnitTestTerritory);
            int counter = 0;

            using(IDataReader rdr = qry.ExecuteReader())
            {
                while(rdr.Read())
                    counter++;
                rdr.Close();
            }
            Assert.AreEqual(3, counter, "Count is " + counter);
        }
Example #19
0
        public Model[] Find(Where.Where where)
        {
            var data = DBMS.DB.GetInstance().Find(_tableName, where);

            var list = new List<Model>();
            foreach (var row in data)
            {
                var obj = (Model)Activator.CreateInstance(_type);
                obj.Id = Convert.ToInt64(row.Get("id"));
                foreach (var fieldData in _dbField)
                {
                    if(fieldData.GetField() is CharField)
                        fieldData.GetInfo().SetValue(obj, row.Get(fieldData.GetInfo().Name.ToLower()));
                    else if(fieldData.GetField() is Int64Field)
                        fieldData.GetInfo().SetValue(obj, Convert.ToInt64(row.Get(fieldData.GetInfo().Name.ToLower())));
                }
                list.Add(obj);
            }

            return list.ToArray();
        }
 /// <summary>
 /// Handles the Click event of the btnSave control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
 protected void btnSave_Click(object sender, EventArgs e)
 {
     if(Page.IsValid){
     try {
       string descriptorId = lblDescriptorId.Text;
       Descriptor descriptor;
       Where where = new Where();
       where.ColumnName = Descriptor.Columns.ProductId;
       where.DbType = DbType.Int32;
       where.ParameterValue = productId;
       Query query = new Query(Descriptor.Schema);
       object strSortOrder = query.GetMax(Descriptor.Columns.SortOrder, where);
       int maxSortOrder = 0;
       int.TryParse(strSortOrder.ToString(), out maxSortOrder);
       if(!string.IsNullOrEmpty(descriptorId)) {
     descriptor = new Descriptor(descriptorId);
       }
       else {
     descriptor = new Descriptor();
     descriptor.SortOrder = maxSortOrder + 1;
       }
       descriptor.ProductId = productId;
       descriptor.Title = txtTitle.Text.Trim();
       descriptor.DescriptorX = HttpUtility.HtmlEncode(txtDescriptor.Value.Trim());
       descriptor.Save(WebUtility.GetUserName());
       Store.Caching.ProductCache.RemoveDescriptorCollectionFromCache(productId);
       LoadDescriptors();
       lblDescriptorId.Text = string.Empty;
       txtTitle.Text = string.Empty;
       txtDescriptor.Value = string.Empty;
       base.MasterPage.MessageCenter.DisplaySuccessMessage(LocalizationUtility.GetText("lblDescriptorSaved"));
     }
     catch(Exception ex) {
       Logger.Error(typeof(descriptors).Name + "btnSave_Click", ex);
       base.MasterPage.MessageCenter.DisplayCriticalMessage(ex.Message);
     }
       }
 }
Example #21
0
 /// <summary>
 /// Handles the Click event of the btnSave control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
 protected void btnSave_Click(object sender, EventArgs e)
 {
     if(Page.IsValid) {
     try {
       string imageId = lblImageId.Text;
       Where where = new Where();
       where.ColumnName = Store.Image.Columns.ProductId;
       where.DbType = DbType.Int32;
       where.ParameterValue = productId;
       Query query = new Query(Store.Image.Schema);
       object strSortOrder = query.GetMax(Store.Image.Columns.SortOrder, where);
       int maxSortOrder = 0;
       int.TryParse(strSortOrder.ToString(), out maxSortOrder);
       Store.Image image;
       if(!string.IsNullOrEmpty(imageId)) {
     image = new Store.Image(imageId);
       }
       else {
     image = new Store.Image();
     image.SortOrder = maxSortOrder + 1;
       }
       image.ProductId = productId;
       image.ImageFile = txtImageFile.Text.Trim();
       image.Caption = txtImageCaption.Text.Trim();
       image.Save(WebUtility.GetUserName());
       Store.Caching.ProductCache.RemoveImageCollectionFromCache(productId);
       Reset();
       LoadProductImages();
       base.MasterPage.MessageCenter.DisplaySuccessMessage(LocalizationUtility.GetText("lblProductImageSaved"));
     }
     catch(Exception ex) {
       Logger.Error(typeof(images).Name + ".btnSave_Click", ex);
       base.MasterPage.MessageCenter.DisplayCriticalMessage(ex.Message);
     }
       }
 }
Example #22
0
        public override IDisplayValues GetDisplayValues(Where where = null)
        {
            IDisplayValues result = base.GetDisplayValues(where);
            result.Columns.Clear();
            result.Columns.Add(new Parameter("GUID", GenericDbType.String, "ecf_ImpressoraFormaPagto.GUID"));
            result.Columns.Add(new Parameter("Índice", GenericDbType.String, "cad_FormaPagto.EGUID"));
            result.Columns.Add(new Parameter("Descrição", GenericDbType.String, "cad_FormaPagto.Descricao"));

            result.DynamicPaging = (w) =>
            {
                result = DbContext.GetDisplayValues(this, w);
                DataReader dataReader = result.DataReader;

                result.Values = (from x in dataReader
                                 select new object[] {
                                        x["p_GUID"],
                                        x["p_Indice"],
                                        x["p_FormaPagtoDescricao"]}).ToList();

                return result;
            };

            return result;
        }
Example #23
0
 public override string ToString()
 {
     return
         ($"{Select.ToString()} {From.ToString()} {Where.ToString()} {GroupBy?.ToString()} {OrderBy?.ToString()} {Skip?.ToString()} {Take?.ToString()}");
 }
Example #24
0
 /// <summary>
 /// 表示默认为false的搜索结果
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <returns></returns>
 public static Searcher <T> False <T>()
 {
     return(new Searcher <T>(Where.True <T>()));
 }
Example #25
0
        /// <exception cref="System.Exception"></exception>
        public virtual void Test3()
        {
            NeoDatis.Odb.ODB odb = Open(BaseName);
            CriteriaQuery    aq  = new CriteriaQuery(Where.Not(Where.Or().Add(Where
                                                                              .Equal("string1", "test class 0")).Add(Where.Equal
                                                                                                                         ("bigDecimal1", new System.Decimal(5)))));

            NeoDatis.Odb.Objects <TestClass> l = odb.GetObjects <TestClass>(aq, true, -1, -1);
            AssertEquals(48, l.Count);
            TestClass testClass = (TestClass
                                   )l.GetFirst();

            AssertEquals("test class 1", testClass.GetString1());
            odb.Close();
        }
Example #26
0
        /// <exception cref="System.Exception"></exception>
        public virtual void Test6Sort()
        {
            NeoDatis.Odb.ODB odb = Open(BaseName);
            NeoDatis.Odb.Core.Query.Criteria.ICriterion c = Where
                                                            .Or().Add(Where.Equal("string1", "test class 2"
                                                                                  )).Add(Where.Equal("string1", "test class 3")).
                                                            Add(Where.Equal("string1", "test class 4")).Add
                                                                (Where.Equal("string1", "test class 5"));
            CriteriaQuery aq = new CriteriaQuery(c);

            aq.OrderByDesc("boolean1,int1");
            NeoDatis.Odb.Objects <TestClass> l = odb.GetObjects <TestClass>(aq, true, -1, -1);
            AssertEquals(4, l.Count);
            TestClass testClass = l.GetFirst();

            AssertEquals("test class 3", testClass.GetString1());
            odb.Close();
        }
Example #27
0
        /// <exception cref="System.Exception"></exception>
        public virtual void TestSodaWithDate()
        {
            NeoDatis.Odb.ODB odb   = Open(BaseName);
            CriteriaQuery    query = new CriteriaQuery(Where.And().Add(Where.Equal("string1", "test class with values"
                                                                                   )).Add(Where.Equal("date1", new System.DateTime(correctDate.Millisecond))));

            NeoDatis.Odb.Objects <TestClass> l = odb.GetObjects <TestClass>(query);
            // assertEquals(1,l.size());
            query = new CriteriaQuery(Where.And().Add(Where.Equal("string1", "test class with values")).Add(Where.Ge("date1", new System.DateTime(correctDate.Millisecond))));
            l     = odb.GetObjects <TestClass>(query);
            if (l.Count != 1)
            {
                query = new CriteriaQuery(Where.Equal("string1", "test class with null BigDecimal"
                                                      ));
                NeoDatis.Odb.Objects <TestClass> l2 = odb.GetObjects <TestClass>(query);
                Println(l2);
                Println(correctDate.Millisecond);
                l = odb.GetObjects <TestClass>(query);
            }
            AssertEquals(1, l.Count);
            odb.Close();
        }
 public TransactionalBehaviorPolicy()
 {
     Where.RespondsToHttpMethod("POST", "PUT", "DELETE");
     Wrap.WithBehavior <TransactionalBehavior>();
 }
Example #29
0
        /// <summary>
        /// Procura na base de dados da retaguarda e importa o movimento
        /// </summary>
        /// <returns></returns>
        private IList<IMovimento> GetFromBackend()
        {
            ImportOrder import = new ImportOrder(txtCodigo.Text);
            import.Execute();

            //tentar recuperar novamente o pedido, neste caso será sempre uma PV
            Where w = new Where {
                {"fat_LanMovPV.EGUID = @p1",
                new Parameter {
                    ParameterName = "@p1",
                    Value = txtCodigo.Text.PadLeft(10, '0')
                }}
            };

            return new PreVenda().Find<IMovimento>(w);
        }
Example #30
0
 public NavigationCommand(Where where, ActivityViewModel activity = null)
 {
     GoWhere  = where;
     Activity = activity;
 }
Example #31
0
 public void Add(ICondition condition)
 {
     Where.Add(condition);
 }
Example #32
0
 private IList <TEntity> Search() => Entity <TEntity> .FindAll(Where.GroupBy(_field), "group_count desc", _Unique.Count("group_count")& _field, 0, MaxRows);
Example #33
0
        public void WriteSql(SqlWriter writer, SqlGenerator sqlGenerator)
        {
            #region Check if FROM aliases need to be renamed

            // Create a list of the aliases used by the outer extents
            // JoinSymbols have to be treated specially.
            List <string> outerExtentAliases = null;
            if ((null != outerExtents) &&
                (0 < outerExtents.Count))
            {
                foreach (var outerExtent in outerExtents.Keys)
                {
                    var joinSymbol = outerExtent as JoinSymbol;
                    if (joinSymbol != null)
                    {
                        foreach (var symbol in joinSymbol.FlattenedExtentList)
                        {
                            if (null == outerExtentAliases)
                            {
                                outerExtentAliases = new List <string>();
                            }
                            outerExtentAliases.Add(symbol.NewName);
                        }
                    }
                    else
                    {
                        if (null == outerExtentAliases)
                        {
                            outerExtentAliases = new List <string>();
                        }
                        outerExtentAliases.Add(outerExtent.NewName);
                    }
                }
            }

            // An then rename each of the FromExtents we have
            // If AllJoinExtents is non-null - it has precedence.
            // The new name is derived from the old name - we append an increasing int.
            var extentList = AllJoinExtents ?? fromExtents;
            if (null != extentList)
            {
                foreach (var fromAlias in extentList)
                {
                    if ((null != outerExtentAliases) &&
                        outerExtentAliases.Contains(fromAlias.Name))
                    {
                        var    i = sqlGenerator.AllExtentNames[fromAlias.Name];
                        string newName;
                        do
                        {
                            ++i;
                            newName = fromAlias.Name + i.ToString(CultureInfo.InvariantCulture);
                        }while (sqlGenerator.AllExtentNames.ContainsKey(newName));
                        sqlGenerator.AllExtentNames[fromAlias.Name] = i;
                        fromAlias.NewName = newName;

                        // Add extent to list of known names (although i is always incrementing, "prefix11" can
                        // eventually collide with "prefix1" when it is extended)
                        sqlGenerator.AllExtentNames[newName] = 0;
                    }

                    // Add the current alias to the list, so that the extents
                    // that follow do not collide with me.
                    if (null == outerExtentAliases)
                    {
                        outerExtentAliases = new List <string>();
                    }
                    outerExtentAliases.Add(fromAlias.NewName);
                }
            }

            #endregion

            // Increase the indent, so that the Sql statement is nested by one tab.
            writer.Indent += 1; // ++ can be confusing in this context

            writer.Write("SELECT ");
            if (IsDistinct)
            {
                writer.Write("DISTINCT ");
            }

            if (Top != null &&
                Skip == null)    // This is simple TOP case. There is no OFFSET.
            {
                Top.WriteSql(writer, sqlGenerator);
            }

            if ((null == @select) ||
                Select.IsEmpty)
            {
                Debug.Assert(false); // we have removed all possibilities of SELECT *.
                writer.Write("*");
            }
            else
            {
                Select.WriteSql(writer, sqlGenerator);
            }

            writer.WriteLine();
            writer.Write("FROM ");
            From.WriteSql(writer, sqlGenerator);

            if ((null != @where) &&
                !Where.IsEmpty)
            {
                writer.WriteLine();
                writer.Write("WHERE ");
                Where.WriteSql(writer, sqlGenerator);
            }

            if ((null != groupBy) &&
                !GroupBy.IsEmpty)
            {
                writer.WriteLine();
                writer.Write("GROUP BY ");
                GroupBy.WriteSql(writer, sqlGenerator);
            }

            if ((null != orderBy) &&
                !OrderBy.IsEmpty &&
                (IsTopMost || Top != null || Skip != null))
            {
                writer.WriteLine();
                writer.Write("ORDER BY ");
                OrderBy.WriteSql(writer, sqlGenerator);
            }

            if (null != Skip)
            {
                writer.WriteLine();
                WriteOffsetFetch(writer, Top, Skip, sqlGenerator); // Write OFFSET, FETCH clause.
            }

            --writer.Indent;
        }
Example #34
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="whereParam"></param>
 /// <returns></returns>
 public Search <T> Where(Where whereParam)
 {
     return((Search <T>)base.Where(whereParam.ToWhereClip()));
 }
Example #35
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="where"></param>
 /// <returns></returns>
 public Search <T> Having(Where where)
 {
     return((Search <T>)base.Having(where.ToWhereClip()));
 }
 public abstract void AddMethodExecutedWhere(MethodInfo method, Where where);
Example #37
0
 public virtual NameValueCollection[] Find(string tableName, Where.Where where)
 {
     throw new Exception("DB 설정 에러");
 }
Example #38
0
		public InterceptorDescriptor(InterceptorReference[] interceptors, Where where)
		{
			this.interceptors = interceptors;
			this.where = where;
		}
 protected ExecutedFacetAbstract(Where where, ISpecification holder)
     : base(Type, holder)
 {
     executedWhere = where;
 }
Example #40
0
 public OrderCollection Where(Where where)
 {
     wheres.Add(where);
     return(this);
 }
Example #41
0
 public ConditionalAttribute(string propertyName, object value, int logical)
 {
     conditions    = new Where[1];
     conditions[0] = new Where(propertyName, Comparison.Equals, value, (Logical)logical);
 }
        public void DeployConsole()
        {
            SetOutput(_isPassive, _isPassive && _isForced);
            try
            {
                System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                {
                    DeployElevated();
                    return;
                }

                List <GitInstallation> installations = null;

                // use the custom installation path if supplied
                if (!string.IsNullOrEmpty(_customPath))
                {
                    if (!Directory.Exists(_customPath))
                    {
                        Program.LogEvent("No Git installation found, unable to continue deployment.", EventLogEntryType.Error);
                        Console.Out.WriteLine();
                        Program.WriteLine($"Fatal: custom path does not exist: '{_customPath}'. {FailFace}");
                        Pause();

                        Result = ResultValue.InvalidCustomPath;
                        return;
                    }

                    Console.Out.WriteLine();
                    Console.Out.WriteLine($"Deploying to custom path: '{_customPath}'.");

                    // if the custom path points to a git location then treat it properly
                    GitInstallation installation;
                    if (Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows64v2, out installation) ||
                        Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v2, out installation) ||
                        Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v1, out installation))
                    {
                        Git.Trace.WriteLine($"   Git found: '{installation.Path}'.");

                        // track known Git installations
                        installations = new List <GitInstallation>();
                        installations.Add(installation);
                    }

                    Program.LogEvent($"Custom path deployed to: '{_customPath}'", EventLogEntryType.Information);
                }
                // since no custom installation path was supplied, use default logic
                else
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Looking for Git installation(s)...");

                    if (Where.FindGitInstallations(out installations))
                    {
                        foreach (var installation in installations)
                        {
                            Console.Out.WriteLine($"  {installation.Path}");
                        }
                    }
                }

                if (installations == null)
                {
                    Program.LogEvent("No Git installation found, unable to continue.", EventLogEntryType.Error);
                    Console.Out.WriteLine();
                    Program.WriteLine("Fatal: Git was not detected, unable to continue. {FailFace}");
                    Pause();

                    Result = ResultValue.GitNotFound;
                    return;
                }

                List <string> copiedFiles;
                foreach (var installation in installations)
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine($"Deploying from '{Program.Location}' to '{installation.Path}'.");

                    if (CopyFiles(Program.Location, installation.Libexec, FileList, out copiedFiles))
                    {
                        int copiedCount = copiedFiles.Count;

                        foreach (var file in copiedFiles)
                        {
                            Console.Out.WriteLine($"  {file}");
                        }

                        // copy help documents
                        if (Directory.Exists(installation.Doc) &&
                            CopyFiles(Program.Location, installation.Doc, DocsList, out copiedFiles))
                        {
                            copiedCount += copiedFiles.Count;

                            foreach (var file in copiedFiles)
                            {
                                Console.Out.WriteLine($"  {file}");
                            }
                        }

                        Program.LogEvent($"Deployment to '{installation.Path}' succeeded.", EventLogEntryType.Information);
                        Console.Out.WriteLine($"     {copiedCount} file(s) copied");
                    }
                    else if (_isForced)
                    {
                        Program.LogEvent($"Deployment to '{installation.Path}' failed.", EventLogEntryType.Warning);
                        Program.WriteLine($"  deployment failed. {FailFace}");
                    }
                    else
                    {
                        Program.LogEvent($"Deployment to '{installation.Path}' failed.", EventLogEntryType.Error);
                        Program.WriteLine($"  deployment failed. {FailFace}");
                        Pause();

                        Result = ResultValue.DeploymentFailed;
                        return;
                    }
                }

                Console.Out.WriteLine();
                Console.Out.WriteLine($"Deploying from '{Program.Location}' to '{UserBinPath}'.");

                if (!Directory.Exists(UserBinPath))
                {
                    Directory.CreateDirectory(UserBinPath);
                }

                if (CopyFiles(Program.Location, UserBinPath, FileList, out copiedFiles))
                {
                    int copiedCount = copiedFiles.Count;

                    foreach (var file in copiedFiles)
                    {
                        Console.Out.WriteLine($"  {file}");
                    }

                    if (CopyFiles(Program.Location, UserBinPath, DocsList, out copiedFiles))
                    {
                        copiedCount = copiedFiles.Count;

                        foreach (var file in copiedFiles)
                        {
                            Console.Out.WriteLine($"  {file}");
                        }
                    }

                    Program.LogEvent($"Deployment to '{UserBinPath}' succeeded.", EventLogEntryType.Information);
                    Console.Out.WriteLine($"     {copiedCount} file(s) copied");
                }
                else if (_isForced)
                {
                    Program.LogEvent($"Deployment to '{UserBinPath}' failed.", EventLogEntryType.Warning);
                    Program.WriteLine($"  deployment failed. {FailFace}");
                }
                else
                {
                    Program.LogEvent($"Deployment to '{UserBinPath}' failed.", EventLogEntryType.Error);
                    Program.WriteLine($"  deployment failed. {FailFace}");
                    Pause();

                    Result = ResultValue.DeploymentFailed;
                    return;
                }

                if (CygwinPath != null && Directory.Exists(CygwinPath))
                {
                    if (CopyFiles(Program.Location, CygwinPath, FileList, out copiedFiles))
                    {
                        int copiedCount = copiedFiles.Count;

                        foreach (var file in copiedFiles)
                        {
                            Console.Out.WriteLine($"  {file}");
                        }

                        if (CopyFiles(Program.Location, CygwinPath, DocsList, out copiedFiles))
                        {
                            copiedCount = copiedFiles.Count;

                            foreach (var file in copiedFiles)
                            {
                                Console.Out.WriteLine($"  {file}");
                            }
                        }

                        Program.LogEvent($"Deployment to '{CygwinPath}' succeeded.", EventLogEntryType.Information);
                        Console.Out.WriteLine($"     {copiedCount} file(s) copied");
                    }
                    else if (_isForced)
                    {
                        Program.LogEvent($"Deployment to '{CygwinPath}' failed.", EventLogEntryType.Warning);
                        Program.WriteLine($"  deployment failed. {FailFace}");
                    }
                    else
                    {
                        Program.LogEvent($"Deployment to '{CygwinPath}' failed.", EventLogEntryType.Error);
                        Program.WriteLine($"  deployment failed. {FailFace}");
                        Pause();

                        Result = ResultValue.DeploymentFailed;
                        return;
                    }
                }

                ConfigurationLevel types = ConfigurationLevel.Global;

                ConfigurationLevel updateTypes;
                if (SetGitConfig(installations, GitConfigAction.Set, types, out updateTypes))
                {
                    if ((updateTypes & ConfigurationLevel.Global) == ConfigurationLevel.Global)
                    {
                        Console.Out.WriteLine("Updated your ~/.gitconfig [git config --global]");
                    }
                    else
                    {
                        Console.Out.WriteLine();
                        Program.WriteLine("Fatal: Unable to update your ~/.gitconfig correctly.");

                        Result = ResultValue.GitConfigGlobalFailed;
                        return;
                    }
                }

                // all necessary content has been deployed to the system
                Result = ResultValue.Success;

                Program.LogEvent($"{Program.Title} v{Program.Version.ToString(3)} successfully deployed.", EventLogEntryType.Information);
                Console.Out.WriteLine();
                Console.Out.WriteLine($"Success! {Program.Title} was deployed! {TadaFace}");
                Pause();
            }
            finally
            {
                SetOutput(true, true);
            }
        }
Example #43
0
        public ActionResult Index()
        {
            var pageCurrent = RequestHelper.GetFormInt("pageCurrent", 1);
            var pageSize    = RequestHelper.GetFormInt("pageSize", 30);
            int total;

            var where = new Where <ManagerLog>();
            //获取排序字段
            var orderField = RequestHelper.GetFormString("orderField");
            Expression <Func <ManagerLog, object> > orderEx;

            switch (orderField)
            {
            case "Id":
                orderEx = p => p.Id;
                break;

            case "UserId":
                orderEx = p => p.UserId;
                break;

            case "UserName":
                orderEx = p => p.UserName;
                break;

            case "ActionType":
                orderEx = p => p.ActionType;
                break;

            case "Remark":
                orderEx = p => p.Remark;
                break;

            case "UserIp":
                orderEx = p => p.UserIp;
                break;

            case "AddTime":
                orderEx = p => p.AddTime;
                break;

            case "ControllerName":
                orderEx = p => p.ControllerName;
                break;

            case "ActionName":
                orderEx = p => p.ActionName;
                break;

            default:
                orderEx = p => p.Id;
                break;
            }
            //设置方式
            var orderDirection = RequestHelper.GetFormString("orderDirection");

            EnumHelper.OrderBy orderby = EnumHelper.OrderBy.Asc;
            if (orderDirection == "desc")
            {
                orderby = EnumHelper.OrderBy.Desc;
            }
            //查询筛选

            var Id = RequestHelper.GetFormInt("Id", 0);

            if (Id > 0)
            {
                where.And(p => p.Id == Id);
            }
            ViewBag.Id = Id;

            var UserId = RequestHelper.GetFormInt("UserId", 0);

            if (UserId > 0)
            {
                where.And(p => p.UserId == UserId);
            }
            ViewBag.UserId = UserId;

            var UserName = RequestHelper.GetFormString("UserName");

            if (!string.IsNullOrEmpty(UserName))
            {
                where.And(p => p.UserName == UserName);
            }
            ViewBag.UserName = UserName;

            var ActionType = RequestHelper.GetFormString("ActionType");

            if (!string.IsNullOrEmpty(ActionType))
            {
                where.And(p => p.ActionType == ActionType);
            }
            ViewBag.ActionType = ActionType;

            var Remark = RequestHelper.GetFormString("Remark");

            if (!string.IsNullOrEmpty(Remark))
            {
                where.And(p => p.Remark == Remark);
            }
            ViewBag.Remark = Remark;

            var UserIp = RequestHelper.GetFormString("UserIp");

            if (!string.IsNullOrEmpty(UserIp))
            {
                where.And(p => p.UserIp == UserIp);
            }
            ViewBag.UserIp = UserIp;

            var AddTime = RequestHelper.GetFormString("AddTime");

            if (!string.IsNullOrEmpty(AddTime))
            {
                var dtAddTime = ToolsHelper.StrToDateTime(AddTime);
                where.And(p => p.AddTime > dtAddTime);
            }
            ViewBag.AddTime = AddTime;

            var ControllerName = RequestHelper.GetFormString("ControllerName");

            if (!string.IsNullOrEmpty(ControllerName))
            {
                where.And(p => p.ControllerName == ControllerName);
            }
            ViewBag.ControllerName = ControllerName;

            var ActionName = RequestHelper.GetFormString("ActionName");

            if (!string.IsNullOrEmpty(ActionName))
            {
                where.And(p => p.ActionName == ActionName);
            }
            ViewBag.ActionName = ActionName;

            //获取数据
            var list = _bll.QueryPageList(pageCurrent, pageSize, out total, where, orderEx, orderby);

            //缓存数据
            ViewBag.pageCurrent = pageCurrent;
            ViewBag.pageSize    = pageSize;
            ViewBag.total       = total;

            ViewBag.orderDirection = orderDirection;
            ViewBag.orderField     = orderField;

            return(View(list));
        }
 public ExecutedControlMethodFacet(MethodInfo method, Where where, ISpecification holder)
     : base(typeof(IExecutedControlMethodFacet), holder)
 {
     methodToWhere[method] = where;
 }
Example #45
0
        /// <exception cref="System.Exception"></exception>
        public virtual void Test5Sort()
        {
            NeoDatis.Odb.ODB odb = Open(BaseName);
            CriteriaQuery    aq  = new CriteriaQuery(Where
                                                     .Not(Where.Or().Add(Where
                                                                         .Equal("string1", "test class 2")).Add(Where.Equal
                                                                                                                    ("string1", "test class 3"))));

            // aq.orderByDesc("double1,boolean1,int1");
            aq.OrderByDesc("double1,int1");
            NeoDatis.Odb.Objects <TestClass> l = odb.GetObjects <TestClass> (aq, true, -1, -1);
            AssertEquals(48, l.Count);
            TestClass testClass = l.GetFirst();

            AssertEquals("test class 9", testClass.GetString1());
            odb.Close();
        }
Example #46
0
 public void CreateWhere()
 {
     Where where = factory.CreateWhere(null);
     Assert.IsNotNull(where);
     Assert.IsInstanceOfType(typeof(CAMLWhere), where);
 }
Example #47
0
        /// <exception cref="System.Exception"></exception>
        public virtual void Test1()
        {
            NeoDatis.Odb.ODB odb = Open(BaseName);
            CriteriaQuery    aq  = new CriteriaQuery(Where.Or().Add(Where.Equal("string1", "test class 1")).Add(Where.Equal("string1", "test class 3")));

            aq.OrderByAsc("string1");
            NeoDatis.Odb.Objects <TestClass> l = odb.GetObjects <TestClass>(aq, true, -1, -1);
            AssertEquals(2, l.Count);
            TestClass testClass = l.GetFirst();

            AssertEquals("test class 1", testClass.GetString1());
            odb.Close();
        }
Example #48
0
 public CurrentProductListCollection Where(Where where)
 {
     wheres.Add(where);
     return(this);
 }
Example #49
0
 public ProductDescriptorCollection Where(Where where)
 {
     wheres.Add(where);
     return(this);
 }
Example #50
0
        public string ToDDL()
        {
            var index = IsUnique ? "CREATE UNIQUE INDEX" : "CREATE INDEX";

            if (IsConcurrent)
            {
                index += " CONCURRENTLY";
            }

            index += $" {IndexName} ON {_mapping.Table.QualifiedName}";

            if (Method != IndexMethod.btree)
            {
                index += $" USING {Method}";
            }

            var membersLocator = _members
                                 .Select(m =>
            {
                var field  = _mapping.FieldFor(m);
                var casing = Casing;
                if (field.FieldType != typeof(string))
                {
                    // doesn't make sense to lower-case this particular member
                    casing = Casings.Default;
                }

                var sql = field.TypedLocator.Replace("d.", "");
                switch (casing)
                {
                case Casings.Upper:
                    return($" upper({sql})");

                case Casings.Lower:
                    return($" lower({sql})");

                default:
                    return($" ({sql})");
                }
            })
                                 .Join(",");

            var locator = $"{membersLocator}";

            if (TenancyScope == TenancyScope.PerTenant)
            {
                locator = $"{locator}, tenant_id";
            }

            index += " (" + locator + ")";

            // Only the B-tree index type supports modifying the sort order, and ascending is the default
            if (Method == IndexMethod.btree && SortOrder == SortOrder.Desc)
            {
                index  = index.Remove(index.Length - 1);
                index += " DESC)";
            }

            if (Where.IsNotEmpty())
            {
                index += $" WHERE ({Where})";
            }

            return(index + ";");
        }
Example #51
0
 public ETLBase()
 {
     Where = new Where();
 }
 public OrderDetailsExtendedCollection Where(Where where)
 {
     wheres.Add(where);
     return(this);
 }
Example #53
0
 public RandWeight(Where where)
     : this(where, ValueObjectType.Value)
 {
 }
 public InterceptorDescriptor(InterceptorReference[] interceptors)
 {
     where             = Where.Default;
     this.interceptors = interceptors;
 }
Example #55
0
        /// <summary>
        /// Pesquisar todos os movimentos utilizando a SearchWindow 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPesquisarMovimento_Click(object sender, EventArgs e)
        {
            IParentModel tipoMovimento = null;

            // Aqui verifica o tipo de movimento que o usuário quer pesquisar
            if (rbtDAV.Checked)
                tipoMovimento = new DAV();
            else if (rbtDAVOS.Checked)
                tipoMovimento = new Data.Faturamento.Lancamento.Movimento.DAV.OS.DAV();
            else
                tipoMovimento = new PreVenda();

            //Filtro para trazer somente os movimentos que estão com o status: Aberto
            Where where = new Where();
            where.Add("fat_lan.status = @status",
                new Parameter
                {
                    ParameterName = "@status",
                    Value = (int)Enuns.Faturamento.Lancamento.Status.Aberto
                });

            // Fazer a Pesquisa e pegar o GUID movimento selecionado
            SearchWindowResult result = SearchWindow.Show(tipoMovimento, where);

            if (!result.GUID.IsNullOrEmpty())
                CarregarMovimento(result.GUID);
        }
 public InterceptorDescriptor(InterceptorReference[] interceptors, Where where)
 {
     this.interceptors = interceptors;
     this.where        = where;
 }
        public bool SetGitConfig(List <GitInstallation> installations, GitConfigAction action, Configuration.Type type, out Configuration.Type updated)
        {
            Trace.WriteLine("Installer::SetGitConfig");
            Trace.WriteLine("   action = " + action + ".");

            updated = Configuration.Type.None;

            if (installations == null && !Where.FindGitInstallations(out installations))
            {
                Trace.WriteLine("   No Git installations detected to update.");
                return(false);
            }

            if ((type & Configuration.Type.Global) == Configuration.Type.Global)
            {
                // the 0 entry in the installations list is the "preferred" instance of Git
                string gitCmdPath = installations[0].Cmd;
                string globalCmd  = action == GitConfigAction.Set
                    ? "config --global credential.helper manager"
                    : "config --global --unset credential.helper";

                if (ExecuteGit(gitCmdPath, globalCmd))
                {
                    Trace.WriteLine("   updating ~/.gitconfig succeeded.");

                    updated |= Configuration.Type.Global;
                }
                else
                {
                    Trace.WriteLine("   updating ~/.gitconfig failed.");

                    Console.Out.WriteLine();
                    Console.Error.WriteLine("Fatal: Unable to update ~/.gitconfig.");
                    Pause();
                    return(false);
                }
            }

            if ((type & Configuration.Type.System) == Configuration.Type.System)
            {
                string systemCmd = action == GitConfigAction.Set
                    ? "config --system credential.helper manager"
                    : "config --system --unset credential.helper";

                int successCount = 0;

                foreach (var installation in installations)
                {
                    if (ExecuteGit(installation.Cmd, systemCmd))
                    {
                        Trace.WriteLine("   updating /etc/gitconfig succeeded.");

                        successCount++;
                    }
                    else
                    {
                        Trace.WriteLine("   updating ~/.gitconfig failed.");
                    }
                }

                if (successCount == installations.Count)
                {
                    updated |= Configuration.Type.System;
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
 public void AddMethodExecutedWhere(MethodInfo method, Where where)
 {
     methodToWhere[method] = where;
 }
Example #59
0
		public InterceptorDescriptor(InterceptorReference[] interceptors)
		{
			where = Where.Default;
			this.interceptors = interceptors;
		}
        public void DeployConsole()
        {
            Trace.WriteLine("Installer::DeployConsole");

            SetOutput(_isPassive, _isPassive && _isForced);
            try
            {
                System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                {
                    DeployElevated();
                    return;
                }

                List <GitInstallation> installations = null;

                // use the custom installation path if supplied
                if (!String.IsNullOrEmpty(_customPath))
                {
                    if (!Directory.Exists(_customPath))
                    {
                        Console.Out.WriteLine();
                        Console.Error.WriteLine("Fatal: custom path does not exist: '{0}'. U_U", _customPath);
                        Pause();

                        Result = ResultValue.InvalidCustomPath;
                        return;
                    }

                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Deploying to custom path: '{0}'.", _customPath);

                    // if the custom path points to a git location then treat it properly
                    GitInstallation installation;
                    if (Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows64v2, out installation) ||
                        Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v2, out installation) ||
                        Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v1, out installation))
                    {
                        Trace.Write("   Git found: " + installation.Path);

                        // track known Git installtations
                        installations = new List <GitInstallation>();
                        installations.Add(installation);
                    }
                }
                // since no custom installation path was supplied, use default logic
                else
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Looking for Git installation(s)...");

                    if (Where.FindGitInstallations(out installations))
                    {
                        foreach (var installation in installations)
                        {
                            Console.Out.WriteLine("  {0}", installation.Path);
                        }
                    }
                }

                if (installations == null)
                {
                    Console.Out.WriteLine();
                    Console.Error.WriteLine("Fatal: Git was not detected, unable to continue. U_U");
                    Pause();

                    Result = ResultValue.GitNotFound;
                    return;
                }

                List <string> cleanedFiles;
                foreach (var installation in installations)
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Deploying from '{0}' to '{1}'.", Program.Location, installation.Path);

                    if (CopyFiles(Program.Location, installation.Libexec, out cleanedFiles))
                    {
                        foreach (var file in cleanedFiles)
                        {
                            Console.Out.WriteLine("  {0}", file);
                        }

                        Console.Out.WriteLine("        {0} file(s) copied", cleanedFiles.Count);
                    }
                    else if (_isForced)
                    {
                        Console.Error.WriteLine("  deployment failed. U_U");
                    }
                    else
                    {
                        Console.Error.WriteLine("  deployment failed. U_U");
                        Pause();

                        Result = ResultValue.RemovalFailed;
                        return;
                    }
                }

                // only update the system configs if using a custom path
                Configuration.Type types = String.IsNullOrWhiteSpace(_customPath)
                    ? Configuration.Type.Global | Configuration.Type.System
                    : Configuration.Type.System;

                Configuration.Type updateTypes;
                if (SetGitConfig(installations, GitConfigAction.Set, types, out updateTypes))
                {
                    if ((updateTypes & Configuration.Type.System) == Configuration.Type.System)
                    {
                        Console.Out.WriteLine();
                        Console.Out.WriteLine("Updated your /etc/gitconfig [git config --system]");
                    }
                    else
                    {
                        Console.Out.WriteLine();

                        // updating /etc/gitconfig should not fail installation when forced
                        if (!_isForced)
                        {
                            // only 'fatal' when not forced
                            Console.Error.Write("Fatal: ");

                            Result = ResultValue.GitConfigSystemFailed;
                            return;
                        }

                        Console.Error.WriteLine("Unable to update your /etc/gitconfig correctly.");
                    }

                    if ((updateTypes & Configuration.Type.Global) == Configuration.Type.Global)
                    {
                        Console.Out.WriteLine("Updated your ~/.gitconfig [git config --global]");
                    }
                    else
                    {
                        Console.Out.WriteLine();
                        Console.Error.WriteLine("Fatal: Unable to update your ~/.gitconfig correctly.");

                        Result = ResultValue.GitConfigGlobalFailed;
                        return;
                    }
                }

                // all necissary content has been deployed to the system
                Result = ResultValue.Success;

                Console.Out.WriteLine();
                Console.Out.WriteLine("Success! {0} was deployed! ^_^", Program.Title);
                Pause();
            }
            finally
            {
                SetOutput(true, true);
            }
        }