Esempio n. 1
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
            this.BlockUpdated += Block_BlockUpdated;
            this.AddConfigurationUpdateTrigger( upnlContent );

            base.OnInit( e );

            var person = ContextEntity<Person>();
            if ( person != null )
            {
                _personId = person.Id;

                // Hide the person name column
                gUserLogins.Columns[1].Visible = false;
            } 
            _canEdit = RockPage.IsAuthorized( "Edit", CurrentPerson );

            gfSettings.ApplyFilterClick += gfSettings_ApplyFilterClick;
            gfSettings.DisplayFilterValue += gfSettings_DisplayFilterValue;

            gUserLogins.DataKeyNames = new string[] { "id" };
            gUserLogins.Actions.ShowAdd = _personId.HasValue && _canEdit;
            gUserLogins.Actions.AddClick += gUserLogins_Add;
            gUserLogins.IsDeleteEnabled = _canEdit;
            gUserLogins.GridRebind += gUserLogins_GridRebind;

            if (_canEdit)
            {
                gUserLogins.RowSelected += gUserLogins_Edit;
            }

            mdDetails.SaveClick += mdDetails_SaveClick;
            mdDetails.OnCancelScript = string.Format( "$('#{0}').val('');", hfIdValue.ClientID );
        }
Esempio n. 2
0
 public ParametriStampaUnione(int? idPersona, int? idUnitaImmobiliare, int? idResponsabile, int? idIncaricatoAttivita, int? idFornitore, int? idCondominio, int? idEsercizio, TipoIndirizzo tipoIndirizzo, decimal? importo, decimal? importoTotale, int? anno, int? detrazione, string telefonoDaContattare, DateTime? dataIniziale, DateTime? dataFinale, decimal? versamenti, decimal? saldoEsercizioPrecedente, string tipoReport, int? idPersonaRichiedente, int? idPersonaAttiva, string body, string descrizione, string oggetto, DateTime? dataAttiva, string identificativo, string contattiDestinatario, string faxDestinatario, string applicazione)
 {
     IdPersona = idPersona;
     IdUnitaImmobiliare = idUnitaImmobiliare;
     IdResponsabile = idResponsabile;
     IdIncaricatoAttivita = idIncaricatoAttivita;
     IdFornitore = idFornitore;
     IdCondominio = idCondominio;
     IdEsercizio = idEsercizio;
     IdAssemblea = 0;
     TipoIndirizzo = tipoIndirizzo;
     Importo = importo;
     ImportoTotale = importoTotale;
     Anno = anno;
     Detrazione = detrazione;
     IdDatiBancari = null;
     TelefonoDaContattare = telefonoDaContattare;
     DataIniziale = dataIniziale;
     DataFinale = dataFinale;
     Versamenti = versamenti;
     SaldoEsercizioPrecedente = saldoEsercizioPrecedente;
     TipoReport = tipoReport;
     IdPersonaRichiedente = idPersonaRichiedente;
     IdPersonaAttiva = idPersonaAttiva;
     Body = body;
     Descrizione = descrizione;
     Oggetto = oggetto;
     DataAttiva = dataAttiva;
     Identificativo = identificativo;
     ContattiDestinatario = contattiDestinatario;
     FaxDestinatario = faxDestinatario;
     Applicazione = applicazione;
     ParametriAggiuntiviLettera = new ParametriAggiuntiviCompilazioneLettera();
 }
Esempio n. 3
0
		public Cheat(Cheat cheat)
		{
			if (cheat.IsSeparator)
			{
				_enabled = false;
				_watch = SeparatorWatch.Instance;
				_compare = null;
			}
			else
			{
				_enabled = cheat.Enabled;
				_watch = Watch.GenerateWatch(
					cheat.Domain,
					cheat.Address ?? 0,
					cheat.Size,
					cheat.Type,					
					cheat.BigEndian ?? false,
					cheat.Name
                    );
				_compare = cheat.Compare;
				_val = cheat.Value ?? 0;

				Pulse();
			}
		}
        public int? GetMinWeightBetweenNodes(string startNode, string endNode)
        {
            int? startNodeIndex = GetMatrixIndexFromNode(startNode);
            int? endNodeIndex = GetMatrixIndexFromNode(endNode);
            if (startNodeIndex != null && endNodeIndex != null)
            {
                int?[] ArrayOfBestPathWeights = new int?[NodeCount];
                bool[] ArrayOfVisitedNodes = new bool[NodeCount];

                for (int index = 0; index < NodeCount; index++) // Initialize Data for Starting Node
                {
                    ArrayOfBestPathWeights[index] = m_MatrixData[(int)startNodeIndex, index];
                    ArrayOfVisitedNodes[index] = false;
                }
                ArrayOfVisitedNodes[(int)startNodeIndex] = true;

                for (int cycle = 0; cycle < NodeCount - 1; cycle++) // Max Cycles Set to Number of Nodes - 1 (Start Index Already Complete)
                {
                    int? selectedNodeIndex = startNodeIndex;
                    int? currentMinWeight = null;
                    for (int visitingIndex = 0; visitingIndex < NodeCount; visitingIndex++) // Find Next Reachable Unvisited Node
                    {
                        if (!ArrayOfVisitedNodes[visitingIndex] && ArrayOfBestPathWeights[visitingIndex] != null)
                        {
                            currentMinWeight = ArrayOfBestPathWeights[visitingIndex];
                            selectedNodeIndex = visitingIndex;
                            for (int alternativeIndex = 0; alternativeIndex < NodeCount; alternativeIndex++) // Determine Best Option
                            {
                                if (!ArrayOfVisitedNodes[alternativeIndex] && ArrayOfBestPathWeights[visitingIndex] != null &&
                                    ArrayOfBestPathWeights[alternativeIndex] != null && currentMinWeight > ArrayOfBestPathWeights[alternativeIndex])
                                {
                                    selectedNodeIndex = alternativeIndex; // Select Better Option
                                    currentMinWeight = ArrayOfBestPathWeights[alternativeIndex];
                                }
                            }
                            break;
                        }
                    }
                    if (ArrayOfVisitedNodes[(int)selectedNodeIndex]) // Done, No More Unvisited Nodes
                    {
                        return ArrayOfBestPathWeights[(int)endNodeIndex];
                    }
                    ArrayOfVisitedNodes[(int)selectedNodeIndex] = true; // Travel to the Selected Unvisited Node
                    for (int potentialIndex = 0; potentialIndex < NodeCount; potentialIndex++) // Update Weights for Potential Paths
                    {
                        int? pathWeight = m_MatrixData[(int)selectedNodeIndex, potentialIndex];
                        if (pathWeight != null) // If Reachable
                        {
                            int totalPathWeight = (int)ArrayOfBestPathWeights[(int)selectedNodeIndex] + (int)pathWeight; // Weight of Potential Path
                            if (ArrayOfBestPathWeights[potentialIndex] == null || totalPathWeight < ArrayOfBestPathWeights[potentialIndex]) // No Path Yet or Smaller Weight was Found
                            {
                                ArrayOfBestPathWeights[potentialIndex] = totalPathWeight;
                            }
                        }
                    }
                }
                return ArrayOfBestPathWeights[(int)endNodeIndex];
            }
            return null;
        }
Esempio n. 5
0
        protected override void InternalFromXml(System.Xml.Linq.XElement xml, TmxMap tmxMap)
        {
            // Get the tile
            uint gid = TmxHelper.GetAttributeAsUInt(xml, "gid");
            this.FlippedHorizontal = TmxMath.IsTileFlippedHorizontally(gid);
            this.FlippedVertical = TmxMath.IsTileFlippedVertically(gid);
            uint rawTileId = TmxMath.GetTileIdWithoutFlags(gid);

            this.Tile = tmxMap.Tiles[rawTileId];

            // The tile needs to have a mesh on it.
            // Note: The tile may already be referenced by another TmxObjectTile instance, and as such will have its mesh data already made
            if (this.Tile.Meshes.Count() == 0)
            {
                this.Tile.Meshes = TmxMesh.FromTmxTile(this.Tile, tmxMap);
            }

            // Check properties for layer placement
            if (this.Properties.PropertyMap.ContainsKey("unity:sortingLayerName"))
            {
                this.SortingLayerName = this.Properties.GetPropertyValueAsString("unity:sortingLayerName");
            }
            if (this.Properties.PropertyMap.ContainsKey("unity:sortingOrder"))
            {
                this.SortingOrder = this.Properties.GetPropertyValueAsInt("unity:sortingOrder");
            }
        }
        public void Setup()
        {
            //Instance Fields Setup
            BooleanField = null;
            ByteField = null;
            SByteField = null;
            IntField = null;
            LongField = null;
            Int16Field = null;
            UInt16Field = null;
            Int32Field = null;
            UInt32Field = null;
            Int64Field = null;
            UInt64Field = null;
            CharField = null;
            DoubleField = null;
            FloatField = null;

            //Static Fields Setup
            BooleanFieldStatic = null;
            ByteFieldStatic = null;
            SByteFieldStatic = null;
            IntFieldStatic = null;
            LongFieldStatic = null;
            Int16FieldStatic = null;
            UInt16FieldStatic = null;
            Int32FieldStatic = null;
            UInt32FieldStatic = null;
            Int64FieldStatic = null;
            UInt64FieldStatic = null;
            CharFieldStatic = null;
            DoubleFieldStatic = null;
            FloatFieldStatic = null;
        }
Esempio n. 7
0
        protected void Initialize()
        {
            Control ctlTitle = Utils.FindControlRecursive(Page, "lblAddModifyTitle");
            Label lblAddModifyTitle = ctlTitle!=null? (Label)ctlTitle : null;

            Form.Attributes.Add("class", "da-form");

            if (Request["view"] != null)
            {
                this.isView = true;
            }

            if (Request["id"] != null)
            {
                entityKey = int.Parse(Request["id"]);
            }

            this.SetAddModifyTitle(lblAddModifyTitle);
            this.SetBottomControls();

            LoadFields();

            if (entityKey.HasValue)
            {
                LoadFieldsFromEntity(entityKey.Value);
                if (this.isView)
                {
                    SetReadOnlyFields();
                }
            }
        }
        public void GetOriginalFileLineExecutionCounts_AggregatesLineExecutionCountsViaMapping()
        {
            var sourceMapFilePath = "path";

            var mockFileSystem = new Mock<IFileSystemWrapper>();
            mockFileSystem
                .Setup(x => x.GetText(sourceMapFilePath))
                .Returns("contents");
            mockFileSystem
                .Setup(x => x.FileExists(sourceMapFilePath))
                .Returns(true);
            mockFileSystem
                .Setup(x => x.GetFileName("source.file"))
                .Returns("source.file");

            var mapper = new TestableSourceMapDotNetLineCoverageMapper(mockFileSystem.Object, GetFakeMappings());
            // Line 1 executed twice, line 2 once, line 3 never, line 4 never
            var result = mapper.GetOriginalFileLineExecutionCounts(new int?[] { null, 2, 1, null, null }, 3, new ReferencedFile() { Path  = @"source.file", SourceMapFilePath = sourceMapFilePath });

            var expected = new int?[]
            {
                null,
                2,
                2,
                null
            };

            Assert.Equal(expected.Length, result.Length);
            for (var i = 0; i < expected.Length; i++)
            {
                Assert.Equal(expected[i], result[i]);
            }
        }
Esempio n. 9
0
 public override void Parse(GameBitBuffer buffer)
 {
     Field0 = buffer.ReadInt(32);
     Field1 = buffer.ReadInt(32);
     Field2 = buffer.ReadInt(5);
     Field3 = buffer.ReadInt(2) + (-1);
     if (buffer.ReadBool())
     {
         Field4 = new WorldLocationMessageData();
         Field4.Parse(buffer);
     }
     if (buffer.ReadBool())
     {
         Field5 = new InventoryLocationMessageData();
         Field5.Parse(buffer);
     }
     Field6 = new GBHandle();
     Field6.Parse(buffer);
     Field7 = buffer.ReadInt(32);
     Field8 = buffer.ReadInt(32);
     Field9 = buffer.ReadInt(4) + (-1);
     Field10 = (byte)buffer.ReadInt(8);
     if (buffer.ReadBool())
     {
         Field11 = buffer.ReadInt(32);
     }
     if (buffer.ReadBool())
     {
         Field12 = buffer.ReadInt(32);
     }
     if (buffer.ReadBool())
     {
         Field13 = buffer.ReadInt(32);
     }
 }
 public override void Parse(GameBitBuffer buffer)
 {
     ActorId = buffer.ReadInt(32);
     if (buffer.ReadBool())
     {
         Position = new Vector3D();
         Position.Parse(buffer);
     }
     if (buffer.ReadBool())
     {
         Angle = buffer.ReadFloat32();
     }
     if (buffer.ReadBool())
     {
         TurnImmediately = buffer.ReadBool();
     }
     if (buffer.ReadBool())
     {
         Speed = buffer.ReadFloat32();
     }
     if (buffer.ReadBool())
     {
         Field5 = buffer.ReadInt(25);
     }
     if (buffer.ReadBool())
     {
         AnimationTag = buffer.ReadInt(21) + (-1);
     }
     if (buffer.ReadBool())
     {
         Field7 = buffer.ReadInt(32);
     }
 }
Esempio n. 11
0
 public void WhenIPressAdd(string button)
 {
     switch (button.ToLowerInvariant())
     {
         case "add":
             this.result = this.value1.Value + this.value2.Value;
             break;
         case "subtract":
             this.result = this.value1.Value - this.value2.Value;
             break;
         case "multiply":
             this.result = this.value1.Value*this.value2.Value;
             break;
         case "divide":
             this.result = this.value1.Value/this.value2.Value;
             break;
         case "sin":
             this.result = Convert.ToInt32(Math.Sin(Convert.ToDouble(this.value1.Value)));
             break;
         case "cos":
             this.result = Convert.ToInt32(Math.Cos(Convert.ToDouble(this.value1.Value)));
             break;
         case "tan":
             this.result = Convert.ToInt32(Math.Floor(Math.Tan(Convert.ToDouble(this.value1.Value))));
             break;
         case "C":
             this.result = null;
             break;
     }
 }
Esempio n. 12
0
 private VideoFile(SerializationInfo info, DeserializeInfo di)
     : this(di.Server, di.Info, di.Type)
 {
     actors = info.GetValue("a", typeof(string[])) as string[];
       description = info.GetString("de");
       director = info.GetString("di");
       genre = info.GetString("g");
       title = info.GetString("t");
       try {
     width = info.GetInt32("w");
     height = info.GetInt32("h");
       }
       catch (Exception) {
       }
       var ts = info.GetInt64("du");
       if (ts > 0) {
     duration = new TimeSpan(ts);
       }
       try {
     bookmark = info.GetInt64("b");
       }
       catch (Exception) {
     bookmark = 0;
       }
       try {
     subTitle = info.GetValue("st", typeof(Subtitle)) as Subtitle;
       }
       catch (Exception) {
     subTitle = null;
       }
       initialized = true;
 }
        internal FieldSchema(DataRow row)
        {
            ColumnName = toString(row, "ColumnName");
            ColumnOrdinal = toInt(row, "ColumnOrdinal");
            ColumnSize = toInt(row, "ColumnSize");
            NumericPrecision = toInt(row, "NumericPrecision");
            NumericScale = toInt(row, "NumericScale");
            DataType = toType(row, "DataType");
            ProviderType = toInt(row, "ProviderType");
            IsLong = toBool(row, "IsLong");
            AllowDBNull = toBool(row, "AllowDBNull");
            IsUnique = toBool(row, "IsUnique");
            IsKey = toBool(row, "IsKey");
            BaseSchemaName = toString(row, "BaseSchemaName");
            BaseTableName = toString(row, "BaseTableName");
            BaseColumnName = toString(row, "BaseColumnName");

            // --------------------------------------------------
            // SqlServer Only
            // --------------------------------------------------
            //IsReadOnly = toBool(row, "IsReadOnly");
            //IsRowVersion = toBool(row, "IsRowVersion");
            //IsAutoIncrement = toBool(row, "IsAutoIncrement");
            //BaseCatalogName = toString(row, "BaseCatalogName");

            // --------------------------------------------------
            // Oracle Only
            // --------------------------------------------------
            //IsAliased = toBool(row, "IsAliased");
            //IsExpression = toBool(row, "IsExpression");
            //ProviderSpecificDataType = toType(row, "ProviderSpecificDataType");
        }
        public virtual  void Initialize(string name, XmlElement xmlConfig)
        {
            _name = name;
            _populationSize = XmlUtils.GetValueAsInt(xmlConfig, "PopulationSize");
            _specieCount = XmlUtils.GetValueAsInt(xmlConfig, "SpecieCount");
            _activationScheme = ExperimentUtils.CreateActivationScheme(xmlConfig, "Activation");
            _complexityRegulationStr = XmlUtils.TryGetValueAsString(xmlConfig,
                "DefaultComplexityRegulationStrategy");
            _complexityThreshold = XmlUtils.TryGetValueAsInt(xmlConfig, "ComplexityThreshold");
            _description = XmlUtils.TryGetValueAsString(xmlConfig, "Description");
            _parallelOptions = ExperimentUtils.ReadParallelOptions(xmlConfig);

            _eaParams = new NeatEvolutionAlgorithmParameters();
            _eaParams.SpecieCount = _specieCount;
            _neatGenomeParams = new NeatGenomeParameters();
            _neatGenomeParams.FeedforwardOnly = _activationScheme.AcyclicNetwork;

            DefaultComplexityRegulationStrategy = ExperimentUtils.CreateComplexityRegulationStrategy(
                _complexityRegulationStr,
                _complexityThreshold);
            DefaultSpeciationStrategy = new KMeansClusteringStrategy<NeatGenome>(new ManhattanDistanceMetric(1.0, 0.0, 10.0));
            DefaultNeatEvolutionAlgorithm = new NeatEvolutionAlgorithm<NeatGenome>(
                    NeatEvolutionAlgorithmParameters,
                    DefaultSpeciationStrategy,
                    DefaultComplexityRegulationStrategy);
        }
Esempio n. 15
0
        public UserRolesForm(int EmployeeID)
        {
            InitializeComponent();
            employeeId = EmployeeID;
            manager = new ContextManager();
            StaffEmployeeLogic employeeLogic = new StaffEmployeeLogic(manager);
            StaffEmployee employee = employeeLogic.Get(EmployeeID);

            if (employee != null)
            {
                if (employee.UserID != null)
                {
                    userId = Convert.ToInt32(employee.UserID);
                    SecurityUsersLogic usersLogic = new SecurityUsersLogic(manager);
                    SecurityUser user = usersLogic.Get(Convert.ToInt32(userId));
                    LoginL.Text = user.Login;
                }
                else
                    MessageBox.Show("Логін користувача відсутній");
            }

            LFML.Text = employee.LastName + " " + employee.FirstName + " " + employee.MiddleName;

            FillRoles();
        }
Esempio n. 16
0
 public ExecuteProcedure(IDbEnvironment dbEnvironment, String procedureName, bool expectException)
 {
     this.procedureName = procedureName;
     this.dbEnvironment = dbEnvironment;
     this.expectException = expectException;
     errorCode = null;
 }
        protected RelationalConnection([NotNull] IDbContextOptions options, [NotNull] ILogger logger)
        {
            Check.NotNull(options, nameof(options));
            Check.NotNull(logger, nameof(logger));

            _logger = logger;

            var relationalOptions = RelationalOptionsExtension.Extract(options);

            _commandTimeout = relationalOptions.CommandTimeout;

            if (relationalOptions.Connection != null)
            {
                if (!string.IsNullOrWhiteSpace(relationalOptions.ConnectionString))
                {
                    throw new InvalidOperationException(RelationalStrings.ConnectionAndConnectionString);
                }

                _connection = new LazyRef<DbConnection>(() => relationalOptions.Connection);
                _connectionOwned = false;
            }
            else if (!string.IsNullOrWhiteSpace(relationalOptions.ConnectionString))
            {
                _connectionString = relationalOptions.ConnectionString;
                _connection = new LazyRef<DbConnection>(CreateDbConnection);
                _connectionOwned = true;
            }
            else
            {
                throw new InvalidOperationException(RelationalStrings.NoConnectionOrConnectionString);
            }

            _throwOnAmbientTransaction = relationalOptions.ThrowOnAmbientTransaction ?? true;
        }
        private void ForeCastInit(int liveid)
        {
                this.live_id = liveid;
                var l = dMatch.liveTables[live_id].First();
                home_team_big = l.Home_team_big;
                away_team_big = l.Away_team_big;
                home_team = l.Home_team;
                away_team = l.Away_team;
                matchtime = l.Match_time;

                //修正把比赛类型搞进去  2011.6.17
                matchtype = l.Match_type;

                var top20h = dMatch.dHome[home_team_big].Union(dMatch.dHome[away_team_big]).
                    Union(dMatch.dAway[home_team_big]).Union(dMatch.dAway[away_team_big]);

                //修正把比赛日期搞进去了 2011.6.14
                var top20hh = top20h.Where(e => e.Match_time.Value.Date < matchtime.Value.Date);

                //修正把比赛类型搞进去  2011.6.17
                Top20 = top20hh.Where(e => e.Match_type == matchtype).OrderByDescending(e => e.Match_time).Take(40).ToList();

                // .ToList();

                //var top20h = matches.result_tb_lib.Where(e => e.home_team_big == l.home_team_big || e.away_team_big == l.away_team_big);
                //var top20a = matches.result_tb_lib.Where(e => e.home_team_big == l.away_team_big || e.away_team_big == l.home_team_big);
                //Top20 = top20h.Union(top20a).Where(e => e.match_time < matchtime).OrderByDescending(e => e.match_time).Take(40).ToList();
                Top20Count = Top20.Count();
            }    
        private StringAlbumParser(string NameClue)
        {
            if (string.IsNullOrEmpty(NameClue))
            {
                _Authour = "";
                _Name = "";
                return;
            }

            if (_DateParser.IsMatch(NameClue))
            {
                _Year = int.Parse(_DateParser.Match(NameClue).Value);
            }

            if (!_NameParser.IsMatch(NameClue))
            {
                _Authour = NameClue;
                _Name = NameClue;
                return;
            }
                
            Match m = _NameParser.Match(NameClue);

            _Authour = m.Groups[1].Value;
            _Name = m.Groups[2].Value;

            _FoundSomething = true;
      
        }
Esempio n. 20
0
		public override void SyncState(Serializer ser)
		{
			base.SyncState(ser);
			ser.BeginSection("FDS");
			ser.BeginSection("RamAdapter");
			diskdrive.SyncState(ser);
			ser.EndSection();
			ser.BeginSection("audio");
			audio.SyncState(ser);
			ser.EndSection();
			{
				// silly little hack
				int tmp = currentside != null ? (int)currentside : 1234567;
				ser.Sync("currentside", ref tmp);
				currentside = tmp == 1234567 ? null : (int?)tmp;
			}
			for (int i = 0; i < NumSides; i++)
				ser.Sync("diskdiffs" + i, ref diskdiffs[i], true);
			ser.Sync("_timerirq", ref _timerirq);
			ser.Sync("_diskirq", ref _diskirq);
			ser.Sync("diskenable", ref diskenable);
			ser.Sync("soundenable", ref soundenable);
			ser.Sync("reg4026", ref reg4026);
			ser.Sync("timerlatch", ref timerlatch);
			ser.Sync("timervalue", ref timervalue);
			ser.Sync("timerreg", ref timerreg);
			ser.EndSection();

			SetIRQ();
		}
Esempio n. 21
0
 public override void Parse(GameBitBuffer buffer)
 {
     ActorID = buffer.ReadUInt(32);
     ActorSNOId = buffer.ReadInt(32);
     Field2 = buffer.ReadInt(6);
     Field3 = buffer.ReadInt(2) + (-1);
     if (buffer.ReadBool())
     {
         WorldLocation = new WorldLocationMessageData();
         WorldLocation.Parse(buffer);
     }
     if (buffer.ReadBool())
     {
         InventoryLocation = new InventoryLocationMessageData();
         InventoryLocation.Parse(buffer);
     }
     GBHandle = new GBHandle();
     GBHandle.Parse(buffer);
     Field7 = buffer.ReadInt(32);
     NameSNOId = buffer.ReadInt(32);
     Quality = buffer.ReadInt(4) + (-1);
     Field10 = (byte)buffer.ReadInt(8);
     if (buffer.ReadBool())
     {
         Field11 = buffer.ReadInt(32);
     }
     if (buffer.ReadBool())
     {
         MarkerSetSNO = buffer.ReadInt(32);
     }
     if (buffer.ReadBool())
     {
         MarkerSetIndex = buffer.ReadInt(32);
     }
 }
Esempio n. 22
0
        static void Main(string[] args)
        {
            // Question 3.1
            //
            // Describe how you could use a single array to implement three stacks.

            int?[,] array_stack = new int?[3, 10];
            Random rand = new Random();

            for (int x = 0; x < 7; x++)
            {
                array_stack[0, x] = rand.Next(0, 10);
                array_stack[1, x] = rand.Next(0, 10);
                array_stack[2, x] = rand.Next(0, 10);
            }

            // print
            Console.WriteLine("array_stack: ");
            print_stack(array_stack);

            // peek
            Console.WriteLine("Peek 1st stack: " + array_stack[0, 0]);

            // pop 1st stack item
            Console.WriteLine("Pop 1st stack item: " + pop_item(ref array_stack, 0));

            // push an item to 1st stack
            push_item(ref array_stack, 0, 1000);

            Console.WriteLine("array_stack: ");
            print_stack(array_stack);

            Console.ReadLine();
        }
Esempio n. 23
0
 private void ClearLastStartId ()
 {
     if (lastStartId.HasValue) {
         StopSelfResult (lastStartId.Value);
         lastStartId = null;
     }
 }
 private void btnBuscaFornecedor_Click(object sender, EventArgs e)
 {
     this._modelFornecedor = new mFornecedor();
     frmBuscaFornecedor objForm = new frmBuscaFornecedor(this._modelFornecedor);
     try
     {
         DialogResult resultado = objForm.ShowDialog();
         if (resultado == DialogResult.Cancel)
         {
             this._modelFornecedor = null;
             this.txtFornecedor.Text = string.Empty;
         }
         else
         {
             this.txtFornecedor.Text = this._modelFornecedor.NomeFornecedor;
             this._idForn = this._modelFornecedor.IdFornecedor;
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         objForm = null;
     }
 }
Esempio n. 25
0
 public Title()
 {
     this.Name = null;
     this.Rating = null;
     
     
 }
 public ProcedureCode (DataRow row)
 {
     if (row.Table.Columns.Contains("ProcedureCodeID"))
         ProcedureCodeID = row.Field<int>("ProcedureCodeID");
     if (row.Table.Columns.Contains("ProcedureCode"))
         ProcedureCodex = row.Field<string>("ProcedureCode");
     if (row.Table.Columns.Contains("Name"))
         Name = row.Field<string>("Name");
     if (row.Table.Columns.Contains("Description"))
         Description = row.Field<string>("Description");
     if (row.Table.Columns.Contains("ProcedureDisplayText"))
         ProcedureDisplayText = row.Field<string>("ProcedureDisplayText");
     if (row.Table.Columns.Contains("ProcedureTypeID"))
         ProcedureTypeID = row.Field<int?>("ProcedureTypeID");
     if (row.Table.Columns.Contains("Section"))
         Section = row.Field<string>("Section");
     if (row.Table.Columns.Contains("BodySystem"))
         BodySystem = row.Field<string>("BodySystem");
     if (row.Table.Columns.Contains("Operation"))
         Operation = row.Field<string>("Operation");
     if (row.Table.Columns.Contains("BodyRegion"))
         BodyRegion = row.Field<string>("BodyRegion");
     if (row.Table.Columns.Contains("Approach"))
         Approach = row.Field<string>("Approach");
     if (row.Table.Columns.Contains("Method"))
         Method = row.Field<string>("Method");
     if (row.Table.Columns.Contains("Qualifier"))
         Qualifier = row.Field<string>("Qualifier");
     if (row.Table.Columns.Contains("InsertJobID"))
         InsertJobID = row.Field<int?>("InsertJobID");
     if (row.Table.Columns.Contains("UpdateJobID"))
         UpdateJobID = row.Field<int?>("UpdateJobID");
 }
 public ActiveDirectorySchemaProperty(DirectoryContext context, string ldapDisplayName)
 {
     this.syntax = ~ActiveDirectorySyntax.CaseExactString;
     this.rangeLower = null;
     this.rangeUpper = null;
     this.linkId = null;
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     if ((context.Name == null) && !context.isRootDomain())
     {
         throw new ArgumentException(Res.GetString("ContextNotAssociatedWithDomain"), "context");
     }
     if (((context.Name != null) && !context.isRootDomain()) && (!context.isADAMConfigSet() && !context.isServer()))
     {
         throw new ArgumentException(Res.GetString("NotADOrADAM"), "context");
     }
     if (ldapDisplayName == null)
     {
         throw new ArgumentNullException("ldapDisplayName");
     }
     if (ldapDisplayName.Length == 0)
     {
         throw new ArgumentException(Res.GetString("EmptyStringParameter"), "ldapDisplayName");
     }
     this.context = new DirectoryContext(context);
     this.schemaEntry = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.SchemaNamingContext);
     this.schemaEntry.Bind(true);
     this.ldapDisplayName = ldapDisplayName;
     this.commonName = ldapDisplayName;
     this.isBound = false;
 }
Esempio n. 28
0
        internal CompositeData(PortableObjectDocument document, object data, int metaTypeIndex = -1)
        {
            if (data==null)
                 throw new InvalidOperationException("No need to allocate CompositeData from NULL data. Write null directly");//todo Refactor execption type,text etc...

                m_Document = document;

                var tp = data.GetType();
                if (tp.IsPrimitive)
                 throw new InvalidOperationException("Can not allocate CompositeData from primitive type: " + tp.FullName);//todo Refactor execption type,text etc...

                var dict = document.m_CompositeDataDict;
                if (dict==null)
                {
                    dict = new Dictionary<object, int>(ReferenceEqualityComparer<object>.Instance);
                    document.m_CompositeDataDict = dict;
                }

                int existingIndex;
                if (dict.TryGetValue(data, out existingIndex))
                {
                    m_ExistingReferenceIndex = existingIndex;
                }
                else
                {
                    document.m_CompositeData.Add(this);
                    dict.Add(data, document.m_CompositeData.Count-1);
                    m_MetaTypeIndex = metaTypeIndex>=0 ? metaTypeIndex :  MetaType.GetExistingOrNewMetaTypeIndex(document, data.GetType());
                }
        }
 public void Play()
 {
     RequestBuffers();
     _finished = false;
     if (_seekTime != null)
     {
         _startTime = (int)(_context.currentTime * 1000 - _seekTime.Value);
         _seekTime = null;
         _pauseTime = 0;
         _paused = false;
     }
     else if (_paused)
     {
         _paused = false;
         _pauseTime += (int)(_context.currentTime * 1000 - _pauseStart);
     }
     else
     {
         _startTime = (int)(_context.currentTime * 1000);
         _pauseTime = 0;
     }
     _source = _context.createBufferSource();
     _source.buffer = _buffer;
     _source.loop = true;
     _source.connect(_audioNode, 0, 0);
     _source.start(0);
     _audioNode.connect(_context.destination, 0, 0);
 }
Esempio n. 30
0
        protected void gv_ExpandedRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                PDFStats stats = (PDFStats)e.Row.DataItem;
                _totalExpandedPdfs += stats.NumberofPdfs;
                _totalExpandedPdfsWithOcr += stats.PdfsWithOcr;
                _totalExpandedPdfsWithArticleInfo += stats.PdfsWithArticleMetadata;
                _totalExpandedPdfsMissingImages += stats.PdfsWithMissingImages;
                _totalExpandedPdfsMissingOcr += stats.PdfsWithMissingOcr;
                _totalExpandedMissingImages += stats.TotalMissingImages;
                _totalExpandedMissingOcr += stats.TotalMissingOcr;
                _totalExpandedMinutes += (stats.TotalMinutesToGenerate == null ? 0 : stats.TotalMinutesToGenerate);

                if (stats.PdfStatusID == 40) e.Row.BackColor=System.Drawing.Color.MistyRose;
                //if (stats.PdfsWithMissingImages > 0) e.Row.Cells[6].BackColor = System.Drawing.Color.MistyRose;
                //if (stats.PdfsWithMissingOcr > 0) e.Row.Cells[7].BackColor = System.Drawing.Color.MistyRose;
                //if (stats.TotalMissingImages > 0) e.Row.Cells[8].BackColor = System.Drawing.Color.MistyRose;
                //if (stats.TotalMissingOcr > 0) e.Row.Cells[9].BackColor = System.Drawing.Color.MistyRose;
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[0].Text = "Total";
                e.Row.Cells[3].Text = _totalExpandedPdfs.ToString();
                e.Row.Cells[4].Text = _totalExpandedPdfsWithOcr.ToString();
                e.Row.Cells[5].Text = _totalExpandedPdfsWithArticleInfo.ToString();
                e.Row.Cells[6].Text = _totalExpandedPdfsMissingImages.ToString();
                e.Row.Cells[7].Text = _totalExpandedPdfsMissingOcr.ToString();
                e.Row.Cells[8].Text = _totalExpandedMissingImages.ToString();
                e.Row.Cells[9].Text = _totalExpandedMissingOcr.ToString();
                e.Row.Cells[10].Text = ((double)_totalExpandedMinutes / (double)_totalExpandedPdfs).ToString("#.00");
            }
        }
Esempio n. 31
0
        public ActionResult Enroll([Bind(Include = "StudentID,FullName,Email")] Student student, int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Course course = db.Courses.Find(id);

            if (course == null)
            {
                return(HttpNotFound());
            }
            if (ModelState.IsValid)
            {
                Student queryStudent = db.Students.ToList().Find(s => s.FullName == student.FullName && s.Email == student.Email);
                if (queryStudent != null)
                {
                    CourseStudent queryCourseStudent = db.CourseStudents.ToList().Find(cs => cs.StudentId == queryStudent.StudentID && cs.CourseId == id);
                    if (queryCourseStudent != null)
                    {
                        ViewBag.Course  = db.Courses.Find(id);
                        ViewBag.Student = student;
                        return(View("ErrorEnroll"));
                    }
                    else
                    {
                        CourseStudent newEnrollment = new CourseStudent();
                        newEnrollment.CourseId  = (int)id;
                        newEnrollment.StudentId = queryStudent.StudentID;
                        db.CourseStudents.Add(newEnrollment);
                        db.SaveChanges();
                        return(RedirectToAction("Index"));
                    }
                }
                else
                {
                    db.Students.Add(student);
                    db.SaveChanges();
                    queryStudent = db.Students.ToList().Find(s => s.FullName == student.FullName && s.Email == student.Email);
                    CourseStudent newEnrollment = new CourseStudent();
                    newEnrollment.CourseId  = (int)id;
                    newEnrollment.StudentId = queryStudent.StudentID;
                    db.CourseStudents.Add(newEnrollment);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }
            else
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
        }
 private static DocumentVersionCache CreateDocumentVersionCache()
 {
     int? documentVersion = 2;
     var documentVersionCache = Mock.Of<DocumentVersionCache>(dvc => dvc.TryGetDocumentVersion(It.IsAny<DocumentSnapshot>(), out documentVersion) == true, MockBehavior.Strict);
     return documentVersionCache;
 }
Esempio n. 33
0
        /// <summary>
        /// Replaces the tokens in the template with the provided values and route token transformer.
        /// </summary>
        /// <param name="template">The template.</param>
        /// <param name="values">The token values to use.</param>
        /// <param name="routeTokenTransformer">The route token transformer.</param>
        /// <returns>A new string with the replaced values.</returns>
        public static string ReplaceTokens(string template, IDictionary <string, string?> values, IOutboundParameterTransformer?routeTokenTransformer)
        {
            var builder = new StringBuilder();
            var state   = TemplateParserState.Plaintext;

            int?tokenStart = null;
            var scope      = 0;

            // We'll run the loop one extra time with 'null' to detect the end of the string.
            for (var i = 0; i <= template.Length; i++)
            {
                var c = i < template.Length ? (char?)template[i] : null;
                switch (state)
                {
                case TemplateParserState.Plaintext:
                    if (c == '[')
                    {
                        scope++;
                        state = TemplateParserState.SeenLeft;
                        break;
                    }
                    else if (c == ']')
                    {
                        state = TemplateParserState.SeenRight;
                        break;
                    }
                    else if (c == null)
                    {
                        // We're at the end of the string, nothing left to do.
                        break;
                    }
                    else
                    {
                        builder.Append(c);
                        break;
                    }

                case TemplateParserState.SeenLeft:
                    if (c == '[')
                    {
                        // This is an escaped left-bracket
                        builder.Append(c);
                        state = TemplateParserState.Plaintext;
                        break;
                    }
                    else if (c == ']')
                    {
                        // This is zero-width parameter - not allowed.
                        var message = Resources.FormatAttributeRoute_TokenReplacement_InvalidSyntax(
                            template,
                            Resources.AttributeRoute_TokenReplacement_EmptyTokenNotAllowed);
                        throw new InvalidOperationException(message);
                    }
                    else if (c == null)
                    {
                        // This is a left-bracket at the end of the string.
                        var message = Resources.FormatAttributeRoute_TokenReplacement_InvalidSyntax(
                            template,
                            Resources.AttributeRoute_TokenReplacement_UnclosedToken);
                        throw new InvalidOperationException(message);
                    }
                    else
                    {
                        tokenStart = i;
                        state      = TemplateParserState.InsideToken;
                        break;
                    }

                case TemplateParserState.SeenRight:
                    if (c == ']')
                    {
                        // This is an escaped right-bracket
                        builder.Append(c);
                        state = TemplateParserState.Plaintext;
                        break;
                    }
                    else if (c == null)
                    {
                        // This is an imbalanced right-bracket at the end of the string.
                        var message = Resources.FormatAttributeRoute_TokenReplacement_InvalidSyntax(
                            template,
                            Resources.AttributeRoute_TokenReplacement_ImbalancedSquareBrackets);
                        throw new InvalidOperationException(message);
                    }
                    else
                    {
                        // This is an imbalanced right-bracket.
                        var message = Resources.FormatAttributeRoute_TokenReplacement_InvalidSyntax(
                            template,
                            Resources.AttributeRoute_TokenReplacement_ImbalancedSquareBrackets);
                        throw new InvalidOperationException(message);
                    }

                case TemplateParserState.InsideToken:
                    if (c == '[')
                    {
                        state = TemplateParserState.InsideToken | TemplateParserState.SeenLeft;
                        break;
                    }
                    else if (c == ']')
                    {
                        --scope;
                        state = TemplateParserState.InsideToken | TemplateParserState.SeenRight;
                        break;
                    }
                    else if (c == null)
                    {
                        // This is an unclosed replacement token
                        var message = Resources.FormatAttributeRoute_TokenReplacement_InvalidSyntax(
                            template,
                            Resources.AttributeRoute_TokenReplacement_UnclosedToken);
                        throw new InvalidOperationException(message);
                    }
                    else
                    {
                        // This is a just part of the parameter
                        break;
                    }

                case TemplateParserState.InsideToken | TemplateParserState.SeenLeft:
                    if (c == '[')
                    {
                        // This is an escaped left-bracket
                        state = TemplateParserState.InsideToken;
                        break;
                    }
                    else
                    {
                        // Unescaped left-bracket is not allowed inside a token.
                        var message = Resources.FormatAttributeRoute_TokenReplacement_InvalidSyntax(
                            template,
                            Resources.AttributeRoute_TokenReplacement_UnescapedBraceInToken);
                        throw new InvalidOperationException(message);
                    }

                case TemplateParserState.InsideToken | TemplateParserState.SeenRight:
                    if (c == ']' && scope == 0)
                    {
                        // This is an escaped right-bracket
                        state = TemplateParserState.InsideToken;
                        break;
                    }
                    else
                    {
                        // This is the end of a replacement token.
                        var token = template
                                    .Substring(tokenStart !.Value, i - tokenStart.Value - 1)
                                    .Replace("[[", "[")
                                    .Replace("]]", "]");

                        if (!values.TryGetValue(token, out var value))
                        {
                            // Value not found
                            var message = Resources.FormatAttributeRoute_TokenReplacement_ReplacementValueNotFound(
                                template,
                                token,
                                string.Join(", ", values.Keys.OrderBy(k => k, StringComparer.OrdinalIgnoreCase)));
                            throw new InvalidOperationException(message);
                        }

                        if (routeTokenTransformer != null)
                        {
                            value = routeTokenTransformer.TransformOutbound(value);
                        }

                        builder.Append(value);

                        if (c == '[')
                        {
                            state = TemplateParserState.SeenLeft;
                        }
                        else if (c == ']')
                        {
                            state = TemplateParserState.SeenRight;
                        }
                        else if (c == null)
                        {
                            state = TemplateParserState.Plaintext;
                        }
                        else
                        {
                            builder.Append(c);
                            state = TemplateParserState.Plaintext;
                        }

                        scope      = 0;
                        tokenStart = null;
                        break;
                    }
                }
            }

            return(builder.ToString());
        }
Esempio n. 34
0
        /// <summary>
        /// Initializes a new instance of the <see cref="VersionOracle"/> class.
        /// </summary>
        public VersionOracle(string projectDirectory, LibGit2Sharp.Repository repo, LibGit2Sharp.Commit head, ICloudBuild cloudBuild, int?overrideBuildNumberOffset = null, string projectPathRelativeToGitRepoRoot = null)
        {
            var repoRoot = repo?.Info?.WorkingDirectory?.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
            var relativeRepoProjectDirectory = !string.IsNullOrWhiteSpace(repoRoot)
                ? (!string.IsNullOrEmpty(projectPathRelativeToGitRepoRoot)
                    ? projectPathRelativeToGitRepoRoot
                    : projectDirectory.Substring(repoRoot.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))
                : null;

            var commit = head ?? repo?.Head.Commits.FirstOrDefault();

            var committedVersion = VersionFile.GetVersion(commit, relativeRepoProjectDirectory);

            var workingVersion = head != null?VersionFile.GetVersion(head, relativeRepoProjectDirectory) : VersionFile.GetVersion(projectDirectory);

            if (overrideBuildNumberOffset.HasValue)
            {
                if (committedVersion != null)
                {
                    committedVersion.BuildNumberOffset = overrideBuildNumberOffset.Value;
                }

                if (workingVersion != null)
                {
                    workingVersion.BuildNumberOffset = overrideBuildNumberOffset.Value;
                }
            }

            this.VersionOptions = committedVersion ?? workingVersion;

            this.GitCommitId   = commit?.Id.Sha ?? cloudBuild?.GitCommitId ?? null;
            this.VersionHeight = CalculateVersionHeight(relativeRepoProjectDirectory, commit, committedVersion, workingVersion);
            this.BuildingRef   = cloudBuild?.BuildingTag ?? cloudBuild?.BuildingBranch ?? repo?.Head.CanonicalName;

            // Override the typedVersion with the special build number and revision components, when available.
            if (repo != null)
            {
                this.Version = GetIdAsVersion(commit, committedVersion, workingVersion, this.VersionHeight);
            }
            else
            {
                this.Version = this.VersionOptions?.Version.Version ?? Version0;
            }

            this.VersionHeightOffset = this.VersionOptions?.BuildNumberOffsetOrDefault ?? 0;

            this.PrereleaseVersion = ReplaceMacros(this.VersionOptions?.Version.Prerelease ?? string.Empty);

            this.CloudBuildNumberOptions = this.VersionOptions?.CloudBuild?.BuildNumberOrDefault ?? VersionOptions.CloudBuildNumberOptions.DefaultInstance;

            if (!string.IsNullOrEmpty(this.BuildingRef) && this.VersionOptions?.PublicReleaseRefSpec?.Length > 0)
            {
                this.PublicRelease = this.VersionOptions.PublicReleaseRefSpec.Any(
                    expr => Regex.IsMatch(this.BuildingRef, expr));
            }
        }
Esempio n. 35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="VersionOracle"/> class.
 /// </summary>
 public VersionOracle(string projectDirectory, LibGit2Sharp.Repository repo, ICloudBuild cloudBuild, int?overrideBuildNumberOffset = null, string projectPathRelativeToGitRepoRoot = null)
     : this(projectDirectory, repo, null, cloudBuild, overrideBuildNumberOffset, projectPathRelativeToGitRepoRoot)
 {
 }
Esempio n. 36
0
        /// <summary>
        /// Initializes a new instance of the <see cref="VersionOracle"/> class.
        /// </summary>
        public static VersionOracle Create(string projectDirectory, string gitRepoDirectory = null, ICloudBuild cloudBuild = null, int?overrideBuildNumberOffset = null, string projectPathRelativeToGitRepoRoot = null)
        {
            Requires.NotNull(projectDirectory, nameof(projectDirectory));
            if (string.IsNullOrEmpty(gitRepoDirectory))
            {
                gitRepoDirectory = projectDirectory;
            }

            using (var git = GitExtensions.OpenGitRepo(gitRepoDirectory))
            {
                return(new VersionOracle(projectDirectory, git, null, cloudBuild, overrideBuildNumberOffset, projectPathRelativeToGitRepoRoot));
            }
        }
        public virtual async Task <IActionResult> GetExecBatchResults([FromRoute][Required] string activityId, [FromRoute][Required] string batchId, [FromQuery] int?timeout)
        {
            var clientContext = this.HttpContext.Items["ClientContext"] as GolemClientMockAPI.Entities.ClientContext;

            try
            {
                var activity = this.ActivityRepository.GetActivity(activityId);

                if (activity == null)
                {
                    return(this.StatusCode(404)); // Agreement not found
                }

                if (activity.RequestorNodeId != clientContext.NodeId)
                {
                    return(this.StatusCode(403)); // Not entitled to act on the activity
                }

                // TODO check batch exists? validate the rights to batch???

                var resultsEntity = await this.ActivityProcessor.GetExecBatchResultsAsync(batchId, timeout ?? 30000);

                var results = this.ExeScriptMapper.MapResultsFromEntity(resultsEntity);

                return(this.Ok(results));
            }
            catch (Exception exc)
            {
                return(this.StatusCode(500, new DestroyActivityError()
                {
                    Message = exc.Message
                }));
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CartSettingsGift" /> class.
 /// </summary>
 /// <param name="allowGifts">True if this checkout supports gift giving.</param>
 /// <param name="giftCharge">giftCharge.</param>
 /// <param name="giftWraps">The gift wraps available for the customer to select from.</param>
 /// <param name="maxMessageLength">The maximum length of the gift message the giver can enter.</param>
 public CartSettingsGift(bool? allowGifts = default(bool?), Currency giftCharge = default(Currency), List<CartSettingsGiftWrap> giftWraps = default(List<CartSettingsGiftWrap>), int? maxMessageLength = default(int?))
 {
     this.AllowGifts = allowGifts;
     this.GiftCharge = giftCharge;
     this.GiftWraps = giftWraps;
     this.MaxMessageLength = maxMessageLength;
 }
Esempio n. 39
0
 /// <summary>
 /// Initializes a new instance of the
 /// MicrosoftDynamicsCRMInsertOptionValueResponse class.
 /// </summary>
 public MicrosoftDynamicsCRMInsertOptionValueResponse(int?newOptionValue = default(int?))
 {
     NewOptionValue = newOptionValue;
     CustomInit();
 }
Esempio n. 40
0
        private void ParseOption(string name, string value)
        {
            switch (name.ToLower())
            {
            case "authmechanism":
                _authMechanism = value;
                break;

            case "authmechanismproperties":
                foreach (var property in GetAuthMechanismProperties(name, value))
                {
                    _authMechanismProperties.Add(property.Key, property.Value);
                }
                break;

            case "authsource":
                _authSource = value;
                break;

            case "connect":
                _connect = ParseClusterConnectionMode(name, value);
                break;

            case "connecttimeout":
            case "connecttimeoutms":
                _connectTimeout = ParseTimeSpan(name, value);
                break;

            case "fsync":
                _fsync = ParseBoolean(name, value);
                break;

            case "gssapiservicename":
                _authMechanismProperties.Add("SERVICE_NAME", value);
                break;

            case "ipv6":
                _ipv6 = ParseBoolean(name, value);
                break;

            case "j":
            case "journal":
                _journal = ParseBoolean(name, value);
                break;

            case "maxidletime":
            case "maxidletimems":
                _maxIdleTime = ParseTimeSpan(name, value);
                break;

            case "maxlifetime":
            case "maxlifetimems":
                _maxLifeTime = ParseTimeSpan(name, value);
                break;

            case "maxpoolsize":
                _maxPoolSize = ParseInt32(name, value);
                break;

            case "minpoolsize":
                _minPoolSize = ParseInt32(name, value);
                break;

            case "readpreference":
                _readPreference = ParseEnum <ReadPreferenceMode>(name, value);
                break;

            case "readpreferencetags":
                var tagSet = ParseReadPreferenceTagSets(name, value);
                if (_readPreferenceTags == null)
                {
                    _readPreferenceTags = new List <TagSet> {
                        tagSet
                    }.AsReadOnly();
                }
                else
                {
                    _readPreferenceTags = _readPreferenceTags.Concat(new[] { tagSet }).ToList();
                }
                break;

            case "replicaset":
                _replicaSet = value;
                break;

            case "safe":
                var safe = ParseBoolean(name, value);
                if (_w == null)
                {
                    _w = safe ? 1 : 0;
                }
                else
                {
                    if (safe)
                    {
                        // don't overwrite existing W value unless it's 0
                        var wCount = _w as WriteConcern.WCount;
                        if (wCount != null && wCount.Value == 0)
                        {
                            _w = 1;
                        }
                    }
                    else
                    {
                        _w = 0;
                    }
                }
                break;

            case "localthreshold":
            case "localthresholdms":
            case "secondaryacceptablelatency":
            case "secondaryacceptablelatencyms":
                _localThreshold = ParseTimeSpan(name, value);
                break;

            case "slaveok":
                if (_readPreference != null)
                {
                    throw new MongoConfigurationException("ReadPreference has already been configured.");
                }
                _readPreference = ParseBoolean(name, value) ?
                                  ReadPreferenceMode.SecondaryPreferred :
                                  ReadPreferenceMode.Primary;
                break;

            case "serverselectiontimeout":
            case "serverselectiontimeoutms":
                _serverSelectionTimeout = ParseTimeSpan(name, value);
                break;

            case "sockettimeout":
            case "sockettimeoutms":
                _socketTimeout = ParseTimeSpan(name, value);
                break;

            case "ssl":
                _ssl = ParseBoolean(name, value);
                break;

            case "sslverifycertificate":
                _sslVerifyCertificate = ParseBoolean(name, value);
                break;

            case "guids":
            case "uuidrepresentation":
                _uuidRepresentation = ParseEnum <GuidRepresentation>(name, value);
                break;

            case "w":
                _w = WriteConcern.WValue.Parse(value);
                break;

            case "wtimeout":
            case "wtimeoutms":
                _wTimeout = ParseTimeSpan(name, value);
                break;

            case "waitqueuemultiple":
                _waitQueueMultiple = ParseDouble(name, value);
                break;

            case "waitqueuesize":
                _waitQueueSize = ParseInt32(name, value);
                break;

            case "waitqueuetimeout":
            case "waitqueuetimeoutms":
                _waitQueueTimeout = ParseTimeSpan(name, value);
                break;

            default:
                _unknownOptions.Add(name, value);
                break;
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="PublishedRequest"/> class.
 /// </summary>
 public PublishedRequest(Uri uri, string absolutePathDecoded, IPublishedContent? publishedContent, bool isInternalRedirect, ITemplate? template, DomainAndUri? domain, string? culture, string? redirectUrl, int? responseStatusCode, IReadOnlyList<string>? cacheExtensions, IReadOnlyDictionary<string, string>? headers, bool setNoCacheHeader, bool ignorePublishedContentCollisions)
 {
     Uri = uri ?? throw new ArgumentNullException(nameof(uri));
     AbsolutePathDecoded = absolutePathDecoded ?? throw new ArgumentNullException(nameof(absolutePathDecoded));
     PublishedContent = publishedContent;
     IsInternalRedirect = isInternalRedirect;
     Template = template;
     Domain = domain;
     Culture = culture;
     RedirectUrl = redirectUrl;
     ResponseStatusCode = responseStatusCode;
     CacheExtensions = cacheExtensions;
     Headers = headers;
     SetNoCacheHeader = setNoCacheHeader;
     IgnorePublishedContentCollisions = ignorePublishedContentCollisions;
 }
Esempio n. 42
0
 public IHttpActionResult Optional(int?seconds = null)
 {
     Thread.Sleep(TimeSpan.FromSeconds(seconds ?? 0));
     return(Json(seconds));
 }
Esempio n. 43
0
        /// <summary>
        /// F15003_s the list available sub funds.
        /// </summary>
        /// <param name="subFund">The sub fund.</param>
        /// <param name="description">The description.</param>
        /// <param name="rollYear">The roll year.</param>
        /// <param name="fundId">The fund id.</param>
        /// <returns>retuns the dataset with AvailableSubFunds Details</returns>
        public static F15003FundMgmtData F15003_ListAvailableSubFunds(string subFund, string description, int? rollYear, int? fundId)
        {
            F15003FundMgmtData fundMgmtData = new F15003FundMgmtData();
            Hashtable ht = new Hashtable();
            if (!string.IsNullOrEmpty(subFund.Trim()))
            {
                ht.Add("@SubFund", subFund);
            }

            if (!string.IsNullOrEmpty(description.Trim()))
            {
                ht.Add("@Description", description);
            }

            ht.Add("@RollYear", rollYear);
            ht.Add("@FundID", fundId);
            Utility.LoadDataSet(fundMgmtData.ListAvailableSubFundItems, "f15005_pcget_SubfundDescription", ht);
            return fundMgmtData;
        }
Esempio n. 44
0
        public async Task <IActionResult> Index(string search,
                                                int?systemId, int?branchId, bool?mine, int?programId, int page = 1)
        {
            var filter = new TriggerFilter(page);

            if (!string.IsNullOrWhiteSpace(search))
            {
                filter.Search = search;
            }

            if (mine == true)
            {
                filter.UserIds = new List <int> {
                    GetId(ClaimType.UserId)
                };
            }
            else if (branchId.HasValue)
            {
                filter.BranchIds = new List <int> {
                    branchId.Value
                };
            }
            else if (systemId.HasValue)
            {
                filter.SystemIds = new List <int> {
                    systemId.Value
                };
            }

            if (programId.HasValue)
            {
                if (programId.Value > 0)
                {
                    filter.ProgramIds = new List <int?> {
                        programId.Value
                    };
                }
                else
                {
                    filter.ProgramIds = new List <int?> {
                        null
                    };
                }
            }

            var triggerList = await _triggerService.GetPaginatedListAsync(filter);

            var paginateModel = new PaginateViewModel
            {
                ItemCount    = triggerList.Count,
                CurrentPage  = page,
                ItemsPerPage = filter.Take.Value
            };

            if (paginateModel.MaxPage > 0 && paginateModel.CurrentPage > paginateModel.MaxPage)
            {
                return(RedirectToRoute(
                           new
                {
                    page = paginateModel.LastPage ?? 1
                }));
            }

            var requireSecretCode = await GetSiteSettingBoolAsync(
                SiteSettingKey.Events.RequireBadge);

            foreach (var trigger in triggerList.Data)
            {
                trigger.AwardBadgeFilename =
                    _pathResolver.ResolveContentPath(trigger.AwardBadgeFilename);
                var graEvent = (await _eventService.GetRelatedEventsForTriggerAsync(trigger.Id))
                               .FirstOrDefault();
                if (graEvent != null)
                {
                    trigger.RelatedEventId   = graEvent.Id;
                    trigger.RelatedEventName = graEvent.Name;
                }
            }

            var systemList = (await _siteService.GetSystemList())
                             .OrderByDescending(_ => _.Id == GetId(ClaimType.SystemId)).ThenBy(_ => _.Name);

            var viewModel = new TriggersListViewModel
            {
                Triggers      = triggerList.Data,
                PaginateModel = paginateModel,
                Search        = search,
                SystemId      = systemId,
                BranchId      = branchId,
                ProgramId     = programId,
                Mine          = mine,
                SystemList    = systemList,
                ProgramList   = await _siteService.GetProgramList()
            };

            if (mine == true)
            {
                viewModel.BranchList = (await _siteService.GetBranches(GetId(ClaimType.SystemId)))
                                       .OrderByDescending(_ => _.Id == GetId(ClaimType.BranchId))
                                       .ThenBy(_ => _.Name);
                viewModel.ActiveNav = "Mine";
            }
            else if (branchId.HasValue)
            {
                var branch = await _siteService.GetBranchByIdAsync(branchId.Value);

                viewModel.BranchName = branch.Name;
                viewModel.SystemName = systemList
                                       .Where(_ => _.Id == branch.SystemId).SingleOrDefault().Name;
                viewModel.BranchList = (await _siteService.GetBranches(branch.SystemId))
                                       .OrderByDescending(_ => _.Id == GetId(ClaimType.BranchId))
                                       .ThenBy(_ => _.Name);
                viewModel.ActiveNav = "Branch";
            }
            else if (systemId.HasValue)
            {
                viewModel.SystemName = systemList
                                       .Where(_ => _.Id == systemId.Value).SingleOrDefault().Name;
                viewModel.BranchList = (await _siteService.GetBranches(systemId.Value))
                                       .OrderByDescending(_ => _.Id == GetId(ClaimType.BranchId))
                                       .ThenBy(_ => _.Name);
                viewModel.ActiveNav = "System";
            }
            else
            {
                viewModel.BranchList = (await _siteService.GetBranches(GetId(ClaimType.SystemId)))
                                       .OrderByDescending(_ => _.Id == GetId(ClaimType.BranchId))
                                       .ThenBy(_ => _.Name);
                viewModel.ActiveNav = "All";
            }
            if (programId.HasValue)
            {
                if (programId.Value > 0)
                {
                    viewModel.ProgramName =
                        (await _siteService.GetProgramByIdAsync(programId.Value)).Name;
                }
                else
                {
                    viewModel.ProgramName = "Not Limited";
                }
            }

            return(View(viewModel));
        }
Esempio n. 45
0
 public JobConfigurationFilterSpecification(int?skip, int?take, string interfaceName, string jobName, bool?isStoredProcedure)
 {
     InitializeFilterData(skip, take, interfaceName, jobName, isStoredProcedure);
 }
Esempio n. 46
0
        /// <summary>
        /// F15003_s the create or edit fund MGMT.
        /// </summary>
        /// <param name="fundId">The fund id.</param>
        /// <param name="fund">The fund.</param>
        /// <param name="rollYear">The roll year.</param>
        /// <param name="description">The description.</param>
        /// <param name="fundGroupId">The fund group id.</param>
        /// <param name="fundItems">The fund items.</param>
        /// <param name="userId">userId</param>
        /// <returns>returns the Insert status</returns>
        public static int F15003_CreateOrEditFundMgmt(int? fundId, string fund, int rollYear, string description, int? fundGroupId, string fundItems, int userId)
        {
            int errorId;
            Hashtable ht = new Hashtable();
            ht.Add("@FundID", fundId);
            ht.Add("@Fund", fund);
            ht.Add("@RollYear", rollYear);
            if (!string.IsNullOrEmpty(description.Trim()))
            {
                ht.Add("@Description", description);
            }

            ht.Add("@FundGroupID", fundGroupId);
            ht.Add("@FundItems", fundItems);
            ht.Add("@UserID", userId);
            errorId = Utility.FetchSPExecuteKeyId("f15003_pcins_Fund", ht);
            return errorId;
        }
       public List<SaleTransactionObject> GetSaleTransactionObjects(int? itemsPerPage, int? pageNumber)
       {
           try
           {
               List<SaleTransaction> saleTransactionEntityList;
               if ((itemsPerPage != null && itemsPerPage > 0) && (pageNumber != null && pageNumber >= 0))
               {
                   var tpageNumber = (int)pageNumber;
                   var tsize = (int)itemsPerPage;
                   saleTransactionEntityList = _repository.GetWithPaging(m => m.SaleTransactionId, tpageNumber, tsize).ToList();
               }

               else
               {
                   saleTransactionEntityList = _repository.GetAll().ToList();
               }

               if (!saleTransactionEntityList.Any())
               {
                   return new List<SaleTransactionObject>();
               }
               var saleTransactionObjList = new List<SaleTransactionObject>();
               saleTransactionEntityList.ForEach(m =>
               {
                   var saleTransactionObject = ModelCrossMapper.Map<SaleTransaction, SaleTransactionObject>(m);
                   if (saleTransactionObject != null && saleTransactionObject.SaleTransactionId > 0)
                   {
                       saleTransactionObjList.Add(saleTransactionObject);
                   }
               });

               return saleTransactionObjList;
           }
           catch (Exception ex)
           {
               ErrorLogger.LogError(ex.StackTrace, ex.Source, ex.Message);
               return new List<SaleTransactionObject>();
           }
       }
Esempio n. 48
0
        private void InitializeFilterData(int?skip = null, int?take = null, string interfaceName = "", string jobName = "", bool?isStoredProcedure = null, int?id = null)
        {
            Query
            .Where(
                e => (string.IsNullOrEmpty(interfaceName) || e.InterfaceName.Contains(interfaceName)) &&
                (string.IsNullOrEmpty(jobName) || e.JobName.Contains(jobName)) &&
                (!isStoredProcedure.HasValue || e.IsStoredProcedure == isStoredProcedure) &&
                (!id.HasValue || e.Id == id)
                );

            if (skip.HasValue && take.HasValue)
            {
                Query
                .Skip(skip.Value)
                .Take(take.Value);
            }
        }
Esempio n. 49
0
            public static string GetCommand(string title, string text, string alertType, string aggregationKey, string sourceType, int?dateHappened, string priority, string hostname, string[] tags, bool truncateIfTooLong = false)
            {
                string processedTitle = EscapeContent(title);
                string processedText  = EscapeContent(text);
                string result         = string.Format(CultureInfo.InvariantCulture, "_e{{{0},{1}}}:{2}|{3}", processedTitle.Length.ToString(), processedText.Length.ToString(), processedTitle, processedText);

                if (dateHappened != null)
                {
                    result += string.Format(CultureInfo.InvariantCulture, "|d:{0}", dateHappened);
                }
                if (hostname != null)
                {
                    result += string.Format(CultureInfo.InvariantCulture, "|h:{0}", hostname);
                }
                if (aggregationKey != null)
                {
                    result += string.Format(CultureInfo.InvariantCulture, "|k:{0}", aggregationKey);
                }
                if (priority != null)
                {
                    result += string.Format(CultureInfo.InvariantCulture, "|p:{0}", priority);
                }
                if (sourceType != null)
                {
                    result += string.Format(CultureInfo.InvariantCulture, "|s:{0}", sourceType);
                }
                if (alertType != null)
                {
                    result += string.Format(CultureInfo.InvariantCulture, "|t:{0}", alertType);
                }
                if (tags != null)
                {
                    result += string.Format(CultureInfo.InvariantCulture, "|#{0}", string.Join(",", tags));
                }
                if (result.Length > MaxSize)
                {
                    if (truncateIfTooLong)
                    {
                        var overage = result.Length - MaxSize;
                        if (title.Length > text.Length)
                        {
                            title = TruncateOverage(title, overage);
                        }
                        else
                        {
                            text = TruncateOverage(text, overage);
                        }
                        return(GetCommand(title, text, alertType, aggregationKey, sourceType, dateHappened, priority, hostname, tags, true));
                    }
                    else
                    {
                        throw new Exception(string.Format("Event {0} payload is too big (more than 8kB)", title));
                    }
                }
                return(result);
            }
Esempio n. 50
0
 public JobConfigurationFilterSpecification(int?skip, int?take)
 {
     InitializeFilterData(skip, take);
 }
Esempio n. 51
0
 public void Add(string title, string text, string alertType = null, string aggregationKey = null, string sourceType = null, int?dateHappened = null, string priority = null, string hostname = null, string[] tags = null)
 {
     _commands.Add(Event.GetCommand(title, text, alertType, aggregationKey, sourceType, dateHappened, priority, hostname, tags));
 }
Esempio n. 52
0
        //DE-2 2
        public List<ResultProduct> loadProducts(int? catId, int? width, int? profile, int? diameter, Guid? braId)
        {
            List<ResultProduct> result = null;
            try
            {
                using (var db = new dekkOnlineEntities())
                {
                    result = (from pro in db.products
                              where (pro.proStatus == true
                                    //&& pro.categoriesDP.cdpStatus == true
                                    && (catId == null || pro.catId == catId)
                                    && (width == null || pro.proDimensionWidth == width)
                                    && (profile == null || pro.proDimensionProfile == profile)
                                    && (diameter == null || pro.proDimensionDiameter == diameter)
                                    && (braId.HasValue == false || pro.braId == braId))
                                    && (!pro.proNameDP.ToUpper().Contains("TEST"))
                                    && (!pro.proNameDP.ToUpper().Contains("TESET"))
                                    //&& pro.catId != null
                              //&& (!pro.proNameDP.Contains("Test"))
                              select new ResultProduct
                              {
                                  Id = pro.proId,
                                  Image = pro.proImage,
                                  CatId = pro.categories.catId,
                                  CategoryImage = pro.categories.catImage,
                                  CategoryName = pro.categories.catName,
                                  Brand = pro.brands.braName,
                                  BrandImage = pro.brands.braImage,
                                  Name = pro.proName,
                                  Width = pro.proDimensionWidth,
                                  Profile = pro.proDimensionProfile,
                                  Diameter = pro.proDimensionDiameter,
                                  TyreSize = pro.proTyreSize,
                                  Fuel = pro.proFuel,
                                  Wet = pro.proWet,
                                  Noise = pro.proNoise,
                                  //Price = pro.proSuggestedPrice,
                                  Price = pro.proSuggestedPrice != null ? (int)Math.Floor((decimal)pro.proSuggestedPrice) : 0,
                                  Stock = pro.proInventory,
                                  SpeedIndex = pro.proSpeed,
                                  LoadIndex = pro.proLoadIndex
                              }).ToList();



                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return result;
        }
Esempio n. 53
0
 partial void OnMinistryContactIdChanging(int?value);
Esempio n. 54
0
 public void Send(string title, string text, string alertType = null, string aggregationKey = null, string sourceType = null, int?dateHappened = null, string priority = null, string hostname = null, string[] tags = null, bool truncateIfTooLong = false)
 {
     Send(Event.GetCommand(title, text, alertType, aggregationKey, sourceType, dateHappened, priority, hostname, tags, truncateIfTooLong));
 }
Esempio n. 55
0
 partial void OnModifiedByChanging(int?value);
Esempio n. 56
0
 partial void OnChurchIdChanging(int?value);
        public string SP_CRUD_User(UserInput input, int operation, out bool isSuccess, out string message, out int? totalRecords)
        {
            isSuccess = true;
            message = string.Empty;
            totalRecords = null;

            SP_Execute jsonResult = new SP_Execute();
            var sqlQuery = "EXEC [SP_CRUD_User] @UserId, @exp, @nbf, @ver, @iss, @aud, @nonce, @iat, @auth_time, @tfp, @c_hash, @Username, @DisplayName, @Email, @PhotoFileId, @LastLoginOn, @LastIPAddress, @CreatedBy, @ModifiedBy, @DeletedBy, @Operation, @IsSuccess OUT, @Message OUT, @TotalRecords OUT";
            SqlParameter[] parameters =
            {
                new SqlParameter("@UserId", input.UserId ?? (object)DBNull.Value),
                new SqlParameter("@exp", input.Exp ?? (object)DBNull.Value),
                new SqlParameter("@nbf", input.Nbf ?? (object)DBNull.Value),
                new SqlParameter("@ver", input.Ver ?? (object)DBNull.Value),
                new SqlParameter("@iss", input.Iss ?? (object)DBNull.Value),
                new SqlParameter("@aud", input.Aud ?? (object)DBNull.Value),
                new SqlParameter("@nonce", input.Nonce ?? (object)DBNull.Value),
                new SqlParameter("@iat", input.Iat ?? (object)DBNull.Value),
                new SqlParameter("@auth_time", input.AuthTime ?? (object)DBNull.Value),
                new SqlParameter("@tfp", input.Tfp ?? (object)DBNull.Value),
                new SqlParameter("@c_hash", input.CHash ?? (object)DBNull.Value),
                new SqlParameter("@Username", input.Username ?? (object)DBNull.Value),
                new SqlParameter("@DisplayName", input.DisplayName ?? (object)DBNull.Value),
                new SqlParameter("@Email", input.Email ?? (object)DBNull.Value),
                new SqlParameter("@PhotoFileId", input.PhotoFileId ?? (object)DBNull.Value),
                new SqlParameter("@LastLoginOn", input.LastLoginOn ?? (object)DBNull.Value),
                new SqlParameter("@LastIPAddress", input.LastIpaddress ?? (object)DBNull.Value),
                new SqlParameter("@CreatedBy", input.CreatedBy ?? (object)DBNull.Value),
                new SqlParameter("@ModifiedBy", input.ModifiedBy ?? (object)DBNull.Value),
                new SqlParameter("@DeletedBy", input.DeletedBy ?? (object)DBNull.Value),
                new SqlParameter("@Operation", operation),
                new SqlParameter{ ParameterName = "@IsSuccess", DbType = DbType.Boolean, Direction = ParameterDirection.Output, Value = isSuccess },
                new SqlParameter{ ParameterName = "@Message", DbType = DbType.AnsiString, Size = 100, Direction = ParameterDirection.Output, Value = message },
                new SqlParameter{ ParameterName = "@TotalRecords", DbType = DbType.Int32, Direction = ParameterDirection.Output, Value = totalRecords, IsNullable = true },
            };
            jsonResult = this.JsonResult.FromSqlRaw(sqlQuery, parameters).AsNoTracking().AsEnumerable().FirstOrDefault();
            isSuccess = Convert.ToBoolean(parameters[21].Value);
            message = Convert.ToString(parameters[22].Value);
            totalRecords = string.IsNullOrEmpty(Convert.ToString(parameters[23].Value)) ? (int?)null : Convert.ToInt32(parameters[23].Value);
            return jsonResult == null ? null : jsonResult.JsonResult;
        }
Esempio n. 58
0
 partial void OnDepartmentIdChanging(int?value);
        public string SP_CRUD_SearchEngineSubmission(SearchEngineSubmissionInput input, int operation, out bool isSuccess, out string message, out int? totalRecords)
        {
            isSuccess = true;
            message = string.Empty;
            totalRecords = null;

            SP_Execute jsonResult = new SP_Execute();
            var sqlQuery = "EXEC [SP_CRUD_SearchEngineSubmission] @SubmissionNo, @URL, @SubmissionURL, @Status, @Operation, @IsSuccess OUT, @Message OUT, @TotalRecords OUT";
            SqlParameter[] parameters =
            {
                new SqlParameter("@SubmissionNo", input.SubmissionNo ?? (object)DBNull.Value),
                new SqlParameter("@URL", input.Url ?? (object)DBNull.Value),
                new SqlParameter("@SubmissionURL", input.SubmissionUrl ?? (object)DBNull.Value),
                new SqlParameter("@Status", input.Status ?? (object)DBNull.Value),
                new SqlParameter("@Operation", operation),
                new SqlParameter{ ParameterName = "@IsSuccess", DbType = DbType.Boolean, Direction = ParameterDirection.Output, Value = isSuccess },
                new SqlParameter{ ParameterName = "@Message", DbType = DbType.AnsiString, Size = 100, Direction = ParameterDirection.Output, Value = message },
                new SqlParameter{ ParameterName = "@TotalRecords", DbType = DbType.Int32, Direction = ParameterDirection.Output, Value = totalRecords, IsNullable = true },
            };
            jsonResult = this.JsonResult.FromSqlRaw(sqlQuery, parameters).AsNoTracking().AsEnumerable().FirstOrDefault();
            isSuccess = Convert.ToBoolean(parameters[5].Value);
            message = Convert.ToString(parameters[6].Value);
            totalRecords = string.IsNullOrEmpty(Convert.ToString(parameters[7].Value)) ? (int?)null : Convert.ToInt32(parameters[7].Value);
            return jsonResult == null ? null : jsonResult.JsonResult;
        }
Esempio n. 60
0
 partial void OnCreatedByChanging(int?value);