protected void Page_Load(object sender, EventArgs e) { var presentationUrl = SiteContext.CurrentSite.SitePresentationURL; if (String.IsNullOrEmpty(presentationUrl)) { ShowError(ResHelper.GetString("bizform.formBuilderMVC.presentationURLMissing")); return; } var uri = new Uri(presentationUrl); var targetOrigin = uri.GetLeftPart(UriPartial.Authority); var path = string.Format(FORMBUILDER_ROUTE_TEMPLATE, EditedForm.FormID); ScriptHelper.RegisterModule(this, "CMS.Builder/FormBuilder/Messaging", new { frameId = formBuilderFrame.ClientID, origin = targetOrigin }); // Modify frame 'src' attribute and add administration domain into it ScriptHelper.RegisterModule(this, "CMS.Builder/FrameSrcAttributeModifier", new { frameId = formBuilderFrame.ClientID, frameSrc = URLHelper.AddParameterToUrl(presentationUrl.TrimEnd('/') + VirtualContext.GetFormBuilderPath(path, CurrentUser.UserName), BUILDER_MODE_QUERY_STRING_NAME, FORM_BUILDER_MODE), }); }
private void HandleBeginRequest(object sender, EventArgs e) { var application = (HttpApplication)sender; var context = application.Context; var relativeFilePath = context.Request.AppRelativeCurrentExecutionFilePath.TrimStart('~'); // Check whether the current request URL contains information about a preview mode if (HandleVirtualContext(ref relativeFilePath)) { // Validate integrity of preview information (including the unique identifier generated by Kentico) in the current request URL if (!VirtualContext.ValidatePreviewHash(relativeFilePath) || !ValidatePreviewGuid(VirtualContext.GetItem(VirtualContext.PARAM_WF_GUID))) { VirtualContext.Reset(); throw new HttpException(404, "The preview link is not valid."); } // Disable same origin policy for a preview mode as Kentico displays preview in a frame AntiForgeryConfig.SuppressXFrameOptionsHeader = true; // Do not cache response in a preview mode, it has to contain current data context.Response.Cache.SetNoServerCaching(); context.Response.Cache.SetNoStore(); // Remove preview mode information from the request URL context.RewritePath("~" + relativeFilePath, context.Request.PathInfo, context.Request.Url.Query.TrimStart('?')); } var previewFeature = new PreviewFeature(); context.Kentico().SetFeature <IPreviewFeature>(previewFeature); }
protected void Page_Load(object sender, EventArgs e) { formId = QueryHelper.GetInteger("formid", 0); recordId = QueryHelper.GetInteger("formRecordId", 0); var presentationUrl = new PresentationUrlRetriever().RetrieveForAdministration(SiteContext.CurrentSiteName); if (String.IsNullOrEmpty(presentationUrl)) { ShowError(ResHelper.GetString("bizform.formBuilderMVC.presentationURLMissing")); return; } var path = String.Format(FORM_ITEM_EDIT_ROUTE_TEMPLATE, formId); if (recordId > 0) { path += $"/{recordId}"; } // Modify frame 'src' attribute and add administration domain into it ScriptHelper.RegisterModule(this, "CMS.Builder/FrameSrcAttributeModifier", new { frameId = formBuilderFrame.ClientID, frameSrc = presentationUrl.TrimEnd('/') + VirtualContext.GetFormBuilderPath(path, MembershipContext.AuthenticatedUser.UserGUID), mixedContentMessage = GetString("builder.ui.mixedcontenterrormessage"), applicationPath = SystemContext.ApplicationPath }); RegisterCookiePolicyDetection(); }
protected void Page_Init(object sender, EventArgs e) { // Check permissions if (!QueryHelper.ValidateHash("hash")) { return; } int bizId = QueryHelper.GetInteger("bizid", 0); int recId = QueryHelper.GetInteger("recid", 0); if ((bizId > 0) && (recId > 0)) { var bfi = BizFormInfo.Provider.Get(bizId); if (bfi == null) { return; } var path = string.Format(FORM_ITEM_PREVIEW_ROUTE_TEMPLATE, bfi.FormID, recId); var site = bfi.Site as SiteInfo; var url = new PresentationUrlRetriever().RetrieveForAdministration(site.SiteName); // Modify frame 'src' attribute and add administration domain into it ScriptHelper.RegisterModule(this, "CMS.Builder/FrameSrcAttributeModifier", new { frameId = mvcFrame.ClientID, frameSrc = url.TrimEnd('/') + VirtualContext.GetFormBuilderPath(path, MembershipContext.AuthenticatedUser.UserGUID), mixedContentMessage = GetString("builder.ui.mixedcontenterrormessage"), applicationPath = SystemContext.ApplicationPath }); RegisterCookiePolicyDetection(); } }
protected void Page_Load(object sender, EventArgs e) { formId = QueryHelper.GetInteger("formid", 0); recordId = QueryHelper.GetInteger("formRecordId", 0); var presentationUrl = SiteContext.CurrentSite.SitePresentationURL; if (String.IsNullOrEmpty(presentationUrl)) { ShowError(ResHelper.GetString("bizform.formBuilderMVC.presentationURLMissing")); return; } var path = String.Format(FORM_ITEM_EDIT_ROUTE_TEMPLATE, formId); if (recordId > 0) { path += $"/{recordId}"; } // Modify frame 'src' attribute and add administration domain into it ScriptHelper.RegisterModule(this, "CMS.Builder/FrameSrcAttributeModifier", new { frameId = formBuilderFrame.ClientID, frameSrc = presentationUrl.TrimEnd('/') + VirtualContext.GetFormBuilderPath(path, CurrentUser.UserName), }); }
public void SetUp() { pagesRetrieverMock = Substitute.For <IPagesRetriever>(); richTextGetLinkMetadataActionExecutor = new RichTextGetLinkMetadataActionExecutor(pagesRetrieverMock, "/"); VirtualContext.SetItem(VirtualContext.PARAM_PREVIEW_LINK, "pv"); MembershipContext.AuthenticatedUser = Substitute.For <CurrentUserInfo>(); }
private T GetVirtualContextItem <T>(string key) { object value = VirtualContext.GetItem(key); if (value != null) { return((T)value); } return(default(T)); }
/// <summary> /// Handles the virtual context for the request. /// </summary> /// <param name="relativePath">Relative path. If loading succeeded, returns updated virtual path without the context values.</param> /// <returns>True, if loading of the virtual context succeeded and the request is a virtual context request, otherwise false.</returns> /// <exception cref="HttpException">When virtual context is invalid.</exception> private static bool HandleVirtualContext(ref string relativePath) { try { return(VirtualContext.HandleVirtualContext(ref relativePath)); } catch (InvalidVirtualContextException ex) { VirtualContext.Reset(); throw new HttpException(404, "The preview link is not valid.", ex); } }
public void GetObjects_VirtualContextNotInitialized_ThrowsExceptionWithForbiddenStatus() { VirtualContext.SetItem(VirtualContext.PARAM_PREVIEW_LINK, null); var siteService = Substitute.For <ISiteService>(); var objectsRetriever = Substitute.For <ObjectsRetriever>(siteService); var controllerInstance = new KenticoObjectSelectorController(objectsRetriever); var exception = Assert.Throws <HttpResponseException>(() => controllerInstance.GetObjects("", 0)); Assert.That(exception.Response.StatusCode, Is.EqualTo(HttpStatusCode.Forbidden)); }
private static string GetAttachmentPreviewUrl(string url) { if (VirtualContext.IsPreviewLinkInitialized) { // Add hash of attachment URL for validation url = VirtualContext.AddPreviewHash(url); // Add prefix of virtual context url = url.Insert(1, VirtualContext.CurrentURLPrefix); } return(url); }
public void ProcessAction_PreviewLinkNotInitialized_ReturnsStatusCodeForbidden() { VirtualContext.SetItem(VirtualContext.PARAM_PREVIEW_LINK, null); var result = richTextGetLinkMetadataActionExecutor.ProcessAction("/page"); Assert.Multiple(() => { Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.Forbidden)); Assert.That(result.StatusCodeMessage, Is.Not.Empty); Assert.That(result.StatusCodeMessage, Is.Not.Null); }); }
private string RemoveVirtualContextData(string path) { // Remove the virtual context prefix if (VirtualContext.ContainsVirtualContextPrefix(path)) { // Remove the path hash path = URLHelper.RemoveParameterFromUrl(path, "uh"); Regex virtualContextPathPrefixRegex = RegexHelper.GetRegex($"{VirtualContext.VirtualContextPrefix}.*/{VirtualContext.VirtualContextSeparator}"); // Remove the virtual context prefix "/cmsctx/.../-" return(virtualContextPathPrefixRegex.Replace(path, String.Empty)); } return(path); }
protected void Page_Load(object sender, EventArgs e) { string url = QueryHelper.GetString("splitUrl", null); if (!string.IsNullOrEmpty(url) && CMSContext.DisplaySplitMode) { // Register script files ltlScript.Text += ScriptHelper.GetIncludeScript("~/CMSModules/Content/CMSDesk/SplitView.js"); // Decode url url = HttpUtility.UrlDecode(url); // Update view mode UpdateViewMode(CMSContext.ViewMode); // Set frame1 url docSplitView.Frame1Url = url; // Get the URL of the other frame NameValueCollection param = new NameValueCollection(); param.Add("culture", CMSContext.SplitModeCultureCode); // Set frame2 url docSplitView.Frame2Url = VirtualContext.GetVirtualContextPath(url, param); // Set script prefix param.Set("culture", "##c##"); string scriptPrefix = VirtualContext.GetVirtualContextPrefix(param); StringBuilder script = new StringBuilder(); script.Append( @"function InitSplitViewSyncScroll(frameElement, body, refreshSameCulture, unbind) { if (InitSyncScroll) { InitSyncScroll(frameElement, body, refreshSameCulture, unbind); } } function SplitModeRefreshFrame() { if (FSP_SplitModeRefreshFrame) { FSP_SplitModeRefreshFrame(); } } var FSP_appPref = '", URLHelper.GetFullApplicationUrl(), @"'; var FSP_cntPref = '", scriptPrefix, "';"); ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "splitViewSync_" + Page.ClientID, ScriptHelper.GetScript(script.ToString())); } }
protected void Page_Init(object sender, EventArgs e) { // Check permissions if (!QueryHelper.ValidateHash("hash")) { return; } int bizId = QueryHelper.GetInteger("bizid", 0); int recId = QueryHelper.GetInteger("recid", 0); if ((bizId > 0) && (recId > 0)) { var bfi = BizFormInfoProvider.GetBizFormInfo(bizId); if (bfi == null) { return; } if (bfi.FormDevelopmentModel == (int)FormDevelopmentModelEnum.Mvc) { var path = string.Format(FORM_ITEM_PREVIEW_ROUTE_TEMPLATE, bfi.FormID, recId); string url = (bfi.Site as SiteInfo).SitePresentationURL; mvcFrame.Visible = true; // Modify frame 'src' attribute and add administration domain into it ScriptHelper.RegisterModule(this, "CMS.Builder/FrameSrcAttributeModifier", new { frameId = mvcFrame.ClientID, frameSrc = url.TrimEnd('/') + VirtualContext.GetFormBuilderPath(path, CurrentUser.UserName), mixedContentMessage = GetString("builder.ui.mixedcontenterrormessage"), applicationPath = SystemContext.ApplicationPath }); } else { bizRecord.ItemID = recId; bizRecord.SiteName = SiteInfoProvider.GetSiteName(bfi.FormSiteID); bizRecord.FormName = bfi.FormName; bizRecord.Visible = true; } } }
private List <HeaderAction> GetSitesAvailableForVirtualAccess() { List <HeaderAction> actions = new List <HeaderAction>(); CacheHelper.Cache(() => { var sitesData = SiteInfoProvider.GetSites() .Columns("SiteName", "SiteDisplayName") .OrderBy("SiteDisplayName") .TypedResult; foreach (SiteInfo s in sitesData) { // Prepare the parameters NameValueCollection values = new NameValueCollection(); values.Add(VirtualContext.PARAM_SITENAME, s.SiteName); HeaderAction site = new HeaderAction { Text = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(s.DisplayName)), ButtonStyle = ButtonStyle.Default, RedirectUrl = VirtualContext.GetVirtualContextPath(Request.Path, values), Target = "_blank" }; actions.Add(site); } return(actions); }, new CacheSettings(60, "DevMenu", "Sites", "VirtualContext") { GetCacheDependency = () => CacheHelper.GetCacheDependency(new[] { SiteInfo.OBJECT_TYPE + "|all", }) }); return(actions); }
private static void FakeVirtualContext() { VirtualContext.SetItem(VirtualContext.PARAM_PREVIEW_LINK, "testPreviewLink"); ValidationHelper.HashStringSalt = "78a60095-2b09-40c2-9a9d-e2cc0b511aca"; VirtualContext.CurrentURLPrefix = "/testPrefix"; }
public void SetUp() { VirtualContext.SetItem(VirtualContext.PARAM_PREVIEW_LINK, "pv"); }
protected void Page_Load(object sender, EventArgs e) { if (SystemContext.DevelopmentMode) { // Restart application menu.AddAction(new HeaderAction { Text = GetString("administration-system.btnrestart"), ButtonStyle = ButtonStyle.Default, Tooltip = GetString("administration-system.btnrestart"), OnClientClick = "function RestartPerformed() {return alert('" + GetString("administration-system.restartsuccess") + "');} if (confirm('" + GetString("system.restartconfirmation") + "')) {" + Page.ClientScript.GetCallbackEventReference(this, "'restart'", "RestartPerformed", String.Empty, true) + "}" }); // Clear cache menu.AddAction(new HeaderAction { Text = GetString("administration-system.btnclearcache"), ButtonStyle = ButtonStyle.Default, Tooltip = GetString("administration-system.btnclearcache"), OnClientClick = "function ClearCachePerformed() {return alert('" + GetString("administration-system.clearcachesuccess") + "');} if (confirm('" + GetString("system.clearcacheconfirmation") + "')) {" + Page.ClientScript.GetCallbackEventReference(this, "'clearcache'", "ClearCachePerformed", String.Empty, true) + "}" }); // Event log HeaderAction eventLog = new HeaderAction { Text = GetString("administration.ui.eventlog"), ButtonStyle = ButtonStyle.Default, Tooltip = GetString("administration.ui.eventlog"), RedirectUrl = "~/CMSModules/EventLog/EventLog.aspx", Target = "_blank" }; // Event log items DataSet ds = EventLogProvider.GetEvents() .OrderByDescending("EventTime") .TopN(10) .Columns("EventTime", "EventType", "Source", "EventCode"); foreach (DataRow row in ds.Tables[0].Rows) { HeaderAction ev = new HeaderAction { Text = string.Format("{0} {1} {2} {3}", row["EventTime"], row["EventType"], row["Source"], row["EventCode"]), ButtonStyle = ButtonStyle.Default }; eventLog.AlternativeActions.Add(ev); } menu.AddAction(eventLog); // Debug menu.AddAction(new HeaderAction { Text = GetString("Administration-System.Debug"), ButtonStyle = ButtonStyle.Default, Tooltip = GetString("Administration-System.Debug"), RedirectUrl = URLHelper.AppendQuery(UIContextHelper.GetElementUrl(ModuleName.CMS, "Debug"), "displaytitle=true"), Target = "_blank" }); // Submit defect menu.AddAction(new HeaderAction { Text = "Submit defect", ButtonStyle = ButtonStyle.Default, Tooltip = "Submit defect", RedirectUrl = "https://kentico.atlassian.net/secure/CreateIssue!default.jspa", Target = "_blank" }); // Virtual site HeaderAction sites = new HeaderAction { Text = GetString("devmenu.sites"), ButtonStyle = ButtonStyle.Default, Tooltip = GetString("devmenu.sites"), Inactive = true }; // Site items var sitesDs = SiteInfoProvider.GetSites().Columns("SiteName", "SiteDisplayName").OrderBy("SiteDisplayName"); foreach (SiteInfo s in sitesDs) { // Prepare the parameters NameValueCollection values = new NameValueCollection(); values.Add(VirtualContext.PARAM_SITENAME, s.SiteName); HeaderAction site = new HeaderAction { Text = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(s.DisplayName)), ButtonStyle = ButtonStyle.Default, RedirectUrl = VirtualContext.GetVirtualContextPath(Request.Path, values), Target = "_blank" }; sites.AlternativeActions.Add(site); } menu.AddAction(sites); } else { Visible = false; } }
public void TearDown() { VirtualContext.SetItem(VirtualContext.PARAM_PREVIEW_LINK, null); MembershipContext.AuthenticatedUser = null; }
protected void Page_Load(object sender, EventArgs e) { var presentationUrl = new PresentationUrlRetriever().RetrieveForAdministration(SiteContext.CurrentSiteName); if (String.IsNullOrEmpty(presentationUrl)) { ShowError(ResHelper.GetString("bizform.formBuilderMVC.presentationURLMissing")); return; } var uri = new Uri(presentationUrl); var targetOrigin = uri.GetLeftPart(UriPartial.Authority); var path = string.Format(FORMBUILDER_ROUTE_TEMPLATE, EditedForm.FormID); ScriptHelper.RegisterModule(this, "CMS.Builder/FormBuilder/Messaging", new { frameId = formBuilderFrame.ClientID, origin = targetOrigin }); // Modify frame 'src' attribute and add administration domain into it ScriptHelper.RegisterModule(this, "CMS.Builder/FrameSrcAttributeModifier", new { frameId = formBuilderFrame.ClientID, frameSrc = URLHelper.AddParameterToUrl(presentationUrl.TrimEnd('/') + VirtualContext.GetFormBuilderPath(path, MembershipContext.AuthenticatedUser.UserGUID), BUILDER_MODE_QUERY_STRING_NAME, FORM_BUILDER_MODE), mixedContentMessage = GetString("builder.ui.mixedcontenterrormessage"), applicationPath = SystemContext.ApplicationPath }); RegisterCookiePolicyDetection(); }
static void Main(string[] args) { Console.WriteLine("BEGINNING TESTS. . . "); Console.WriteLine(); /*** Begin Tests ***/ VirtualContext<AdentureWorksLTDataContext> vc = new VirtualContext<AdentureWorksLTDataContext>(); //EntitySet<Customer> customers = vc.Get<Customer>().WithFullGraph().Load(); int count = 0; Console.WriteLine("Counting via DataContext directly."); using (AdentureWorksLTDataContext context = new AdentureWorksLTDataContext()) { context.Log = Console.Out; count = (from c in context.GetTable<Customer>() select c).Count(); Console.WriteLine("There are " + count + " Customers in the DB."); } Console.WriteLine(); Console.WriteLine("Counting via VirtualContext."); vc.Log = Console.Out; count = vc.Get<Customer>().Count(); Console.WriteLine("There are " + count + " Customers in the DB."); Console.WriteLine(); Console.WriteLine("Testing vc counting functionality vis a vis query batching."); var countQuery = vc.GetCount(typeof(Customer)); var customerQuery = vc.Get(typeof(Customer)); vc.LoadPending(); count = countQuery.GetCount(); EntitySet<Customer> customers = customerQuery.GetData() as EntitySet<Customer>; Console.WriteLine("There are " + count + " Customers in the DB."); Console.WriteLine("Customer EntitySet contains " + customers.Count() + " entities."); Console.WriteLine(); //Customer customer = vc.Get<Customer>().WithFullGraph().PK(29653); //Console.WriteLine("--------- EntityStates: ---------"); //foreach (EntityState state in vc.EntityStates) //{ // Console.WriteLine(state.Entity.GetType() + " has status " + state.Status); //} //Console.WriteLine(); //Console.WriteLine("Duplicating object graph."); //Customer dupCust = vc.ORMUtility.Duplicate(customer) as Customer; //Console.WriteLine("--------- EntityStates: ---------"); //foreach (EntityState state in vc.EntityStates) //{ // Console.WriteLine(state.Entity.GetType() + " has status " + state.Status); //} //Console.WriteLine(); //Console.WriteLine("Modifying a SaleOrderDetail of the duplicated graph."); //SalesOrderDetail detail = dupCust.SalesOrderHeaders.First().SalesOrderDetails.First(); //detail.UnitPrice += 0.01M; ////dupCust.SalesOrderHeaders.First().SalesOrderDetails.Remove(detail); ////SalesOrderDetail newDetail = vc.ORMUtility.ShallowCopy(detail) as SalesOrderDetail; ////newDetail.SalesOrderDetailID = 0; ////dupCust.SalesOrderHeaders.First().SalesOrderDetails.Add(newDetail); //Console.WriteLine("--------- EntityStates: ---------"); //foreach (EntityState state in vc.EntityStates) //{ // Console.WriteLine(state.Entity.GetType() + " has status " + state.Status); //} //Console.WriteLine(); //Console.WriteLine("Calling vc.ORMUtility.Modify(dupCust, customer)"); //vc.ORMUtility.Modify(dupCust, customer); //Console.WriteLine("--------- EntityStates: ---------"); //foreach (EntityState state in vc.EntityStates) //{ // Console.WriteLine(state.Entity.GetType() + " has status " + state.Status); //} //Console.WriteLine(); //if (object.ReferenceEquals(customer, dupCust)) //{ // Console.WriteLine("Root references are equal!!!"); //} //else //{ // Console.WriteLine("Root references are NOT equal."); //} //if (object.Equals(customer, dupCust)) //{ // Console.WriteLine("Root objects are equal by value."); //} //else //{ // Console.WriteLine("Root object NOT equal by value!!!"); //} //if (vc.ORMUtility.ShallowCompare(customer, dupCust)) //{ // Console.WriteLine("Root objects equal as per ShallowCompare()."); //} //else //{ // Console.WriteLine("Root object NOT equal as per ShallowCompare()!!!"); //} //if (vc.ORMUtility.DeepCompare(customer, dupCust)) //{ // Console.WriteLine("Root objects equal as per DeepCompare()."); //} //else //{ // Console.WriteLine("Root object NOT equal as per DeepCompare()!!!"); //} //SalesOrderDetail origDetail = customer.SalesOrderHeaders.First().SalesOrderDetails.First(); //SalesOrderDetail newDetail = vc.ORMUtility.ShallowCopy(origDetail) as SalesOrderDetail; //newDetail.SalesOrderDetailID = 0; //newDetail.ModifiedDate = DateTime.Now; //customer.SalesOrderHeaders.First().SalesOrderDetails.Add(newDetail); //vc.SubmitChanges(); //foreach (SalesOrderDetail detail in customer.SalesOrderHeaders.First().SalesOrderDetails) //{ // foreach (PropertyInfo property in vc.ORMUtility.GetDBColProperties(typeof(SalesOrderDetail))) // { // if (property.Name != "rowguid") // { // Console.Write(property.Name + " = " + property.GetValue(detail, null).ToString() + "|"); // } // } // Console.WriteLine(); //} //VirtualContext<AdentureWorksLTDataContext> vc = new VirtualContext<AdentureWorksLTDataContext>(); //Product newProduct = new Product() //{ // Name = "LL Touring Frame - Black, 62", // ProductNumber = "FR-T55B-62", // Color = "Black", // StandardCost = 265.20M, // ListPrice = 390.10M, // Size = "62", // Weight = 1451.49M, // SellStartDate = DateTime.Now, // SellEndDate = null, // DiscontinuedDate = null, // ModifiedDate = DateTime.Now //}; //ProductModel productModel = vc.Get<ProductModel>().Where(m => m.Name == "LL Touring Frame").Load().SingleOrDefault(); //ProductCategory productCategory = vc.Get<ProductCategory>().Where(c => c.Name == "Touring Bikes").Load().SingleOrDefault(); //newProduct.ProductModel = productModel; //newProduct.ProductCategory = productCategory; //vc.SubmitChanges(); //Console.WriteLine("---------- DependentTree ---------"); //foreach (object entity in vc.ORMUtility.ToDependentTree(customer)) //{ // Console.WriteLine(entity.GetType().Name + " has status " + vc.GetEntityStatus(entity)); //} //Console.WriteLine(); //Console.WriteLine("---------- FlatGraph ---------"); //foreach (object entity in vc.ORMUtility.ToFlatGraph(customer)) //{ // Console.WriteLine(entity.GetType().Name + " has status " + vc.GetEntityStatus(entity)); //} //Console.WriteLine(); //Product firstProduct = customer.SalesOrderHeaders.First().SalesOrderDetails.First().Product; //Console.WriteLine("firstProduct ID=" + firstProduct.ProductID + ": " + firstProduct.Name); //Console.WriteLine(); //Console.WriteLine("Attempting to modify product name."); //firstProduct.Name += "something"; //Console.WriteLine("Before serialization, ID=" + customer.CustomerID + ": " + customer.CompanyName + " has " + customer.SalesOrderHeaders.First().SalesOrderDetails.Count() + " details."); //string serializedEntity = ormUtility.SerializeEntity(customer); //Customer deserializedCustomer = ormUtility.DeserializeEntity(typeof(Customer), serializedEntity) as Customer; //Console.WriteLine("After serialization, ID=" + customer.CustomerID + ": " + customer.CompanyName + " has " + deserializedCustomer.SalesOrderHeaders.First().SalesOrderDetails.Count() + " details."); //List<EntityState> EntityStates = vc.EntityStates.ToList(); //EntityState state = EntityStates.First(); //Console.WriteLine("The first EntityState before serialization: " + state.Entity.GetType().Name + " marked for " + state.Status); //Console.WriteLine("vc.IsTracking(" + state.Entity.GetType() + ") = " + vc.IsTracking(state.Entity)); //string serializedEntityState = ormUtility.SerializeEntity(state); //EntityState deserializedState = ormUtility.DeserializeEntity(typeof(EntityState), serializedEntityState) as EntityState; //Console.WriteLine("The first EntityState after deserialization: " + state.Entity.GetType().Name + " marked for " + state.Status); //Console.WriteLine("(after deserialization) vc.IsTracking(" + deserializedState.Entity.GetType() + ") = " + vc.IsTracking(deserializedState.Entity)); //string allEntityStatesSerialized = ormUtility.SerializeEntity(EntityStates); //List<EntityState> deserializedEntityStates = ormUtility.DeserializeEntity(EntityStates.GetType(), allEntityStatesSerialized) as List<EntityState>; //Customer dsCust = deserializedEntityStates.First().Entity as Customer; //SalesOrderHeader dsHeader = null; //foreach (EntityState entityState in deserializedEntityStates) //{ // dsHeader = entityState.Entity as SalesOrderHeader; // if (dsHeader != null) // { // break; // } //} //if (object.ReferenceEquals(dsCust, dsHeader.Customer)) //{ // Console.WriteLine("References preserved!"); //} //else //{ // Console.WriteLine("Duplicate entities created."); //} //int pageNum = 1; ////var products = vc.Get<Product>().OrderByDescending(p => p.Name).PageSize(10).PageNum(pageNum++).Load(); //var products = vc.Get<Product>().OrderBy(p => p.Name).Load(); ////while (products.Count() > 0) ////{ // foreach (Product prod in products) // { // foreach (PropertyInfo property in ormUtility.GetDBColProperties(typeof(Product))) // { // if (property.Name != "ThumbNailPhoto" && // property.Name != "rowguid") // { // object val = property.GetValue(prod, null); // Console.Write(property.Name + " = "); // if (val != null) // { // Console.Write(val.ToString() + "|"); // } // else // { // Console.Write("NULL|"); // } // } // } // Console.WriteLine(); // //Console.WriteLine(prod.Name); // } // Console.WriteLine(); // products = vc.Get<Product>().OrderByDescending(p => p.Name).PageSize(10).PageNum(pageNum++).Load(); //} //EntitySet<Customer> customersWithSales = vc.Get<Customer>().WithFullGraph().Detach().Where(c => c.SalesOrderHeaders.Count() > 0).OrderByDescending(c => c.SalesOrderHeaders.Single().SalesOrderID).Load(); //Console.WriteLine("First 10 Customers with at least one sale:"); //int i = 0; //foreach (Customer cust in customersWithSales) //{ // int detailsCnt = (from d in ormUtility.ToEntityTree(cust) // where d.GetType() == typeof(SalesOrderDetail) // select d).Count(); // Console.WriteLine("ID=" + cust.CustomerID + ": " + cust.CompanyName + " has " + cust.SalesOrderHeaders.Count() + " headers and " + detailsCnt + " details."); // //foreach (SalesOrderHeader head in cust.SalesOrderHeaders) // //{ // // foreach (SalesOrderDetail det in head.SalesOrderDetails) // // { // // Console.WriteLine("ID=" + det.SalesOrderDetailID); // // } // //} // //Console.WriteLine(); // if (i++ >= 10) break; //} //Console.WriteLine("Constructing EntityQueries."); ////var custQuery = vc.Get<Customer>().WithDependents().Where(c => c.SalesOrderHeaders.Count() > 0); //var custQuery = vc.Get<Customer>() // .LoadWith<Customer>(c => c.SalesOrderHeaders.First().SalesOrderDetails) // .LoadWith<SalesOrderHeader>(s => s.SalesOrderDetails) // .Where(c => c.CustomerID == 29653); ////var custQuery = vc.Get(typeof(Customer)).WithDependents(); //var prodQuery = vc.Get<Product>().WithFKs(); //var addrQuery = vc.Get<CustomerAddress>(); //Console.WriteLine("Retrieving both queries via one DataConnection."); //vc.LoadPending(); //Console.WriteLine("Obtaining data from EntityQueries."); ////EntitySet<Customer> customers = custQuery.GetData() as EntitySet<Customer>; //Customer customer = custQuery.GetData().SingleOrDefault(); //EntitySet<Product> products = prodQuery.GetData(); //EntitySet<CustomerAddress> addresses = addrQuery.GetData(); //Console.WriteLine("Obtain customer ID=" + customer.CustomerID + ": " + customer.CompanyName + " with " + customer.SalesOrderHeaders.Count() + " sales headers."); //Console.WriteLine("Obtained " + products.Count() + " products and " + addresses.Count() + " CustomerAddresses."); ////Customer thrilling = (from c in customersWithSales //// where c.CustomerID == 29653 //// select c).SingleOrDefault(); //Customer thrilling = vc.Get<Customer>().WithFullGraph().PK(29653); ////Console.WriteLine("Before edit, CompanyName = " + thrilling.CompanyName + "."); //Console.WriteLine("EntityStates:"); //foreach (EntityState entityState in vc.EntityStates) //{ // Console.WriteLine(entityState.Entity.GetType().Name + " " + entityState.Status + (entityState.IsRoot ? " is Root." : ".")); //} ////thrilling.CompanyName = "The Thrilling Bike Store"; ////Console.WriteLine("After edit, CompanyName = " + thrilling.CompanyName + "."); ////Console.WriteLine("EntityStates:"); ////foreach (EntityState entityState in vc.EntityStates) ////{ //// Console.WriteLine(entityState.Entity.GetType().Name + " " + entityState.Status); ////} ////Console.WriteLine("VirtualContext submitting changes. . ."); ////vc.SubmitChanges(); ////Console.WriteLine("Querying customer back. . ."); ////Customer editedThrilling = vc.Get<Customer>().PK(29653); ////Console.WriteLine("Back from data source, CompanyName = " + editedThrilling.CompanyName + "."); ////foreach (SalesOrderDetail detail in thrilling.SalesOrderHeaders.Single().SalesOrderDetails.Where(d => d.ProductID == 789).ToList()) ////{ //// thrilling.SalesOrderHeaders.Single().SalesOrderDetails.Remove(detail); ////} //foreach (SalesOrderDetail detail in thrilling.SalesOrderHeaders.Single().SalesOrderDetails) //{ // foreach (PropertyInfo column in ormUtility.GetDBColProperties(typeof(SalesOrderDetail))) // { // Console.Write(column.Name + " = " + column.GetValue(detail, null) + "|"); // } // Console.WriteLine(); //} //Product product = vc.Get(typeof(Product)).WithFKs().PK(789) as Product; //Console.WriteLine("ProductID=" + product.ProductID + " has ModelID=" + product.ProductModelID + ": " + product.ProductModel.Name); //for (int j = 0; j < 5; j++) //{ // SalesOrderDetail sale = new SalesOrderDetail(); // sale.ModifiedDate = DateTime.Now; // sale.Product = product; // sale.OrderQty = 1; // sale.UnitPrice = 1.0M; // sale.UnitPriceDiscount = 1.0M; // thrilling.SalesOrderHeaders.First().SalesOrderDetails.Add(sale); //} //Console.WriteLine("EntityStates:"); //foreach (EntityState entityState in vc.EntityStates) //{ // Console.WriteLine(entityState.Entity.GetType().Name + " " + entityState.Status + (entityState.IsRoot ? " is Root." : ".")); //} //Console.WriteLine(); //Console.WriteLine("Submitting changes. . ."); //vc.SubmitChanges(); //Console.WriteLine(); //Console.WriteLine("EntityStates:"); //foreach (EntityState entityState in vc.EntityStates) //{ // Console.WriteLine(entityState.Entity.GetType().Name + " " + entityState.Status + (entityState.IsRoot ? " is Root." : ".")); //} //Console.WriteLine("Reading all customers, full graph, with > 0 orders via VirtualContext with tracking on."); //EntitySet<Customer> customers = vc.Get<Customer>().WithFullGraph().Where(c => c.SalesOrderHeaders.Count() > 0).Load(); //Console.WriteLine("Currently tracking: " + vc.EntityStates.Count() + "."); //Console.WriteLine("Reading all customers, full graph, with > 0 orders via VirtualContext WITHOUT tracking."); //customers = vc.Get<Customer>().WithFullGraph().Where(c => c.SalesOrderHeaders.Count() > 0).Detach().Load(); //Console.WriteLine("Currently tracking: " + vc.EntityStates.Count() + "."); //Console.WriteLine(customers.Count() + " Customers with at least one order."); //Console.WriteLine("The first 10 are:"); //int i = 0; //foreach (Customer cust in customers) //{ // Console.WriteLine("ID=" + cust.CustomerID + ": " + cust.CompanyName + "."); // if (++i >= 10) break; //} //Customer customer1 = customers.First(); //Console.WriteLine("Generating EntityTree on first Customer: " + customer1.CompanyName + "."); //EntityTree<AdentureWorksLTDataContext> entityTree = new EntityTree<AdentureWorksLTDataContext>(customer1); ////foreach (object item in entityTree) ////{ //// Console.WriteLine(item.GetType()); ////} //List<Type> entityTypes = new List<Type>(); //foreach (object item in entityTree) //{ // if (!entityTypes.Contains(item.GetType())) // { // entityTypes.Add(item.GetType()); // } //} //foreach (Type type in entityTypes) //{ // int count = (from e in entityTree // where e.GetType() == type // select e).Count(); // Console.WriteLine("There are " + count + " " + type + "."); //} //Console.WriteLine(); //Console.WriteLine("A list of Entity Types:"); //foreach (Type type in ormUtility.GetAllEntityTypes()) //{ // Console.WriteLine(type); //} //EntityTracker<AdentureWorksLTDataContext> tracker = new EntityTracker<AdentureWorksLTDataContext>(); //tracker.Track(customer1); //tracker.SetOriginal(customer1); //CustomerAddress customerAddress = customer1.CustomerAddresses.First(); //Console.WriteLine("CustomerAddress.AddressID=" + customerAddress.AddressID + "."); //Address address = customerAddress.Address; //if (address != null) //{ // Console.WriteLine("Address ID=" + address.AddressID + ": " + address.AddressLine1 + "."); //} //else //{ // Console.WriteLine("CustomerAddress.Address == null."); //} //tracker.SetInsert(customer1); //Console.WriteLine("Modifying Customer object."); //customer1.FirstName = "Bobby"; //customer1.SalesOrderHeaders.Clear(); //SalesOrderHeader header = customer1.SalesOrderHeaders.First(); //header.SalesOrderDetails.Clear(); //header.Customer = null; //SalesOrderHeader header1 = new SalesOrderHeader(); //customer1.SalesOrderHeaders.Add(header1); //WriteEntityTree(tracker); //SalesOrderHeader header2 = new SalesOrderHeader(); //customer1.SalesOrderHeaders.Add(header2); //SalesOrderDetail detail1 = new SalesOrderDetail(); //SalesOrderDetail detail2 = new SalesOrderDetail(); //header2.SalesOrderDetails.Add(detail1); //header2.SalesOrderDetails.Add(detail2); //Address address1 = vc.Get<Address>().Load().First(); //tracker.Track(address1); //tracker.SetOriginal(address1); //header2.Address = address1; //using (AdentureWorksLTDataContext context = new AdentureWorksLTDataContext()) //{ // using (TransactionScope scope = new TransactionScope()) // { // context.DeferredLoadingEnabled = false; // DataContextSyncTool<AdentureWorksLTDataContext> syncTool = // new DataContextSyncTool<AdentureWorksLTDataContext>(context, tracker); // WriteEntityTree(tracker); // Console.WriteLine("Syncing to DataContext. . ."); // syncTool.Sync(); // Console.WriteLine("Submitting changes to DB. . ."); // context.SubmitChanges(); // Console.WriteLine("Resetting Tracker. . ."); // tracker.ResetTracking(); // WriteEntityTree(tracker); // Console.WriteLine("Rolling back transaction. . ."); // } //} //WriteEntityTree(tracker); /*** End Tests ***/ Console.WriteLine(); Console.WriteLine("Press Enter to Exit."); Console.ReadLine(); }