Inheritance: IDisposable
Beispiel #1
2
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            int id;
            if (!int.TryParse(Request.QueryString["id"], out id))
            {
                Response.Redirect("~/MediaCenter.aspx");
            }
            Database db = new Database();
            Lang lang = new Lang();
            db.AddParameter("@lang", lang.getCurrentLang());
            db.AddParameter("@id", id);
            DataTable dt = db.ExecuteDataTable("select top(3) * from Report where lang=@lang and (not id=@id) Order by id desc");
            Repeater1.DataSource = dt;
            Repeater1.DataBind();

            db.AddParameter("@lang", lang.getCurrentLang());
            dt = db.ExecuteDataTable("select top(3) * from SocialEvent where lang=@lang Order by id desc");
            Repeater2.DataSource = dt;
            Repeater2.DataBind();

            db.AddParameter("@lang", lang.getCurrentLang());
            db.AddParameter("@id", id);
            dt = db.ExecuteDataTable("select * from Report where lang=@lang and id=@id");
            Repeater3.DataSource = dt;
            Repeater3.DataBind();

            if (dt.Rows.Count == 0)
            {
                Response.Redirect("~/MediaCenter.aspx");
            }
        }
    }
        public ParameterContainer(Database.DatabaseProvider databaseProvider)
        {
            if (databaseProvider == null) throw new ArgumentNullException("databaseProvider");

            this.databaseProvider = databaseProvider;
            this.parameters = new Dictionary<string, IDbDataParameter>();
        }
 private static IDictionary<string,object> InsertEntity(object entity, Database database, string tableName)
 {
     var dictionary = entity as IDictionary<string, object>;
     if (dictionary == null)
         throw new SimpleDataException("Could not discover data in object.");
     return database.Adapter.Insert(tableName, dictionary);
 }
Beispiel #4
0
		public async Task CreateDbAsync()
		{
			db = new Database(_connectionStringName);
			var all = Utils.LoadTextResource(string.Format("AsyncPoco.Tests.{0}_init.sql", _connectionStringName));
			foreach(var sql in all.Split(';').Select(s => s.Trim()).Where(s => s.Length > 0))
				await db.ExecuteAsync(sql);
		}
Beispiel #5
0
    public override void runExtension(Database db)
    {
        foreach (DBItem result in db.getSpawnableItems()) {
            // If this item can be made by other items, create a symmetric "Makes" property
            if (!result.propertyExists("madeby"))
                continue;

            foreach (KeyValuePair<string, string> ingredients in (List<KeyValuePair<string, string>>)result.getProperty("madeby")) {
                string ingredient1 = ingredients.Key;
                string ingredient2 = ingredients.Value;
                if (!db.itemExists(ingredient1) || !db.itemExists(ingredient2))
                    continue;
                DBItem dbIng1 = db.getItem(ingredient1);
                DBItem dbIng2 = db.getItem(ingredient2);
                if (!dbIng1.propertyExists("makes"))
                    dbIng1.setProperty("makes", new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>(ingredient2, result.ClassName) });
                else
                    (dbIng1.getProperty("makes") as List<KeyValuePair<string, string>>).Add(new KeyValuePair<string, string>(ingredient2, result.ClassName));
                if (!dbIng2.propertyExists("makes"))
                    dbIng2.setProperty("makes", new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>(ingredient1, result.ClassName) });
                else
                    (dbIng2.getProperty("makes") as List<KeyValuePair<string, string>>).Add(new KeyValuePair<string, string>(ingredient1, result.ClassName));

            }
        }
    }
Beispiel #6
0
        public void CreateDatabase()
        {
            var connectoinStringBuilder = new SqlConnectionStringBuilder(ConnectionString);
            string dbName = connectoinStringBuilder.InitialCatalog;
            connectoinStringBuilder.InitialCatalog = string.Empty;

            using (var connection = new SqlConnection(connectoinStringBuilder.ToString()))
            {
                try
                {
                    var serverConnection = new ServerConnection(connection);
                    var server = new Microsoft.SqlServer.Management.Smo.Server(serverConnection);
                    var db = new Database(server, dbName);
                    db.Create();
                }
                catch (Exception e)
                {
                    throw new Exception(string.Format("Ошибка при создании БД - {0}", e));
                }
                finally
                {
                    if (connection.State == ConnectionState.Open)
                    {
                        connection.Close();
                    }
                }
            }
        }
Beispiel #7
0
        public static string HandleParameter( string name, object value, Database db, ref List<Parameter> ps )
        {
            string ret = db.DelimColumn( name );
            if( value != null && value.GetType() == typeof(SpecialValue) )
            {
                // Special Handling
                var sv = (SpecialValue)value;

                switch( sv.Name )
                {
                case "is-null":
                    ret += " IS NULL";
                    return ret;
                case "is-not-null":
                    ret += " IS NOT NULL";
                    return ret;
                case "lit-value":
                    var lv = (LiteralValue)sv;
                    ret += " = " + lv.TextValue;
                    return ret;
                default:
                    throw new ArgumentOutOfRangeException( "value", "Unhandled Special Value passed in." );
                }
            }

            var pname = "auto_"+name+"_"+ps.Count.ToString();
            ret += " = " + db.DelimParameter( pname );

            ps.Add( new Parameter( pname, value ) );

            return ret;
        }
 public Indexer()
 {
     database = new Database("b81ca2da-f0ca-4968-b9ef-a147009a4ef4.mysql.sequelizer.com",
         "dbb81ca2daf0ca4968b9efa147009a4ef4", "lizeabvjtqokfima", "qauWLTF4Db7umBPvvyy5LPYAzjLvtFMJKNKnbahQUaN7eEks6ndW4FvHi3vAhkH6");
     command = database.CreateCommand();
     command.CommandTimeout = 0;
 }
Beispiel #9
0
    public void SetUp()
    { 
      var home = _context.CurrentDatabase.GetItem("/sitecore/content/home");

      var contentRootItem = TestUtil.CreateContentFromFile("TestResources\\items in workflow.xml", _testRoot);
      _publishableItem = contentRootItem.Axes.GetChild("publishable");
      _itemInWorkflow = contentRootItem.Axes.GetChild("in draft");
      _noWorkflow = contentRootItem.Axes.GetChild("no workflow");

      _noWorkflow.Editing.BeginEdit();
      _noWorkflow[FieldIDs.Workflow] = string.Empty;
      _noWorkflow[FieldIDs.WorkflowState] = string.Empty;
      _noWorkflow.Editing.EndEdit();

      // publish the root item only so publishing on any item works
      var dbs = new Database[]{ Sitecore.Configuration.Factory.GetDatabase("web")};
      var langs = new Language[]{ Sitecore.Context.Language};
      var handle = PublishManager.PublishItem(_testRoot, dbs, langs, false, true);

      PublishManager.PublishItem(contentRootItem, dbs, langs, false, true);

      var jobs = from j in Sitecore.Jobs.JobManager.GetJobs()
                 where j.Name.Contains("Publish") && j.Name.Contains("web")
                 select j;

      foreach (var job in jobs)
        job.Wait();
    }
Beispiel #10
0
    public static GameObject GenerateViewObject(Database database, bool pod, bool analytic, int analyticType)
    {
        GameObject currentHarness = Generate((int)View_Type.Harness);
        Transform harnessTransform =  currentHarness.transform;

        List<DatabaseUtilities.Table> tableInfo = database.tables;
        int tableCount = tableInfo.Count;

        GameObject[] tables = new GameObject[tableCount];

        for(int i = 0; i < tableCount; i++)
        {
            tables[i] = GenerateTableObj(tableInfo[i], harnessTransform, analytic);
        }
        
        if(!analytic)
        {
            currentHarness.GetComponent<TableHarness>().Initialize(tables, pod);
        }
        else
        {
            currentHarness.GetComponent<TableHarness>().Initialize(tables, analytic, analyticType);
        }

        currentHarness.transform.localPosition = new Vector3(0, 0, 0);
        return currentHarness;
    }
Beispiel #11
0
    public static GameObject GenerateAnalyticObject(Database database, int analyticType)
    {
        //Make sure to generate the correct type of harness (disk harness)
        GameObject currentHarness = Generate((int)View_Type.DiskHarness);
        Transform harnessTransform = currentHarness.transform;

        List<DatabaseUtilities.Table> tableInfo = database.tables;
        int tableCount = tableInfo.Count;

        GameObject[] anaObjects = new GameObject[tableCount];

        if(analyticType == 1)
        {
            DatabaseUtilities.Table infoObject = tableInfo[0];
            List<DatabaseUtilities.Column> dataTypes = infoObject.columns;
            int dataTypeSize = dataTypes.Count;

            GameObject[] disks = new GameObject[dataTypeSize];

            for(int i = 0; i < dataTypeSize; i++)
            {
                disks[i] = GenerateDiskObj(dataTypes[i], harnessTransform);
            }

            currentHarness.GetComponent<DiskHarness>().Initialize(disks, dataTypes);
        }

        return currentHarness;
    }
Beispiel #12
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            SetContentView (Resource.Layout.Main);

            Button prevButton = FindViewById<Button> (Resource.Id.prevButton);
            Button nextButton = FindViewById<Button> (Resource.Id.nextButton);
            Button listenButton = FindViewById<Button> (Resource.Id.listenButton);

            phraseTextView = FindViewById<TextView> (Resource.Id.phraseTextView);
            translationTextView = FindViewById<TextView> (Resource.Id.translationTextView);

            SoundPlayer soundPlayer = new SoundPlayerIml (Assets);

            db = new InMemoryDatabase ();

            new PopulateInMemoryDatabaseWithSampleDataCmd (db as InMemoryDatabase)
                .Execute ();

            presenter = new PhrasesPresenterIml (this, soundPlayer, db, lessonNumber);

            prevButton.Click += delegate {
                presenter.MovePrevious ();
            };

            nextButton.Click += delegate {
                presenter.MoveNext ();
            };

            listenButton.Click += delegate {
                presenter.PlaySoundStart ();
            };
        }
Beispiel #13
0
        public void ClearPanelsAkrFromDrawing(Database db)
        {
            SelectionBlocks sel = new SelectionBlocks(db);
             sel.SelectAKRPanelsBtr();

             List<ObjectId> idsBtrPanelsAkr = sel.IdsBtrPanelAr.ToList();
             idsBtrPanelsAkr.AddRange(sel.IdsBtrPanelSb);

             List<ObjectId> idsBtrOther = new List<ObjectId>();

             foreach (ObjectId idBtrPanel in idsBtrPanelsAkr)
             {
            using (var btrPanel = idBtrPanel.Open(OpenMode.ForRead) as BlockTableRecord)
            {
               foreach (ObjectId idBlRefPanel in btrPanel.GetBlockReferenceIds(false, true))
               {
                  using (var blRefPanel = idBlRefPanel.Open(OpenMode.ForWrite, false, true) as BlockReference)
                  {
                     blRefPanel.Erase();
                  }
               }
               foreach (ObjectId idEnt in btrPanel)
               {
                  using (var blRef = idEnt.Open(OpenMode.ForRead, false, true) as BlockReference)
                  {
                     if (blRef == null) continue;
                     idsBtrOther.Add(blRef.BlockTableRecord);
                  }
               }
            }
             }

             eraseIdsDbo(idsBtrPanelsAkr);
             eraseIdsDbo(idsBtrOther);
        }
Beispiel #14
0
        public void SetUp()
        {
            TestUtils.CreateTestDb();
            TestUtils.Execute(@"CREATE TABLE Tbl(IntValue int NULL)");

            _target = new Database(TestUtils.ConnStr);
        }
	private IEnumerator Start () {
		Debug.LogFormat ("Data path = {0}", Application.persistentDataPath);

#if UNITY_EDITOR_WIN
		Log.SetLogger(new UnityLogger());
#endif
		_db = Manager.SharedInstance.GetDatabase ("spaceshooter");
		_pull = _db.CreatePullReplication (GameController.SYNC_URL);
		_pull.Continuous = true;
		_pull.Start ();
		while (_pull != null && _pull.Status == ReplicationStatus.Active) {
			yield return new WaitForSeconds(0.5f);
		}

		var doc = _db.GetExistingDocument ("player_data");
		if (doc != null) {
			//We have a record!  Get the ship data, if possible.
			string assetName = String.Empty;
			if(doc.UserProperties.ContainsKey("ship_data")) {
				assetName = doc.UserProperties ["ship_data"] as String;
			}
			StartCoroutine(LoadAsset (assetName));
		} else {
			//Create a new record
			doc = _db.GetDocument("player_data");
			doc.PutProperties(new Dictionary<string, object> { { "ship_data", String.Empty } });
		}

		doc.Change += DocumentChanged;
		_push = _db.CreatePushReplication (new Uri ("http://127.0.0.1:4984/spaceshooter"));
		_push.Start();
	}
        public void DeleteUser(int id)
        {
            try
            {
                using (Database db = new Database(GlobalObjects.CONNECTION_STRING))
                {
                    db.Open();
                    string sql;
                    int ret = 0;
                    DataTable oTable = new DataTable();
                    sql = "DeleteFromTable";
                    db.ExecuteCommandReader(sql,
                        new string[] { "@tablename", "@id", "@updatedby" },
                        new DbType[] { DbType.String, DbType.Int32, DbType.String },
                        new object[] { "Withdrawals", id, appUsr.UserName },
                        out ret, ref oTable, CommandTypeEnum.StoredProcedure);

                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        public DataView GetAll(string query, int type)
        {
            try
            {
                using (Database db = new Database(GlobalObjects.CONNECTION_STRING))
                {

                    db.Open();
                    int ret = 0;
                    DataTable oTable = new DataTable();
                    string sql = "GetWithdrawals";
                    db.ExecuteCommandReader(sql,
                        new string[] { "@query" },
                        new DbType[] { DbType.String },
                        new object[] { query },
                        out ret, ref oTable, CommandTypeEnum.StoredProcedure);

                    return Utility.FilterDataTable(FormalFormatTable(oTable), "type=" + type.ToString());

                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
		protected override void ConfigureServer(Database.Config.RavenConfiguration ravenConfiguration)
		{
			ravenConfiguration.AnonymousUserAccessMode = AnonymousUserAccessMode.None;
			ravenConfiguration.AuthenticationMode = "OAuth";
			ravenConfiguration.OAuthTokenCertificate = CertGenerator.GenerateNewCertificate("RavenDB.Test");
			ravenConfiguration.Catalog.Catalogs.Add(new TypeCatalog(typeof(FakeAuthenticateClient)));
		}
		protected override IEnumerable<DbParameter> CoreGetColumnParameters(Type connectionType, string dataSourceTag, Server server, Database database, Schema schema, Table table)
		{
			if ((object)connectionType == null)
				throw new ArgumentNullException(nameof(connectionType));

			if ((object)dataSourceTag == null)
				throw new ArgumentNullException(nameof(dataSourceTag));

			if ((object)server == null)
				throw new ArgumentNullException(nameof(server));

			if ((object)database == null)
				throw new ArgumentNullException(nameof(database));

			if ((object)schema == null)
				throw new ArgumentNullException(nameof(schema));

			if ((object)table == null)
				throw new ArgumentNullException(nameof(table));

			if (dataSourceTag.SafeToString().ToLower() == ODBC_SQL_SERVER_DATA_SOURCE_TAG)
			{
				return new DbParameter[]
						{
							//DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.ReflectionFascadeLegacyInstance.CreateParameter(connectionType, null,ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P1", server.ServerName),
							//DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.ReflectionFascadeLegacyInstance.CreateParameter(connectionType, null,ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P2", database.DatabaseName),
							DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.CreateParameter(connectionType, null, ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P3", schema.SchemaName),
							DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.CreateParameter(connectionType, null, ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P4", table.TableName)
						};
			}

			throw new ArgumentOutOfRangeException(string.Format("dataSourceTag: '{0}'", dataSourceTag));
		}
Beispiel #20
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

            int id = -1;
            if (int.TryParse(Request.QueryString["id"], out id))
            {
                Database db = new Database();
                Lang lang = new Lang();
                db.AddParameter("@id", id);
                db.AddParameter("@lang", lang.getCurrentLang());
                DataTable dt = db.ExecuteDataTable("select country.name as countryname,researcher.* from Researcher inner join Country on Researcher.Country=Country.id where researcher.lang=@lang and researcher.IsAproved=1 and researcher.id=@id");
                if(dt.Rows.Count==0)
                {
                    Response.Redirect("Experts.aspx");
                }
                Repeater1.DataSource = dt;
                Repeater1.DataBind();

                LoadResearch(id,"",null,null);

                txtTitle.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {__doPostBack('" + btnSearch.UniqueID + "','');}} ");
                txtFrom.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {__doPostBack('" + btnSearch.UniqueID + "','');}} ");
                txtTo.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {__doPostBack('" + btnSearch.UniqueID + "','');}} ");
            }
        }
    }
Beispiel #21
0
    private void LoadResearch(int id,string title,DateTime? from,DateTime? to)
    {
        Database db = new Database();
        Lang lang = new Lang();
        string sqlSearch = "select * from Research where ResearcherId=@id";
        db.AddParameter("@id", id);

        if (!string.IsNullOrWhiteSpace(title))
        {
            sqlSearch += " and Title like '%' + @title + '%'";
            db.AddParameter("@title", title);
        }
        if (from.HasValue)
        {
            sqlSearch += " and AddDate>=@fromDate";
            db.AddParameter("@fromDate", from);
        }
        if (to.HasValue)
        {
            sqlSearch += " and AddDate<=@toDate";
            db.AddParameter("@toDate", to);
        }

        DataTable dt = db.ExecuteDataTable(sqlSearch);
        ListView1.DataSource = dt;
        ListView1.DataBind();
    }
 public void FailIfWrongFieldLabeled()
 {
     var dataspec = new DatabaseSpec();
     dataspec.AddSchema<Categories>();
     var database = new Database(ConnectionString);
     Assert.That(database.Satisfies(dataspec), Is.False);
 }
 public void FailIfIncrementDoesNotMatch()
 {
     var dataspec = new DatabaseSpec();
     dataspec.AddSchema<Shippers>();
     var database = new Database(ConnectionString);
     Assert.That(database.Satisfies(dataspec), Is.False);
 }
        public IEnumerable<object> GetAll(string typeName, string sortColumn, string sortOrder)
        {
            var currentType = Type.GetType(typeName);
            var tableName = (TableNameAttribute)Attribute.GetCustomAttribute(currentType, typeof(TableNameAttribute));
            var uioMaticAttri = (UIOMaticAttribute)Attribute.GetCustomAttribute(currentType, typeof(UIOMaticAttribute));
            var strTableName = tableName.Value;

            var db = (Database)DatabaseContext.Database;
            if(!string.IsNullOrEmpty(uioMaticAttri.ConnectionStringName))
                db = new Database(uioMaticAttri.ConnectionStringName);

            if (strTableName.IndexOf("[") < 0)
            {
                strTableName = "[" + strTableName + "]";
            }

            var query = new Sql().Select("*").From(strTableName);


            if (!string.IsNullOrEmpty(sortColumn) && !string.IsNullOrEmpty(sortOrder))
            {
                var strSortColumn = sortColumn;
                if (strSortColumn.IndexOf("[") < 0)
                {
                    strSortColumn = "[" + strSortColumn + "]";
                }

                query.OrderBy(strSortColumn + " " + sortOrder);
            }

            foreach (dynamic item in db.Fetch<dynamic>(query))
            {
                // get settable public properties of the type
                var props = currentType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                    .Where(x => x.GetSetMethod() != null);

                // create an instance of the type
                var obj = Activator.CreateInstance(currentType);
                

                // set property values using reflection
                var values = (IDictionary<string, object>)item;
                foreach (var prop in props)
                {
                    var columnAttri =
                           prop.GetCustomAttributes().Where(x => x.GetType() == typeof(ColumnAttribute));

                    var propName = prop.Name;
                    if (columnAttri.Any())
                        propName = ((ColumnAttribute)columnAttri.FirstOrDefault()).Name;
                    if(values.ContainsKey(propName))
                        prop.SetValue(obj, values[propName]);
                }

                yield return obj;
            }
            

            
        }
Beispiel #25
0
        public static void UpdateStatus(int id, string tableName, string fileName,string title,  int archiveId, IQueryTable toTable, QueryColumn toStatus, QueryColumn toPrimary)
        {
            NBearLite.DbProviders.DbProvider provider =
                        NBearLite.DbProviders.DbProviderFactory.CreateDbProvider(
                                null,
                                "System.Data.SqlServerCe",
                                @"Data Source=enforce.sdf;
                                  Encrypt Database=True;
                                  Password=enforce_123456;
                                  File Mode=shared read;
                                  Persist Security Info=False;");
            Database database = new Database(provider);

            UpdateSqlSection section = new UpdateSqlSection(database, toTable);
            section.AddColumn(toStatus, 2); // 2 代表已归档
            section.Where(toPrimary == id);
            section.Execute();

            InsertSqlSection insert = new InsertSqlSection(database, DataBases.ArchiveExt);
            insert.AddColumn(DataBases.ArchiveExt.ArchiveID, archiveId);
            insert.AddColumn(DataBases.ArchiveExt.TableName, tableName);
            insert.AddColumn(DataBases.ArchiveExt.PrimaryValue, id);
            insert.AddColumn(DataBases.ArchiveExt.FileName, fileName);
            insert.AddColumn(DataBases.ArchiveExt.Title, title);
            insert.AddColumn(DataBases.ArchiveExt.CreateTime, DateTime.Now);
            insert.AddColumn(DataBases.ArchiveExt.ExchangeGUID, CommonInvoke.NewGuid);
            insert.Execute();
        }
        public void CodeAction(BonoboGitServerContext context)
        {
            _db = context.Database;

            if (UpgradeHasAlreadyBeenRun())
            {
                return;
            }

            using (var trans = context.Database.BeginTransaction())
            {
                try
                {
                    RenameTables();
                    CreateTables();
                    CopyData();
                    AddRelations();
                    DropRenamedTables();
                    trans.Commit();
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }
Beispiel #27
0
 public SaleProcessor(Database database, IOutgoingCommandEnvelopeRouter envelopeRouter, SaleRepository saleRepository, InventoryRepository inventoryRepository)
 {
     this.database = database;
     this.envelopeRouter = envelopeRouter;
     this.saleRepository = saleRepository;
     this.inventoryRepository = inventoryRepository;
 }
 public void FailIfSeedDoesNotMatch()
 {
     var dataspec = new DatabaseSpec();
     dataspec.AddSchema<Employees>();
     var database = new Database(ConnectionString);
     Assert.That(database.Satisfies(dataspec), Is.False);
 }
        public void CreateSnaphot(string SnapshotName, string SourceDatabase, string SnapshotLocation)
        {
            Database SrcDatabase = _Server.Databases[SourceDatabase];

            Database SnapshotDatabase = new Database(_Server, SnapshotName);
            SnapshotDatabase.DatabaseSnapshotBaseName = SourceDatabase;

            foreach (FileGroup Group in SrcDatabase.FileGroups)
            {
                SnapshotDatabase.FileGroups.Add(new FileGroup(SnapshotDatabase, Group.Name));
                foreach (DataFile File in Group.Files)
                {
                    SnapshotDatabase.FileGroups[Group.Name].Files.Add(
                        new DataFile(
                            SnapshotDatabase.FileGroups[Group.Name],
                            File.Name,
                            SnapshotLocation + @"\" + SnapshotName + "_" + File.Name + ".ss")
                    );
                }
            }

            DropSnapshot(SnapshotName);

            SnapshotDatabase.Create();

            _Repository.Connection.ChangeDatabase(SourceDatabase);
        }
 public void SucceedIfEverythingMatches()
 {
     var dataspec = new DatabaseSpec();
     dataspec.AddSchema<Suppliers>();
     var database = new Database(ConnectionString);
     Assert.That(database.Satisfies(dataspec), Is.True);
 }
 public static Category GetByName(string name)
 {
     object[] row = Database.ReaderRow(Database.ReturnCommand($"select * from tbCategories where catname = '{name}'"));
     return(new Category((byte)row[0], (string)row[1]));
 }
Beispiel #32
0
 /// <summary>
 /// The implementation of this abstract method should initialize the cDBCommandWrapper object
 /// for the Update Command to reconcile changes to the database within the DataSet.
 /// </summary>
 /// <param name="db">The Microsoft.Practices.EnterpriseLibrary.Data object that represents an
 /// abstract database that commands can be run against.</param>
 public abstract DbCommandWrapper InitializeUpdateCommand(Database db);
Beispiel #33
0
 /// <summary>
 /// The implementation of this abstract method should initialize the DBCommandWrapper object
 /// for the Insert Command to reconcile changes to the database within the DataSet.
 /// </summary>
 /// <param name="db">The Microsoft.Practices.EnterpriseLibrary.Data object that represents an
 /// abstract database that commands can be run against.</param>
 public abstract DbCommandWrapper InitializeInsertCommand(Database db);
Beispiel #34
0
 public ApplicationContext()
 {
     Database.EnsureCreated();
 }
 static EntitiesContext()
 {
     // Don't run migrations, ever!
     Database.SetInitializer<EntitiesContext>(null);
 }
Beispiel #36
0
        static void Main(string[] args)
        {
            var connectionString = ConfigurationManager.AppSettings["defaultConnection"];
            if (args.Length > 0)
            {
                connectionString = args[0];
            }

            // Use ConferenceContext as entry point for dropping and recreating DB
            using (var context = new ConferenceContext(connectionString))
            {
                if (context.Database.Exists())
                    context.Database.Delete();

                context.Database.Create();
            }

            Database.SetInitializer<EventStoreDbContext>(null);
            Database.SetInitializer<MessageLogDbContext>(null);
            Database.SetInitializer<BlobStorageDbContext>(null);
            Database.SetInitializer<ConferenceRegistrationDbContext>(null);
            Database.SetInitializer<RegistrationProcessManagerDbContext>(null);
            Database.SetInitializer<PaymentsDbContext>(null);

            DbContext[] contexts =
                new DbContext[] 
                { 
                    new EventStoreDbContext(connectionString),
                    new MessageLogDbContext(connectionString),
                    new BlobStorageDbContext(connectionString),
                    new PaymentsDbContext(connectionString),
                    new RegistrationProcessManagerDbContext(connectionString),
                    new ConferenceRegistrationDbContext(connectionString),
                };

            foreach (DbContext context in contexts)
            {
                var adapter = (IObjectContextAdapter)context;

                var script = adapter.ObjectContext.CreateDatabaseScript();

                context.Database.ExecuteSqlCommand(script);

                context.Dispose();
            }

            using (var context = new ConferenceRegistrationDbContext(connectionString))
            {
                ConferenceRegistrationDbContextInitializer.CreateIndexes(context);
            }

            using (var context = new RegistrationProcessManagerDbContext(connectionString))
            {
                RegistrationProcessManagerDbContextInitializer.CreateIndexes(context);
            }

            using (var context = new PaymentsDbContext(connectionString))
            {
                PaymentsReadDbContextInitializer.CreateViews(context);
            }

            MessagingDbInitializer.CreateDatabaseObjects(connectionString, "SqlBus");
        }
 public static Category GetById(byte id)
 {
     object[] row = Database.ReaderRow(Database.ReturnCommand($"select * from tbCategories where categoryid = '{id}'"));
     return(new Category((byte)row[0], (string)row[1]));
 }
 public KaraokeContext() : base(@"Data Source=DESKTOP-6IUC6KR;Initial Catalog=KaraokeApp;Integrated Security=True")
 {
     Database.SetInitializer(new DropCreateDatabaseIfModelChanges <KaraokeContext>());
 }
Beispiel #39
0
        protected void lbtAccept_Click(object sender, EventArgs e)
        {
            Database database = new Database("PSCPortalConnectionString");
            using (DbConnection connection = database.GetConnection())
            {
                connection.Open();
                User user = UserCollection.GetUserCollection().SingleOrDefault(a => a.Name == Username);
                DbCommand commandLog = database.GetCommand(connection);
                #region LogId
                DbParameter prId = database.GetParameter(System.Data.DbType.Guid, "@Id", Guid.NewGuid());
                commandLog.Parameters.Add(prId);
                #endregion
                #region LogIp
                DbParameter prIp = database.GetParameter(System.Data.DbType.String, "@Ip", Request.UserHostAddress);
                commandLog.Parameters.Add(prIp);
                #endregion
                #region UserId
                DbParameter prUserId = database.GetParameter(System.Data.DbType.Guid, "@UserId", user == null ? Guid.Empty : user.Id);
                commandLog.Parameters.Add(prUserId);
                #endregion
                #region OldData
                DbParameter prOldData = database.GetParameter(System.Data.DbType.String, "@OldData", "");
                commandLog.Parameters.Add(prOldData);
                #endregion
                #region NewData
                DbParameter prNewData = database.GetParameter(System.Data.DbType.String, "@NewData", redHTMLBlog.Content);
                commandLog.Parameters.Add(prNewData);
                #endregion
                #region ObjectId
                DbParameter prObjectId = database.GetParameter(System.Data.DbType.Guid, "@ObjectId", DataId);
                commandLog.Parameters.Add(prObjectId);
                #endregion
                #region ObjectType
                DbParameter prObjectType = database.GetParameter(System.Data.DbType.String, "@ObjectType", "HTMLBlog");
                commandLog.Parameters.Add(prObjectType);
                #endregion
                #region ModifiedDate
                DbParameter prModifiedDate = database.GetParameter(System.Data.DbType.DateTime, "@ModifiedDate", DateTime.Now);
                commandLog.Parameters.Add(prModifiedDate);
                #endregion
                commandLog.CommandText = "IF (EXISTS(SELECT 1 FROM HTMLBlog WHERE DataId=@ObjectId)) ";
                commandLog.CommandText += "BEGIN ";
                commandLog.CommandText += "set @OldData = (select HTMLBlogContent from HTMLBlog where DataId=@ObjectId) ";
                commandLog.CommandText += "INSERT INTO LogData (Id,Ip,UserId,OldData,NewData,ObjectId,ObjectType,ModifiedDate) VALUES (@Id, @Ip,@UserId,@OldData,@NewData,@ObjectId,@ObjectType,@ModifiedDate) ";
                commandLog.CommandText += "END ";
                commandLog.CommandText += "ELSE ";
                commandLog.CommandText += "BEGIN ";
                commandLog.CommandText += "INSERT INTO LogData (Id,Ip,UserId,OldData,NewData,ObjectId,ObjectType,ModifiedDate) VALUES (@Id, @Ip,@UserId,NULL,@NewData,@ObjectId,@ObjectType,@ModifiedDate) ";
                commandLog.CommandText += "END ";
                commandLog.ExecuteNonQuery();

                DbCommand command = database.GetCommand(connection);
                #region DataId
                DbParameter prDataId = database.GetParameter();
                prDataId.DbType = System.Data.DbType.Guid;
                prDataId.Direction = System.Data.ParameterDirection.InputOutput;
                prDataId.ParameterName = "@DataId";
                prDataId.Value = DataId;
                command.Parameters.Add(prDataId);
                #endregion
                #region HTMLBlogContent
                DbParameter prHTMLBlogContent = database.GetParameter();
                prHTMLBlogContent.DbType = System.Data.DbType.String;
                prHTMLBlogContent.Direction = System.Data.ParameterDirection.InputOutput;
                prHTMLBlogContent.ParameterName = "@HTMLBlogContent";
                prHTMLBlogContent.Value = redHTMLBlog.Content;
                command.Parameters.Add(prHTMLBlogContent);
                #endregion
                command.CommandText = "IF (EXISTS(SELECT 1 FROM HTMLBlog WHERE DataId=@DataId)) ";
                command.CommandText += "BEGIN ";
                command.CommandText += "UPDATE HTMLBlog SET HTMLBlogContent=@HTMLBlogContent WHERE DataId=@DataId ";
                command.CommandText += "END ";
                command.CommandText += "ELSE ";
                command.CommandText += "BEGIN ";
                command.CommandText += "INSERT INTO HTMLBlog (DataId, HTMLBlogContent) VALUES (@DataId, @HTMLBlogContent) ";
                command.CommandText += "END ";
                command.ExecuteNonQuery();
                connection.Close();
            }
            Accept();
        }
 /// <summary>
 /// Set database initializer
 /// </summary>
 public virtual void SetDatabaseInitializer(int databaseinstallmodel)
 {
     var initializer = new CreateCeDatabaseIfNotExists<BaseObjectContext>();
     Database.SetInitializer(initializer);
 }
Beispiel #41
0
        static void Main(string[] args)
        {
            Database.SetInitializer(new DropCreateDatabaseAlways <ManyToManyDbEntity>());
            //Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ManyToManyDbEntity>());

            using (ManyToManyDbEntity db = new ManyToManyDbEntity())
            {
                Product p1 = new Product {
                    Name = "Nokia Lumia 930", Price = 9000
                };
                Product p2 = new Product {
                    Name = "Nokia Lumia 830", Price = 6000
                };
                Product p3 = new Product {
                    Name = "Samsung Galaxy S5", Price = 10000
                };
                Product p4 = new Product {
                    Name = "Samsung Galaxy S4", Price = 6000
                };

                db.Products.AddRange(new List <Product> {
                    p1, p2, p3, p4
                });
                db.SaveChanges();

                Order order1 = new Order {
                    Customer = "Nazar", Quantity = 1
                };
                order1.Product.Add(p1);
                order1.Product.Add(p2);
                order1.Product.Add(p4);

                Order order2 = new Order {
                    Customer = "Alex", Quantity = 2
                };
                order2.Product.Add(p1);
                order2.Product.Add(p3);
                order2.Product.Add(p4);

                db.Orders.AddRange(new List <Order> {
                    order1, order2
                });
                db.SaveChanges();

                foreach (var itemProd in db.Products.Include(p => p.Order))
                {
                    Console.WriteLine("{0}.{1}", itemProd.Id, itemProd.Name);

                    if (itemProd.Order == null)
                    {
                        continue;
                    }

                    foreach (var itemOrder in itemProd.Order)
                    {
                        Console.WriteLine("{0}.{1}", itemOrder.Id, itemOrder.Customer);
                    }
                    Console.WriteLine("-----------------------------------------");
                }

                Console.WriteLine("-----------------------------------------");
                Console.ReadKey();

                foreach (var itemOrder in db.Orders.Include(p => p.Product))
                {
                    Console.WriteLine("{0}.{1}", itemOrder.Id, itemOrder.Customer);

                    if (itemOrder.Product == null)
                    {
                        continue;
                    }

                    foreach (var itemProd in itemOrder.Product)
                    {
                        Console.WriteLine("{0}.{1} - {2}", itemProd.Id, itemProd.Name, itemProd.Price);
                    }
                    Console.WriteLine("-----------------------------------------");
                }
            }
        }
Beispiel #42
0
 public NFeContext()
     : base("name=NotasFiscais")
 {
     Database.SetInitializer<NFeContext>(null);
 }
Beispiel #43
0
 static DotnetCore22DBContext()
 {
     Database.SetInitializer <DotnetCore22DBContext>(null);
 }
Beispiel #44
0
        private void cmdDELETE_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime tglmemo   = ((DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value).Date;
                DateTime tglserver = GlobalVar.DateTimeOfServer.Date;
                switch (selectedGrid)
                {
                case enumSelectedGrid.HeaderSelected:
                    if (dataGridHeader.SelectedCells.Count == 0)
                    {
                        MessageBox.Show(Messages.Error.RowNotSelected);
                    }

                    if (tipeLokasi == "G")
                    {
                        MessageBox.Show("Anda tidak punya wewenang hapus data");
                        return;
                    }

                    if (bool.Parse(dataGridHeader.SelectedCells[0].OwningRow.Cells["isClosed"].Value.ToString()) == true)
                    {
                        MessageBox.Show("Tidak bisa hapus data sudah di audit");
                        return;
                    }

                    //if (dataGridHeader.SelectedCells[0].OwningRow.Cells["TglGudang"].Value.ToString() != "")
                    //{
                    //    MessageBox.Show("Sudah dibuat nota retur. Tidak bisa di hapus...!!!");
                    //    return;
                    //}

                    if (tglmemo != tglserver)
                    {
                        MessageBox.Show("Tidak bisa hapus record. Tanggal server beda dengan Tanggal Memo");
                        return;
                    }

                    if (dataGridDetail.Rows.Count > 0)
                    {
                        MessageBox.Show("Hapus detail dulu...!");
                        return;
                    }
                    if (!SecurityManager.IsManager())
                    {
                        MessageBox.Show("Hapus hanya dapat dilakukan oleh manager");
                        return;
                    }

                    //GlobalVar.LastClosingDate = (DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value;
                    //if ((DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value <= GlobalVar.LastClosingDate)
                    //{
                    //    throw new Exception(String.Format(Messages.Error.AlreadyClosingPJT, GlobalVar.LastClosingDate));
                    //}
                    if (MessageBox.Show("Hapus record ini?", "DELETE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        Guid rowID = (Guid)dataGridHeader.SelectedCells[0].OwningRow.Cells["HeaderRowID"].Value;
                        try
                        {
                            this.Cursor = Cursors.WaitCursor;
                            using (Database db = new Database())
                            {
                                DataTable dt = new DataTable();
                                db.Commands.Add(db.CreateCommand("usp_ReturPenjualan_DELETE"));     //cek heri
                                db.Commands[0].Parameters.Add(new Parameter("@rowID", SqlDbType.UniqueIdentifier, rowID));

                                db.Commands[0].ExecuteNonQuery();
                            }

                            MessageBox.Show("Record telah dihapus");
                            this.RefreshDataReturJual();
                        }
                        catch (Exception ex)
                        {
                            Error.LogError(ex);
                        }
                        finally
                        {
                            this.Cursor = Cursors.Default;
                        }
                    }
                    break;

                case enumSelectedGrid.DetailSelected:
                    if (dataGridDetail.SelectedCells.Count == 0)
                    {
                        MessageBox.Show(Messages.Error.RowNotSelected);
                        return;
                    }

                    if (tipeLokasi == "G")
                    {
                        MessageBox.Show("Anda tidak punya wewenang hapus data");
                        return;
                    }

                    if (bool.Parse(dataGridHeader.SelectedCells[0].OwningRow.Cells["isClosed"].Value.ToString()) == true)
                    {
                        MessageBox.Show("Tidak bisa hapus data sudah di audit");
                        return;
                    }

                    //if (dataGridHeader.SelectedCells[0].OwningRow.Cells["TglGudang"].Value.ToString() != "")
                    //{
                    //    MessageBox.Show("Sudah dibuat nota retur. Tidak bisa di hapus...!!!");
                    //    return;
                    //}

                    bool link = (bool)(dataGridDetail.SelectedCells[0].OwningRow.Cells["DetailSyncFlag"].Value);
                    if (link)
                    {
                        MessageBox.Show("Sudah Link ke Piutang, tidak bisa dihapus");
                        return;
                    }

                    if (tglmemo != tglserver)
                    {
                        MessageBox.Show("Tidak bisa hapus record. Tanggal server beda dengan Tanggal Memo");
                        return;
                    }

                    if (!SecurityManager.IsManager())
                    {
                        MessageBox.Show("Hapus hanya dapat dilakukan oleh manager");
                        return;
                    }

                    GlobalVar.LastClosingDate = (DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value;
                    if ((DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value <= GlobalVar.LastClosingDate)
                    {
                        throw new Exception(String.Format(Messages.Error.AlreadyClosingPJT, GlobalVar.LastClosingDate));
                    }
                    if (MessageBox.Show("Hapus record ini?", "DELETE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        Guid   rowID     = (Guid)dataGridDetail.SelectedCells[0].OwningRow.Cells["DetailRowID"].Value;
                        string kodeRetur = dataGridDetail.SelectedCells[0].OwningRow.Cells["KodeRetur"].Value.ToString();
                        string type_usp_DELETE;

                        if (kodeRetur == "1")
                        {
                            type_usp_DELETE = "usp_ReturPenjualanDetail_DELETE";     //cek heri
                        }
                        else
                        {
                            type_usp_DELETE = "usp_ReturPenjualanTarikanDetail_DELETE";     //cek heri
                        }
                        try
                        {
                            this.Cursor = Cursors.WaitCursor;
                            using (Database db = new Database())
                            {
                                db.Commands.Add(db.CreateCommand(type_usp_DELETE));
                                db.Commands[0].Parameters.Add(new Parameter("@rowID", SqlDbType.UniqueIdentifier, rowID));
                                db.Commands[0].ExecuteNonQuery();
                            }

                            MessageBox.Show("Record telah dihapus");
                            this.RefreshDataReturJualDetail();
                        }
                        catch (Exception ex)
                        {
                            Error.LogError(ex);
                        }
                        finally
                        {
                            this.Cursor = Cursors.Default;
                        }
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                Error.LogError(ex);
            }
        }
        private static void ProcessMediaUpload(Stream content, Database db, string path, bool skipExisting = false)
        {
            var guidPattern = @"(?<id>{[a-z0-9]{8}[-][a-z0-9]{4}[-][a-z0-9]{4}[-][a-z0-9]{4}[-][a-z0-9]{12}})";

            path = path.Replace('\\', '/').TrimEnd('/');
            path = (path.StartsWith("/") ? path : "/" + path);
            var originalPath = path;
            var dotIndex     = path.IndexOf(".", StringComparison.OrdinalIgnoreCase);

            if (dotIndex > -1)
            {
                path = path.Substring(0, dotIndex);
            }

            if (!path.StartsWith(Constants.MediaLibraryPath))
            {
                path = Constants.MediaLibraryPath + (path.StartsWith("/") ? path : "/" + path);
            }

            var mediaItem = (MediaItem)db.GetItem(path);

            if (mediaItem == null && Regex.IsMatch(originalPath, guidPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase))
            {
                var id = Regex.Match(originalPath, guidPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase).Value;
                mediaItem = db.GetItem(id);
            }

            if (mediaItem == null)
            {
                var fileName = Path.GetFileName(originalPath);
                var itemName = Path.GetFileNameWithoutExtension(path);
                var dirName  = (Path.GetDirectoryName(path) ?? string.Empty).Replace('\\', '/');

                if (String.IsNullOrEmpty(fileName))
                {
                    PowerShellLog.Warn($"The filename cannot be determined for the entry {fileName}.");
                    return;
                }

                var mco = new MediaCreatorOptions
                {
                    Database    = db,
                    Versioned   = Settings.Media.UploadAsVersionableByDefault,
                    Destination = $"{dirName}/{itemName}",
                };

                var mc = new MediaCreator();
                using (var ms = new MemoryStream())
                {
                    content.CopyTo(ms);
                    mc.CreateFromStream(ms, fileName, mco);
                }
            }
            else
            {
                if (skipExisting)
                {
                    return;
                }

                var mediaUri = MediaUri.Parse(mediaItem);
                var media    = MediaManager.GetMedia(mediaUri);

                using (var ms = new MemoryStream())
                {
                    content.CopyTo(ms);
                    using (new EditContext(mediaItem, SecurityCheck.Disable))
                    {
                        using (var mediaStream = new MediaStream(ms, media.Extension, mediaItem))
                        {
                            media.SetStream(mediaStream);
                        }
                    }
                }
            }
        }
Beispiel #46
0
        public void HandleRequest(HttpListenerContext context)
        {
            NameValueCollection query;

            using (StreamReader rdr = new StreamReader(context.Request.InputStream))
                query = HttpUtility.ParseQueryString(rdr.ReadToEnd());

            using (var db = new Database())
            {
                List <ServerItem> filteredServers = null;
                Account           a = db.Verify(query["guid"], query["password"]);
                if (a != null)
                {
                    if (a.Banned)
                    {
                        filteredServers = YoureBanned();
                    }
                    else
                    {
                        filteredServers = GetServersForRank(a.Rank);
                    }
                }
                else
                {
                    filteredServers = GetServersForRank(0);
                }

                Chars chrs = new Chars()
                {
                    Characters = new List <Char>()
                    {
                    },
                    NextCharId  = 2,
                    MaxNumChars = 1,
                    Account     = db.Verify(query["guid"], query["password"]),
                    Servers     = filteredServers
                };
                Account dvh = null;
                if (chrs.Account != null)
                {
                    db.GetCharData(chrs.Account, chrs);
                    db.LoadCharacters(chrs.Account, chrs);
                    chrs.News = db.GetNews(chrs.Account);
                    dvh       = chrs.Account;
                }
                else
                {
                    chrs.Account = Database.CreateGuestAccount(query["guid"]);
                    chrs.News    = db.GetNews(null);
                }

                MemoryStream  ms         = new MemoryStream();
                XmlSerializer serializer = new XmlSerializer(chrs.GetType(), new XmlRootAttribute(chrs.GetType().Name)
                {
                    Namespace = ""
                });

                XmlWriterSettings xws = new XmlWriterSettings();
                xws.OmitXmlDeclaration = true;
                xws.Encoding           = Encoding.UTF8;
                XmlWriter xtw = XmlWriter.Create(context.Response.OutputStream, xws);
                serializer.Serialize(xtw, chrs, chrs.Namespaces);
            }
        }
Beispiel #47
0
 public void Cleanup()
 {
     Database.Cleanup();
 }
        public void ProcessRequest(HttpContext context)
        {
            var request           = context.Request;
            var requestParameters = request.Params;

            var username   = requestParameters.Get("user");
            var password   = requestParameters.Get("password");
            var authHeader = request.Headers["Authorization"];

            if (string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(authHeader))
            {
                if (authHeader.StartsWith("Basic"))
                {
                    var encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
                    var encoding         = Encoding.GetEncoding("iso-8859-1");
                    var usernamePassword = encoding.GetString(System.Convert.FromBase64String(encodedUsernamePassword));

                    var separatorIndex = usernamePassword.IndexOf(':');

                    username = usernamePassword.Substring(0, separatorIndex);
                    password = usernamePassword.Substring(separatorIndex + 1);
                }
            }

            var itemParam         = requestParameters.Get("script");
            var pathParam         = requestParameters.Get("path");
            var originParam       = requestParameters.Get("scriptDb");
            var sessionId         = requestParameters.Get("sessionId");
            var persistentSession = requestParameters.Get("persistentSession").Is("true");
            var rawOutput         = requestParameters.Get("rawOutput").Is("true");
            var apiVersion        = requestParameters.Get("apiVersion");
            var serviceMappingKey = request.HttpMethod + "/" + apiVersion;
            var isUpload          = request.HttpMethod.Is("POST") && request.InputStream.Length > 0;
            var unpackZip         = requestParameters.Get("skipunpack").IsNot("true");
            var skipExisting      = requestParameters.Get("skipexisting").Is("true");
            var scDb = requestParameters.Get("sc_database");

            var serviceName = ApiVersionToServiceMapping.ContainsKey(serviceMappingKey)
                ? ApiVersionToServiceMapping[serviceMappingKey]
                : string.Empty;

            // verify that the service is enabled
            if (!CheckServiceEnabled(context, apiVersion, request.HttpMethod))
            {
                return;
            }

            // verify that the user is authorized to access the end point
            var authUserName = string.IsNullOrEmpty(username) ? Context.User.Name : username;
            var identity     = new AccountIdentity(authUserName);

            if (!CheckIsUserAuthorized(context, identity.Name, serviceName))
            {
                return;
            }

            lock (LoginLock)
            {
                // login user if specified explicitly
                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    AuthenticationManager.Login(identity.Name, password, false);
                }
            }

            var isAuthenticated = Context.IsLoggedIn;

            if (!CheckServiceAuthentication(context, serviceName, identity, isAuthenticated))
            {
                return;
            }

            var useContextDatabase = apiVersion.Is("file") || apiVersion.Is("handle") || !isAuthenticated ||
                                     string.IsNullOrEmpty(originParam) || originParam.Is("current");

            // in some cases we need to set the database as it's still set to web after authentication
            if (!scDb.IsNullOrEmpty())
            {
                Context.Database = Database.GetDatabase(scDb);
            }

            var scriptDb = useContextDatabase ? Context.Database : Database.GetDatabase(originParam);
            var dbName   = scriptDb?.Name;

            if (scriptDb == null && !apiVersion.Is("file") && !apiVersion.Is("handle"))
            {
                PowerShellLog.Error($"The '{serviceMappingKey}' service requires a database but none was found in parameters or Context.");
                return;
            }

            PowerShellLog.Info($"'{serviceMappingKey}' called by user: '******'");
            PowerShellLog.Debug($"'{request.Url}'");

            Item scriptItem = null;

            switch (apiVersion)
            {
            case "1":
                scriptItem = scriptDb.GetItem(itemParam) ??
                             scriptDb.GetItem(ApplicationSettings.ScriptLibraryPath + itemParam);
                break;

            case "media":
                ProcessMedia(context, isUpload, scriptDb, itemParam, unpackZip, skipExisting);
                return;

            case "file":
                ProcessFile(context, isUpload, originParam, pathParam);
                return;

            case "handle":
                ProcessHandle(context, originParam);
                return;

            case "2":
                var apiScripts = GetApiScripts(dbName);
                if (apiScripts.ContainsKey(dbName))
                {
                    var dbScripts = apiScripts[dbName];
                    if (dbScripts.ContainsKey(itemParam))
                    {
                        scriptItem = scriptDb.GetItem(dbScripts[itemParam].Id);
                    }
                }

                if (scriptItem == null)
                {
                    context.Response.StatusCode        = 404;
                    context.Response.StatusDescription = "The specified script is invalid.";
                    return;
                }
                break;

            case "script":
                ProcessScript(context, request, rawOutput, sessionId, persistentSession);
                return;

            default:
                PowerShellLog.Error($"Requested API/Version ({serviceMappingKey}) is not supported.");
                return;
            }

            ProcessScript(context, scriptItem);
        }
Beispiel #49
0
 public ApplicationContext() : base("DefaultConnection")
 {
     Database.SetInitializer(new ApplicationInitializer());
 }
Beispiel #50
0
 private Database db;//数据库操作对象。
 /// <summary>
 /// 构造函数。
 /// </summary>
 public SampEngine()
 {
     db = DatabaseFactory.CreateDatabase();
 }
Beispiel #51
0
        public static string GetAreaBound()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            //PromptKeywordOptions pkOp = new PromptKeywordOptions("");
            //pkOp.Message = "\nUse Island Detection ";
            //pkOp.Keywords.Add("Yes");
            //pkOp.Keywords.Add("No");
            //pkOp.AllowNone = false;
            //PromptResult pr = ed.GetKeywords(pkOp);
            //if (pr.Status == PromptStatus.Cancel)
            //{
            //    return null;
            //}
            //string pkostr = pr.StringResult;
            //bool flagIsland = false;
            //if (pkostr == "Yes") { flagIsland = true; } else { flagIsland = false; }
            PromptPointResult ppr = ed.GetPoint("\nSelect Internal Point on Closed Area: ");
            if (ppr.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\n" + ppr.StringResult);
            }
            string value = null;
            DBObjectCollection dbObjColl = ed.TraceBoundary(ppr.Value, false);
            Double area = 0;
            try
            {
                if (dbObjColl.Count > 0)
                {
                    Transaction tr = doc.TransactionManager.StartTransaction();
                    using (tr)
                    {
                        BlockTable bt = (BlockTable)
                           tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead);
                        BlockTableRecord btr = (BlockTableRecord)
                            tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
                        ObjectIdCollection objIds = new ObjectIdCollection();
                        foreach (DBObject Obj in dbObjColl)
                        {
                            Entity ent = Obj as Entity;
                            if (ent != null)
                            {
                                // ent.GetField("Area");
                                if (ent is Polyline)
                                {
                                    Polyline p = (Polyline)ent;
                                    if (p.Closed)
                                    {
                                        area = p.Area;
                                        string presisi = "#";
                                        switch (db.Auprec)
                                        {
                                            case 0:
                                                presisi = "#";
                                                break;
                                            case 1:
                                                presisi = "#0.0";
                                                break;
                                            case 2:
                                                presisi = "#0.00";
                                                break;
                                            case 3:
                                                presisi = "#0.000";
                                                break;
                                            case 4:
                                                presisi = "#0.0000";
                                                break;
                                            case 5:
                                                presisi = "#0.00000";
                                                break;
                                            default:
                                                presisi = "#0.00";
                                                break;
                                        }
                                        value = area.ToString(presisi);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch
            {

                throw;
            }
            return value;
        }
Beispiel #52
0
 public void Initialize()
 {
     Database.Initialize();
     Cleanup();
 }
 public int UpdateCategoryItemsCount(int categoryID)
 {
     return(Database.ExecuteSqlCommand("UPDATE CategoryStats SET COUNT = COUNT + 1 WHERE CategoryID = @p0", categoryID));
 }
Beispiel #54
0
        public static void testAttributedBlockInsert()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            // change block name to your suit

            PromptEntityOptions pEnOpt = new PromptEntityOptions("\nPick Block Reference:");
            pEnOpt.SetRejectMessage("\nObject Not Block Reference");
            pEnOpt.AddAllowedClass(typeof(BlockReference), true);

            PromptEntityResult pEnRes = ed.GetEntity(pEnOpt);
            ObjectId EntId = pEnRes.ObjectId;
            //PromptResult pr = ed.GetString("\nType Block Name: ");
            //string blockName = pr.StringResult;
            string blockName = null;
            BlockReference UserBlockref = null;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                UserBlockref = (BlockReference)trans.GetObject(EntId, OpenMode.ForRead);
                blockName = UserBlockref.Name;
            }
            Matrix3d ucs = ed.CurrentUserCoordinateSystem;
            //get current UCS matrix
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    // to force update drawing screen
                    doc.TransactionManager.EnableGraphicsFlush(true);
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite);

                    // if the block table doesn't already exists, exit
                    if (!bt.Has(blockName))
                    {
                        Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Block " + blockName + " does not exist.");
                        return;
                    }

                    // insert the block in the current space
                    PromptPointResult ppr = ed.GetPoint("\nSpecify insertion point: ");
                    if (ppr.Status != PromptStatus.OK)
                    {
                        return;
                    }
                    DBObjectCollection dbobjcoll = ed.TraceBoundary(ppr.Value, false);
                    Double area = 0;
                    try
                    {
                        if (dbobjcoll.Count > 0)
                        {
                            BlockTableRecord blockTableRecmSpace = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
                            ObjectIdCollection traceObjIds = new ObjectIdCollection();
                            foreach (DBObject obj in dbobjcoll)
                            {
                                Entity EntTrace = obj as Entity;
                                if (EntTrace != null)
                                {
                                    if (EntTrace is Polyline)
                                    {
                                        Polyline p = (Polyline)EntTrace;
                                        if (p.Closed)
                                        {
                                            area = p.Area;
                                        }

                                    }
                                    if (EntTrace is Line)
                                    {
                                        Line Ln = (Line)EntTrace;
                                        if (Ln.Closed)
                                        {
                                            area = Ln.Area;
                                        }

                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                        throw;
                    }
                    string presisi = "#";
                    switch (db.Auprec)
                    {
                        case 0:
                            presisi = "#";
                            break;
                        case 1:
                            presisi = "#0.0";
                            break;
                        case 2:
                            presisi = "#0.00";
                            break;
                        case 3:
                            presisi = "#0.000";
                            break;
                        case 4:
                            presisi = "#0.0000";
                            break;
                        case 5:
                            presisi = "#0.00000";
                            break;
                        default:
                            presisi = "#0.00";
                            break;
                    }

                    valueAreaBoundary = area.ToString(presisi);

                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                    ObjectContextCollection occ = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES");
                    List<string> ListTag = new List<string>();
                    List<string> ListString = new List<string>();

                    Point3d pt = ppr.Value;
                    BlockReference bref = new BlockReference(pt, bt[blockName]);

                    Dictionary<string, string> dic = GetAttributDef(bref.BlockTableRecord, tr);
                    foreach (KeyValuePair<string, string> item in dic)
                    {
                        ListTag.Add(item.Key.ToUpper().ToString());
                        // string[] info = item.Value.Split('|');
                    }
                    formUserInputAttribut frmInput = new formUserInputAttribut();
                    IntPtr handle = AcAp.MainWindow.Handle;
                    if (frmInput.ShowDialog(ListTag) == System.Windows.Forms.DialogResult.OK)
                    {
                        ListString.AddRange(frmInput.InputString);
                    }
                    else { return; }

                    bref.Rotation = frmInput.UseRotation ? UserBlockref.Rotation : 0.0;

                    bref.TransformBy(ucs);
                    bref.AddContext(occ.CurrentContext);
                    //add blockreference to current space
                    btr.AppendEntity(bref);
                    tr.AddNewlyCreatedDBObject(bref, true);
                    // set attributes to desired values

                    ApplyAttibutes(db, tr, bref, ListTag, ListString);

                    bref.RecordGraphicsModified(true);
                    // to force updating a block reference
                    tr.TransactionManager.QueueForGraphicsFlush();
                    tr.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message);
            }
            finally
            {
                // Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Pokey")
            }
        }
        public async Task <ActionResult> GetByFileDataID(string buildConfig, string cdnConfig, string ids, string filename)
        {
            var filedataidlist = new List <uint>();

            foreach (var fdid in ids.Split(','))
            {
                filedataidlist.Add(uint.Parse(fdid));
            }

            var filedataids = filedataidlist.ToArray();

            if (string.IsNullOrEmpty(buildConfig) || string.IsNullOrEmpty(cdnConfig) || filedataids.Length == 0 || string.IsNullOrEmpty(filename))
            {
                throw new NullReferenceException("Invalid arguments!");
            }

            Logger.WriteLine("Serving zip file \"" + filename + "\" (" + filedataids.Length + " fdids starting with " + filedataids[0].ToString() + ") for build " + buildConfig + " and cdn " + cdnConfig);

            var errors = new List <string>();

            using (var zip = new MemoryStream())
            {
                using (var archive = new ZipArchive(zip, ZipArchiveMode.Create))
                {
                    foreach (var filedataid in filedataids)
                    {
                        if (zip.Length > 100000000)
                        {
                            errors.Add("Max of 100MB per archive reached, didn't include file " + filedataid);
                            Logger.WriteLine("Max of 100MB per archive reached!");
                            continue;
                        }

                        try
                        {
                            using (var cascStream = new MemoryStream(await CASC.GetFile(buildConfig, cdnConfig, filedataid)))
                            {
                                var entryname = Path.GetFileName(await Database.GetFilenameByFileDataID(filedataid));
                                if (entryname == "")
                                {
                                    entryname = filedataid.ToString() + ".unk";
                                }

                                var entry = archive.CreateEntry(entryname);
                                using (var entryStream = entry.Open())
                                {
                                    cascStream.CopyTo(entryStream);
                                }
                            }
                        }
                        catch (FileNotFoundException)
                        {
                            errors.Add("File " + filedataid + " not found in root of buildconfig " + buildConfig + " cdnconfig " + cdnConfig);
                            Logger.WriteLine("File " + filedataid + " not found in root of buildconfig " + buildConfig + " cdnconfig " + cdnConfig);
                        }
                        catch (Exception e)
                        {
                            errors.Add("Error " + e.Message + " occured when getting file " + filedataid);
                            Logger.WriteLine("Error " + e.Message + " occured when getting file " + filedataid + " of buildconfig " + buildConfig + " cdnconfig " + cdnConfig);
                        }
                    }

                    if (errors.Count > 0)
                    {
                        using (var errorStream = new MemoryStream())
                        {
                            var entry = archive.CreateEntry("errors.txt");
                            using (var entryStream = entry.Open())
                            {
                                foreach (var error in errors)
                                {
                                    entryStream.Write(Encoding.UTF8.GetBytes(error + "\n"));
                                }
                            }
                        }
                    }
                }

                return(new FileContentResult(zip.ToArray(), "application/octet-stream")
                {
                    FileDownloadName = filename
                });
            }
        }
		internal static void Generate(
			DBConnection cn, TextWriter writer, string baseNamespace, Database database,
			RedStapler.StandardLibrary.Configuration.SystemDevelopment.Database configuration ) {
			if( configuration.rowConstantTables == null )
				return;

			writer.WriteLine( "namespace " + baseNamespace + "." + database.SecondaryDatabaseName + "RowConstants {" );
			foreach( var table in configuration.rowConstantTables ) {
				Column valueColumn;
				var orderIsSpecified = !table.orderByColumn.IsNullOrWhiteSpace();
				var values = new List<string>();
				var names = new List<string>();
				try {
					var columns = new TableColumns( cn, table.tableName, false );
					valueColumn = columns.AllColumnsExceptRowVersion.Single( column => column.Name.ToLower() == table.valueColumn.ToLower() );
					var nameColumn = columns.AllColumnsExceptRowVersion.Single( column => column.Name.ToLower() == table.nameColumn.ToLower() );

					var cmd = new InlineSelect(
						new[] { valueColumn.Name, nameColumn.Name },
						"FROM " + table.tableName,
						false,
						orderByClause: orderIsSpecified ? "ORDER BY " + table.orderByColumn : "" );
					cmd.Execute(
						cn,
						reader => {
							while( reader.Read() ) {
								if( reader.IsDBNull( reader.GetOrdinal( valueColumn.Name ) ) )
									values.Add( valueColumn.NullValueExpression.Any() ? valueColumn.NullValueExpression : "null" );
								else {
									var valueString = valueColumn.ConvertIncomingValue( reader[ valueColumn.Name ] ).ToString();
									values.Add( valueColumn.DataTypeName == typeof( string ).ToString() ? "\"{0}\"".FormatWith( valueString ) : valueString );
								}
								names.Add( nameColumn.ConvertIncomingValue( reader[ nameColumn.Name ] ).ToString() );
							}
						} );
				}
				catch( Exception e ) {
					throw new UserCorrectableException(
						"Column or data retrieval failed for the " + table.tableName + " row constant table. Make sure the table and the value, name, and order by columns exist.",
						e );
				}

				CodeGenerationStatics.AddSummaryDocComment( writer, "Provides constants copied from the " + table.tableName + " table." );
				var className = table.tableName.TableNameToPascal( cn ) + "Rows";
				writer.WriteLine( "public class " + className + " {" );

				// constants
				for( var i = 0; i < values.Count; i++ ) {
					CodeGenerationStatics.AddSummaryDocComment( writer, "Constant generated from row in database table." );
					// It's important that row constants actually *be* constants (instead of static readonly) so they can be used in switch statements.
					writer.WriteLine( "public const " + valueColumn.DataTypeName + " " + StandardLibraryMethods.GetCSharpIdentifier( names[ i ] ) + " = " + values[ i ] + ";" );
				}

				// one to one map
				var dictionaryType = "OneToOneMap<" + valueColumn.DataTypeName + ", string>";
				writer.WriteLine( "private static readonly " + dictionaryType + " " + dictionaryName + " = new " + dictionaryType + "();" );

				writeStaticConstructor( writer, className, names, values, valueColumn.DataTypeName );

				// methods
				writeGetNameFromValueMethod( writer, valueColumn.DataTypeName );
				writeGetValueFromNameMethod( writer, valueColumn.DataTypeName );
				if( orderIsSpecified ) {
					writeGetValuesToNamesMethod( writer, valueColumn.DataTypeName );
					writeFillListControlMethod( writer, valueColumn );
				}

				writer.WriteLine( "}" ); // class
			}
			writer.WriteLine( "}" ); // namespace
		}
Beispiel #57
0
 public abstract void SaveFiles(Database database, string directory, IList <LoadedDatabaseFile> files);
Beispiel #58
0
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     modelBuilder.Conventions.Remove <PluralizingTableNameConvention>();
     Database.SetInitializer(new DatosdeInicio());//Agrega datos de inicio a la base de datos despues de eliminar la base de datos
 }
Beispiel #59
0
 public abstract IList <LoadedDatabaseFile> LoadFiles(Database database, string directory);
    public static void Main(String[] args)
    {
        Storage storage = StorageFactory.Instance.CreateStorage();

        storage.Open("testcodegenerator.dbs");
        Database db = new Database(storage);

        DateTime start = DateTime.Now;

        for (int i = 0; i < nLabels; i++)
        {
            RecordLabel label = new RecordLabel();
            label.name    = "Label" + i;
            label.email   = "contact@" + label.name + ".com";
            label.address = "Country, City, Street";
            label.phone   = "+1 123-456-7890";
            db.AddRecord(label);
        }

        for (int i = 0; i < nAlbums; i++)
        {
            Album album = new Album();
            album.name    = "Album" + i;
            album.label   = (RecordLabel)Enumerable.First(db.Select(typeof(RecordLabel), "name='Label" + (i % nLabels) + "'"));
            album.genre   = "Rock";
            album.release = DateTime.Now;
            db.AddRecord(album);

            for (int j = 0; j < nTracksPerAlbum; j++)
            {
                Track track = new Track();
                track.no       = j + 1;
                track.name     = "Track" + j;
                track.album    = album;
                track.duration = 3.5f;
                db.AddRecord(track);
            }
        }

        Console.WriteLine("Elapsed time for database initialization: " + (DateTime.Now - start));

        QueryExecutionListener listener = new QueryExecutionListener();

        storage.Listener = listener;

        Query         trackQuery = db.CreateQuery(typeof(Track));
        CodeGenerator code       = trackQuery.GetCodeGenerator();

        code.Predicate(code.And(code.Gt(code.Field("no"),
                                        code.Literal(0)),
                                code.Eq(code.Field(code.Field(code.Field("album"), "label"), "name"),
                                        code.Parameter(1, typeof(string)))));
        start = DateTime.Now;
        int nTracks = 0;

        for (int i = 0; i < nLabels; i++)
        {
            trackQuery[1] = "Label" + i;
            foreach (Track t in trackQuery)
            {
                nTracks += 1;
            }
        }
        Console.WriteLine("Elapsed time for searching of " + nTracks + " tracks: " + (DateTime.Now - start));
        Debug.Assert(nTracks == nAlbums * nTracksPerAlbum);

        String prev       = "";
        int    n          = 0;
        Query  labelQuery = db.CreateQuery(typeof(RecordLabel));

        code = labelQuery.GetCodeGenerator();
        code.OrderBy("name");
        foreach (RecordLabel label in labelQuery)
        {
            Debug.Assert(prev.CompareTo(label.name) < 0);
            prev = label.name;
            n   += 1;
        }
        Debug.Assert(n == nLabels);

        prev = "";
        n    = 0;
        code = labelQuery.GetCodeGenerator();
        code.Predicate(code.Like(code.Field("name"),
                                 code.Literal("Label%")));
        code.OrderBy("name");
        foreach (RecordLabel label in labelQuery)
        {
            Debug.Assert(prev.CompareTo(label.name) < 0);
            prev = label.name;
            n   += 1;
        }
        Debug.Assert(n == nLabels);

        n    = 0;
        code = labelQuery.GetCodeGenerator();
        code.Predicate(code.In(code.Field("name"),
                               code.List(code.Literal("Label1"), code.Literal("Label2"), code.Literal("Label3"))));
        foreach (RecordLabel label in labelQuery)
        {
            n += 1;
        }
        Debug.Assert(n == 3);

        n    = 0;
        code = labelQuery.GetCodeGenerator();
        code.Predicate(code.And(code.Or(code.Eq(code.Field("name"),
                                                code.Literal("Label1")),
                                        code.Or(code.Eq(code.Field("name"),
                                                        code.Literal("Label2")),
                                                code.Eq(code.Field("name"),
                                                        code.Literal("Label3")))),
                                code.Like(code.Field("email"),
                                          code.Literal("contact@%"))));
        foreach (RecordLabel label in labelQuery)
        {
            n += 1;
        }
        Debug.Assert(n == 3);

        code = labelQuery.GetCodeGenerator();
        code.Predicate(code.And(code.Like(code.Field("phone"),
                                          code.Literal("+1%")),
                                code.In(code.Field("name"),
                                        code.Parameter(1, typeof(ArrayList)))));
        ArrayList list = new ArrayList(nLabels);

        for (int i = 0; i < nLabels; i++)
        {
            list.Add("Label" + i);
        }
        n             = 0;
        labelQuery[1] = list;
        foreach (RecordLabel label in labelQuery)
        {
            Debug.Assert(label.name == "Label" + n++);
        }
        Debug.Assert(n == nLabels);

        n    = 0;
        code = trackQuery.GetCodeGenerator();
        code.Predicate(code.Or(code.Eq(code.Field(code.Field(code.Field("album"), "label"), "name"),
                                       code.Literal("Label1")),
                               code.Eq(code.Field(code.Field(code.Field("album"), "label"), "name"),
                                       code.Literal("Label2"))));
        foreach (Track track in trackQuery)
        {
            Debug.Assert(track.album.label.name == "Label1" || track.album.label.name == "Label2");
            n += 1;
        }
        Debug.Assert(n == nAlbums * nTracksPerAlbum * 2 / nLabels);

        Debug.Assert(listener.nSequentialSearches == 0);
        Debug.Assert(listener.nSorts == 0);


        db.DropTable(typeof(Track));
        db.DropTable(typeof(Album));
        db.DropTable(typeof(RecordLabel));

        storage.Close();
    }