Example #1
0
        public async Task Relations_Zero_One_And_One_One_Async()
        {
            var db = new Db();
            db.Initialize(TestConstants.SqlClientConnectionString, "System.Data.SqlClient");

            var result = await db.CreateCommand("select * from [dbo].[BaseTable] where id=@id")
                .AddParameter("@id", 5)
                .ReadOneMapToAsync<BaseTable>();

            // zero one
            if (result.ZeroOneId.HasValue)
            {
                var zeroOne = await db.CreateCommand("Select * from [dbo].[ZeroOne] where Id=@id")
                  .AddParameter("@id", result.ZeroOneId)
                  .ReadOneMapToAsync<ZeroOne>();

                result.ZeroOne = zeroOne;
            }

            // one one
            var oneOne = await db.CreateCommand("Select * from [dbo].[OneOne] where Id=@id")
                .AddParameter("@id", result.OneOneId)
                .ReadOneMapToAsync<OneOne>();

            result.OneOne = oneOne;

            Assert.AreEqual(result.Name.TrimEnd(), "Base 2");
            Assert.IsTrue(result.ZeroOneId.HasValue && result.ZeroOneId == 1);
            Assert.AreEqual(result.ZeroOne.Id, 1);
            Assert.AreEqual(result.ZeroOne.Name, "Zero 1");
            Assert.AreEqual(result.OneOneId, 3);
            Assert.AreEqual(result.OneOne.Id, 3);
            Assert.AreEqual(result.OneOne.Name, "One 2");
        }
Example #2
0
        public void Relations_Zero_One_And_One_One()
        {
            var db = new Db();
            db.Initialize(TestConstants.SqlClientConnectionString, "System.Data.SqlClient");

            var result = db.CreateCommand("select * from [dbo].[BaseTable] where id=@id")
                .AddParameter("@id", 4)
                .ReadOneMapTo<BaseTable>();

            // zero one
            if (result.ZeroOneId.HasValue)
            {
                var zeroOne = db.CreateCommand("Select * from [dbo].[ZeroOne] where Id=@id")
                  .AddParameter("@id", result.ZeroOneId)
                  .ReadOneMapTo<ZeroOne>();

                result.ZeroOne = zeroOne;
            }

            // one one
            var oneOne = db.CreateCommand("Select * from [dbo].[OneOne] where Id=@id")
                .AddParameter("@id", result.OneOneId)
                .ReadOneMapTo<OneOne>();

            result.OneOne = oneOne;

            Assert.AreEqual(result.Name.TrimEnd(), "Base 1");
            Assert.IsFalse(result.ZeroOneId.HasValue);
            Assert.AreEqual(result.OneOneId,2);
            Assert.AreEqual(result.OneOne.Id, 2);
            Assert.AreEqual(result.OneOne.Name, "One 1");
        }
		public static async Task Send(Db db)
		{
			var host = HttpContext.Current?.Request.ServerVariables["HTTP_HOST"];
            if (host == null || !host.Equals("jeegoordah.azurewebsites.net", StringComparison.InvariantCultureIgnoreCase))
			{
				throw new Exception($"Sending notifications is disabled for {host}");
			}

			var sendTasks = db.Query<Bro>()
				.Where(x => x.Email != null)
				.Where(x => x.Notifications.Count > 0)
				.ToArray()
				.Select(async bro =>
				{
					var message = new SendGridMessage
					{
						From = _from,
						To = new[] {new MailAddress(bro.Email)},
						Subject = "Jeegoordah notifications",
						Text = GetContent(bro.Notifications),
						Html = null,
					};

					_logger.I($"Sending {bro.Notifications.Count} notifications for {bro.Name}");
					await _transport.DeliverAsync(message);
					_logger.I($"Notifications for {bro.Name} sent");
				});

			await Task.WhenAll(sendTasks);

			db.Query<Notification>().ForEach(db.Session.Delete);
			_logger.I("Notifications deleted");
		}
    public void ShouldBeThreadLocalStandardValuesProvider()
    {
      var templateId = ID.NewID;
      var itemId = ID.NewID;
      var fieldId = ID.NewID;

      var t1 = Task.Factory.StartNew(() =>
      {
        using (var db = new Db
                          {
                            new DbTemplate(templateId) { { fieldId, "$name" } },
                            new DbItem("Home", itemId, templateId)
                          })
        {
          Thread.Sleep(1000);
          db.GetItem(itemId)[fieldId].Should().Be("Home");
        }
      });

      var t2 = Task.Factory.StartNew(() =>
      {
        using (var db = new Db
                          {
                            new DbTemplate(templateId) { fieldId },
                            new DbItem("Home", itemId, templateId)
                          })
        {
          db.GetItem(itemId)[fieldId].Should().BeEmpty();
        }
      });

      t1.Wait();
      t2.Wait();
    }
    public void ShouldPropagateFieldsFromAllBaseTemplates()
    {
      // arrange
      ID myTemplateId = ID.NewID;

      using (var db = new Db
      {
        this.baseTemplateOne,
        this.baseTemplateTwo,
        this.baseTemplateThree,
        new DbTemplate("Main Template", myTemplateId) {BaseIDs = new[] {this.baseTemplateOne.ID, this.baseTemplateThree.ID}},
        new DbItem("home", ID.NewID, myTemplateId)
      })
      {
        // act
        Item home = db.GetItem("/sitecore/content/home");
        Template template = TemplateManager.GetTemplate(myTemplateId, db.Database);

        // assert

        // note: as noted above, fields propagation should "just" work
        home.Fields["Title"].Should().NotBeNull("home.Fields[\"Title\"]");
        home.Fields["Description"].Should().NotBeNull("home.Fields[\"Description\"]");

        template.GetField("Title").Should().NotBeNull("template.GetField(\"Title\")");
        template.GetField("Description").Should().NotBeNull("template.GetField(\"Description\")");
      }
    }
Example #6
0
        /// <summary>
        /// Get html
        /// </summary
        private static string getHtml(string url, string customUserAgent, Db.HttpHeadersInfoCollection httpHeaders)
        {
            try
            {

                //set new proxy if use proxy
                CookieAwareWebClient client = Factory.Instance.getWebClientNext(customUserAgent,httpHeaders);
                client = setCredential(client, url);

                //Set Wait time
                System.Threading.Thread.Sleep(Factory.Instance.i.Project.ScrapingSetting.waitEachRequestMilliseconds);


                Stream s = client.OpenRead(url); ;
                StreamReader sr = new StreamReader(s);
                string html = sr.ReadToEnd();
                s.Close();
                return html;
            }
            catch (Exception ex)
            {
                //Wait after error - prevent next request
                System.Threading.Thread.Sleep(Factory.Instance.i.Project.ScrapingSetting.waitAfterError);
                Factory.Instance.log.Error(ex);
                return string.Empty;
            }
        }
Example #7
0
        /// <summary>
        /// Get html Async
        /// </summary>
        private string getHtmlAsync(string url, string customUserAgent, Db.HttpHeadersInfoCollection httpHeaders)
        {
            try
            {

                //set new proxy if use proxy
                CookieAwareWebClient client = Factory.Instance.getWebClientNext(customUserAgent,httpHeaders);
                client = setCredential(client, url);              

                //Set Wait time
                System.Threading.Thread.Sleep(Factory.Instance.i.Project.ScrapingSetting.waitEachRequestMilliseconds);

                //Stream s = 
                asyncEnd = false;
                client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);               
                client.OpenReadAsync(new Uri(url));
                while (asyncEnd == false)
                    System.Threading.Thread.Sleep(10);
              
                return this.currentHtml;

            }
            catch (Exception ex)
            {
                //Wait after error - prevent next request
                System.Threading.Thread.Sleep(Factory.Instance.i.Project.ScrapingSetting.waitAfterError);
                Factory.Instance.log.Error(ex);
                return string.Empty;
            }
        }
Example #8
0
        public FieldBase(Db.Field Field)
        {
            this.TenantID = Configure.GetTenantResolutionProvider().GetTenantID();

            if (this.TenantID != Field.TenantID)
            {
                Log.Fatal("TenantID Does not match. FieldID: {0}, Global TenantID: {1}, Field TenantID: {2}",
                    Field.FieldID, this.TenantID, Field.TenantID);
                throw new FatalException("Data error.");
            }

            this.Dirty = false;
            this.FieldID = Field.FieldID;

            this.ValueString = Field.ValueText;
            this.ValueDate = Field.ValueDate;
            this.ValueDecimal = Field.ValueDecimal;
            this.ValueBool = Field.ValueBoolean;
            this.ValueLookup = Field.ValueLookup;
            this.ValueBinary = Field.ValueBinary;
            this.ValueEntityReference = Field.ValueEntityReference;
            this.ValueItemReference = Field.ValueItemReference;
            this.Guid = Field.Guid;

            RefreshOriginalValues();
        }
Example #9
0
        public HistoryPresenter(Db db)
        {
            this.db = db;

            nullAccount = new Account();
            nullAccount.Name = "";
        }
    public void ShouldPropagateFieldsFromTheBaseTemplate()
    {
      // arrange
      ID templateId = ID.NewID;

      using (var db = new Db
      {
        this.baseTemplateOne,
        new DbTemplate("My Template", templateId) {BaseIDs = new[] {this.baseTemplateOne.ID}},
        new DbItem("home", ID.NewID, templateId)
      })
      {
        // act
        Item home = db.GetItem("/sitecore/content/home");
        Template template = TemplateManager.GetTemplate(templateId, db.Database);
        Template baseTemplate = TemplateManager.GetTemplate(this.baseTemplateOne.ID, db.Database);

        TemplateField titleField = baseTemplate.GetField("Title");

        // assert 

        // note: it should "just" work as Sitecore wil do all the looking up the templates chain
        template.GetFields(false).Should().NotContain(f => f.Name == "Title" || f.ID == titleField.ID);
        template.GetFields(true).Should().Contain(f => f.Name == "Title" && f.ID == titleField.ID);

        template.GetField("Title").Should().NotBeNull("template.GetField(\"Title\")");
        template.GetField(titleField.ID).Should().NotBeNull("template.GetField(titleField.ID)");

        home.Fields["Title"].Should().NotBeNull("home.Fields[\"Title\"]");
        home.Fields[titleField.ID].Should().NotBeNull("home.Fields[titleField.ID]");
      }
    }
		public CameraFileSelectionDialog (GPhotoCamera cam, Db datab)
		{
			camera = cam;
			db = datab;
			saved_files = null;
			selected_tags = null;
		}
Example #12
0
 public static void Merge(string path, Db to_db)
 {
     Log.Warning ("Will merge db {0} into main f-spot db {1}", path, FSpot.Global.BaseDirectory + "/photos.db" );
     Db from_db = new Db ();
     from_db.Init (path, true);
     //MergeDb mdb = new MergeDb (from_db, to_db);
 }
        public async Task<int> Save(long routeId, Station station, int number)
        {
            if(routeId <= 0) throw new ArgumentException("routeId <= 0");
            if(station == null) throw new ArgumentNullException("station");

            using (var db = new Db())
            {
                using (var transaction = db.Database.BeginTransaction(IsolationLevel.RepeatableRead))
                {
                    try
                    {
                        var route = db.Routes.SingleOrDefault(s => s.Id == routeId);
                        if(route == null) throw new NullReferenceException("route");

                        station = await _stationRepository.GetByLatLng(station.Latitude, station.Longitude);
                        if(station == null) throw new NullReferenceException("station");

                        var routeStation = new RouteStation(){Number = number,RouteId = routeId,StationId = station.Id};
                        db.Entry(routeStation).State = EntityState.Added;
                        return await db.SaveChangesAsync();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Log.Error(ex.Message);
                        throw;
                    }
                }
            }

        }
Example #14
0
        public void Run()
        {
            _Console.WriteLine("End statement with ';'");
            _Console.WriteLine("Enter 'quit' when done");
            _Console.WriteLine();

            string line;
            string statement = "";
            _Console.Write(">");
            while((line = _Console.ReadLine()) != "quit") {
                statement += line + '\n';
                if(!line.Trim().EndsWith(";"))
                    continue;

                using(var db = new Db()) {
                    try {
                        db.ExecuteReader(statement, PrintHeader,PrintGrid);
                    } catch(Exception e) {
                        _Console.WriteLine(e.Message);
                    }
                }
                statement = "";
                _Console.Write(">");
            }
        }
Example #15
0
		public HttpDataHandler(HttpRequest request, Db db)
		{
			string cmd = request.Form["ex"];
			Form = request.Form;
			Database = db;
			Nodes = new Node();
			if (!string.IsNullOrEmpty(cmd))
			{
				if (cmd.Equals("insert"))
				{
					ParseInsertQuery();
				}
				else if (cmd.Equals("update"))
				{
					ParseUpdateQuery();
				}
				else if (cmd.Equals("delete"))
				{
					ParseDeleteQuery();
				}
				else if (cmd.Equals("select"))
				{
					ParseSelectQuery();
				}
			}
		}
Example #16
0
        // Constructor.
        public TagSelectionWidget(TagStore tag_store)
            : base(new TreeStore (typeof(uint), typeof(string)))
        {
            database = MainWindow.Toplevel.Database;

            HeadersVisible = false;

            complete_column = new TreeViewColumn ();

            pix_render = new CellRendererPixbuf ();
            complete_column.PackStart (pix_render, false);
            complete_column.SetCellDataFunc (pix_render, new TreeCellDataFunc (IconDataFunc));
            //complete_column.AddAttribute (pix_render, "pixbuf", OpenIconColumn);

            //icon_column = AppendColumn ("icon",
            //, new TreeCellDataFunc (IconDataFunc));
            //icon_column = AppendColumn ("icon", new CellRendererPixbuf (), new TreeCellDataFunc (IconDataFunc));

            text_render = new CellRendererText ();
            complete_column.PackStart (text_render, true);
            complete_column.SetCellDataFunc (text_render, new TreeCellDataFunc (NameDataFunc));

            AppendColumn (complete_column);

            this.tag_store = tag_store;

            Update ();

            ExpandDefaults ();

            tag_store.ItemsAdded += HandleTagsAdded;
            tag_store.ItemsRemoved += HandleTagsRemoved;
            tag_store.ItemsChanged += HandleTagsChanged;

            // TODO make the search find tags that are not currently expanded
            EnableSearch = true;
            SearchColumn = NameColumn;

            // Transparent white
            empty_pixbuf.Fill(0xffffff00);

            /* set up drag and drop */
            DragDataGet += HandleDragDataGet;
            DragDrop += HandleDragDrop;
            DragBegin += HandleDragBegin;

            Gtk.Drag.SourceSet (this,
                       Gdk.ModifierType.Button1Mask | Gdk.ModifierType.Button3Mask,
                       tag_source_target_table,
                       DragAction.Copy | DragAction.Move);

            DragDataReceived += HandleDragDataReceived;
            DragMotion += HandleDragMotion;

            Gtk.Drag.DestSet (this,
                              DestDefaults.All,
                              tag_dest_target_table,
                              DragAction.Copy | DragAction.Move);
        }
Example #17
0
    public void GetMapPoints_ItemIdPassed_PointsReturnedFormRepo(IMapPointRepository mapPointRepository, Db db, MapPoint[] points,[FakeDb.AutoFixture.Content]Data.Items.Item item)
    {
      mapPointRepository.GetAll(null).ReturnsForAnyArgs(points);

      var controller = new MapsController(mapPointRepository);
      var actualPoints = controller.GetMapPoints(item.ID.Guid).Data as IEnumerable<MapPoint>;
      actualPoints.ShouldBeEquivalentTo(points);
    }
Example #18
0
 public FieldString(FieldType Type, FieldBase Base, EntityBase Entity, Db.IDbContext ctx = null)
     : base(Type, Base, Entity, ctx)
 {
     if (Type.DataType != DataType.Text)
     {
         throw new ArgumentOutOfRangeException("Cannot create a string field from a non-string type.");
     }
 }
Example #19
0
 public FieldLookup(FieldType Type, FieldBase Base, EntityBase Entity, Db.IDbContext ctx = null)
     : base(Type, Base, Entity, ctx)
 {
     if (Type.DataType != DataType.Lookup)
     {
         throw new ArgumentOutOfRangeException("Cannot create a lookup field from a non-lookup type.");
     }
 }
Example #20
0
		/// <summary>
		/// Default constructor.
		/// </summary>
		public SecurityManager(Db db = null) {
			if (db == null)
				db = new Db();
			this.db = db;

			UserManager = new UserManager<Entities.User>(new UserStore<Entities.User>(this.db));
			RoleStore = new RoleStore<IdentityRole>(this.db);
		}
Example #21
0
        public FolderTreeModel()
            : base(typeof (string), typeof (int), typeof (Uri))
        {
            database = MainWindow.Toplevel.Database;
            database.Photos.ItemsChanged += HandlePhotoItemsChanged;

            UpdateFolderTree ();
        }
 public FieldDecimal(FieldType Type, FieldBase Base, EntityBase Entity, Db.IDbContext ctx = null)
     : base(Type, Base, Entity, ctx)
 {
     if (Type.DataType != DataType.Decimal)
     {
         throw new ArgumentOutOfRangeException("Cannot create a decimal field from a non-decimal type.");
     }
 }
 public FieldEntityReference(FieldType Type, FieldBase Base, EntityBase Entity, Db.IDbContext ctx = null)
     : base(Type, Base, Entity, ctx)
 {
     if (Type.DataType != DataType.EntityReference)
     {
         throw new ArgumentOutOfRangeException("Cannot create an entity reference field from a non-entity-reference type.");
     }
 }
 public User GetUserByLogon(LogonModel model)
 {
     using (var db = new Db())
     {
         return db.Users.FirstOrDefault(u => u.UserName == model.UserName && u.Password == model.UserPass);
     }
     return null;
 }
 public FieldLazyBinary(FieldType Type, FieldBase Base, EntityBase Entity, Db.IDbContext ctx = null)
     : base(Type, Base, Entity, ctx)
 {
     if (Type.DataType != DataType.Binary)
     {
         throw new ArgumentOutOfRangeException("Cannot create a binary field from a non-binary type.");
     }
 }
Example #26
0
        /// <summary>
        /// Csv Writer
        /// </summary>
        public System.IO.StreamWriter openCsvFileWriter(Db.intelliScraperProjectStoreInfo s)
        {

            bool append = true;
            if (s.CsvExcelSetting.csvFileClear)
                append = false;
            this.csvWriter = new System.IO.StreamWriter(s.CsvExcelSetting.csvFileSaveTo, append);
            return this.csvWriter;
        }
Example #27
0
 public void ShouldCreateItemHierarchyAndReadChildByPath()
 {
   // arrange & act
   using (var db = new Db { new DbItem("parent") { new DbItem("child") } })
   {
     // assert
     db.GetItem("/sitecore/content/parent/child").Should().NotBeNull();
   }
 }
Example #28
0
 public void ShouldCreateItemInSpecificLanguage()
 {
   // arrange & act
   using (var db = new Db { new DbItem("home") { new DbField("Title") { { "en", "Hello!" }, { "da", "Hej!" } } } })
   {
     db.Database.GetItem("/sitecore/content/home", Language.Parse("en"))["Title"].Should().Be("Hello!");
     db.Database.GetItem("/sitecore/content/home", Language.Parse("da"))["Title"].Should().Be("Hej!");
   }
 }
		public static void Load (Db db)
		{
			tag_remote = new TagProxy (db.Tags);
			Bus.Session.Register (SERVICE_PATH, new ObjectPath (TAG_PROXY_PATH), tag_remote);
			tag_remote.OnRemoteUp ();

			photo_remote = new PhotoProxy (db);
			Bus.Session.Register (SERVICE_PATH, new ObjectPath (PHOTO_PROXY_PATH), photo_remote);
			photo_remote.OnRemoteUp ();
		}
Example #30
0
        public void SetUp()
        {
            Gtk.Application.Init ();
            try {
                File.Delete (path);
            } catch {}

            db = new Db ();
            db.Init (path, true);
        }
Example #31
0
File: Ac.cs Project: 15831944/Geo7
 public static AcTransaction StartTransaction(bool lockDocument = false)
 {
     return(Db.StartAcTransaction(lockDocument));
 }