public Poll GetPoll(string serviceID, string clientID) { Poll poll; BowmarPollsDataContext context = new BowmarPollsDataContext(); var dataOptions = new System.Data.Linq.DataLoadOptions(); dataOptions.LoadWith<Poll>(Poll => Poll.PollElements); context.LoadOptions = dataOptions; Guid current_poll = this.getPollforService(context, serviceID); if (current_poll == null) return null; var result = from a in context.Polls where a.id == current_poll select a; poll = result.First(); // check to see if client has participated, if so return results, if not don't bool participated = this.hasClientParticipated(context, current_poll, clientID); poll.isResult = participated; //if (!participated) //{ // poll.isResult = false; // this.setClientAsParticipated(context, current_poll, clientID); //} return poll; }
public FiltreretOejebliksbilledeType ReadPeriod(DateTime fromDate, DateTime toDate, PersonIdentifier pId, Func <string, Guid> cpr2UuidFunc) { using (var dataContext = new ExtractDataContext()) { var loadOptions = new System.Data.Linq.DataLoadOptions(); loadOptions.LoadWith <ExtractItem>(ei => ei.Extract); dataContext.LoadOptions = loadOptions; var individualResponses = Extract.GetPersonFromAllExtracts(pId.CprNumber, dataContext.ExtractItems, Constants.DataObjectMap); var fullResp = new IndividualHistoryResponseType(pId, individualResponses); var pnrs = fullResp.AllRelationPNRs; var uuids = CprBroker.Data.Part.PersonMapping.AssignGuids(pnrs); Func <string, Guid> uuidGetter = (pnr) => { Guid?uuid = null; var pnrIndex = Array.IndexOf <string>(pnrs, pnr); if (pnrIndex != -1) { uuid = uuids[pnrIndex]; } return(uuid.HasValue ? uuid.Value : cpr2UuidFunc(pnr)); }; return(fullResp .ToFiltreretOejebliksbilledeType(uuidGetter) .Filter(VirkningType.Create(fromDate, toDate))); } }
/// <summary> /// Sets the load options to load the child entities with a root Subscription object /// </summary> /// <param name="loadOptions"></param> public static void SetLoadOptionsForChildren(System.Data.Linq.DataLoadOptions loadOptions) { loadOptions.LoadWith <Subscription>((Subscription sub) => sub.DataSubscription); loadOptions.LoadWith <Subscription>((Subscription sub) => sub.BirthdateSubscription); loadOptions.LoadWith <Subscription>((Subscription sub) => sub.Channels); loadOptions.LoadWith <Subscription>((Subscription sub) => sub.SubscriptionPersons); }
string exportDupl(bool withDump) { if (!readLangs()) return null; TradosDataContext db = Machines.getTradosContext(false); System.Data.Linq.DataLoadOptions opt = new System.Data.Linq.DataLoadOptions(); opt.LoadWith<Sentence>(s => s.Page); db.LoadOptions = opt; XElement res = new XElement("lookup"); StringBuilder sb = new StringBuilder(); //Duplicity, grupovane dle Srctext var q1 = db.Lookups. Where(lkp => lkp.SrcLang == (short)SrcLang && lkp.TransLang == (short)TransLang). Select(lkp => new { lkp.SrcText, lkp.TransText, lkp.Hash, lkp.Id, /*debug*/ lkp.SrcHash }). ToArray(); //nejak nefunguje grupovani var query = q1.GroupBy(st => st.SrcText).Where(g => g.Count() >= 2).ToArray(); //Vety s duplicitami if (withDump) { int[] hashes = query.SelectMany(g => g).Select(l => l.Hash).ToArray(); Sentence[] duplSent = db.Sentences.Where(s => s.SrcLang == (short)SrcLang && s.TransLang == (short)TransLang && hashes.Contains(s.Hash)).ToArray(); foreach (var grp in query) { res.Add(new XElement("item", new XElement(SrcLang.ToString(), grp.Key.IndexOf('<') >= 0 ? (object)new XCData(grp.Key) : (object)grp.Key), grp.Select(s => new XElement(TransLang.ToString() + "_dupl", new XElement("text", s.TransText.IndexOf('<') >= 0 ? (object)new XCData(s.TransText) : (object)s.TransText), duplSent.Where(d => d.SrcText == grp.Key && d.TransText == s.TransText). Select(d => new XElement("page", d.Page.FileName + "(" + d.Id.ToString() + ")")) )))); } res.Save(@"c:\temp\lookup_export.xml"); } return "Počet duplicit = " + query.Length.ToString(); }
/// <summary> /// Deletes the given subscription from the database /// </summary> /// <param name="subscriptionId"></param> /// <param name="subscriptionType"></param> /// <returns></returns> private bool DeleteSubscription(Guid subscriptionId, CprBroker.EventBroker.Data.SubscriptionType.SubscriptionTypes subscriptionType) { // Find the Subscription object and delete it and its children using (EventBrokerDataContext dataContext = new EventBrokerDataContext()) { System.Data.Linq.DataLoadOptions loadOptions = new System.Data.Linq.DataLoadOptions(); Subscription.SetLoadOptionsForChildren(loadOptions); dataContext.LoadOptions = loadOptions; var subscription = (from sub in dataContext.Subscriptions where sub.SubscriptionId == subscriptionId && !sub.Deactivated.HasValue && sub.SubscriptionTypeId == (int)subscriptionType select sub ).SingleOrDefault(); if (subscription != null) { subscription.Deactivated = DateTime.Now; dataContext.SubmitChanges(); return(true); } else { return(false); } } }
public IEnumerable <Product> GetProductsByCategory(int?categoryId) { using (var dc = new EcommerceDataContext(_connectionString)) { var loadOptions = new System.Data.Linq.DataLoadOptions(); loadOptions.LoadWith <Product>(p => p.Images); dc.LoadOptions = loadOptions; return(dc.Products.Where(p => p.Categoryid == categoryId).ToList()); } }
public IQueryable<FuelRecord> AllIncluding(params Expression<Func<FuelRecord, object>>[] includeProperties) { var dataOptions = new System.Data.Linq.DataLoadOptions(); foreach (var expression in includeProperties) { dataOptions.LoadWith<FuelRecord>(expression); } _context.LoadOptions = dataOptions; IQueryable<FuelRecord> query = _context.FuelRecords; return query; }
void doSearch() { //se sentenci laduj i page TradosDataContext db = Machines.getTradosContext(false); db.CommandTimeout = 30; System.Data.Linq.DataLoadOptions opt = new System.Data.Linq.DataLoadOptions(); opt.LoadWith<Sentence>(s => s.Page); db.LoadOptions = opt; StringBuilder sb = new StringBuilder(); //zakladni podminka na vsechny sentence v grupe: vyber sentenci a aktualni trans text if (!string.IsNullOrEmpty(SearchSentId.Text)) { PagesRep.DataSource = db.Sentences.Where(s => s.Id == int.Parse(SearchSentId.Text)).Select(s => new { url = "EditPage.aspx?sentIds=" + s.Id, title = s.Page.FileName }); } else { Langs srcLang = LowUtils.EnumParse<Langs>(ConfigurationManager.AppSettings["Trados.srcLang." + partnerCode]); Langs transLang = LowUtils.EnumParse<Langs>(ConfigurationManager.AppSettings["Trados.transLang." + partnerCode]); //Test na jednoznacnost jmena: var q3 = db.Sentences.Where(s => s.SrcLang == (short)srcLang && s.TransLang == (short)transLang). Where(s => db.Sentences.Where(s2 => s2.PageId == s.PageId && s2.TransLang == s.SrcLang && s2.Name == s.Name).Count() > 1). Select(s => s.Name).ToArray(); if (q3.Length > 0) { ErrorLab.Text = "**** Error duplicitni jmena zdroju k prekladu: " + q3.Aggregate((r, i) => r + "; " + i); return; } var q2 = db.Sentences.Where(s => s.SrcLang == (short)srcLang && s.TransLang == (short)transLang). Select(s => new { id = s.Id, oldSrcText = s.SrcText, transText = s.TransText, pageId = s.PageId, fileName = s.Page.FileName, newSrcText = db.Sentences.Where(s2 => s2.PageId == s.PageId && s2.TransLang == s.SrcLang && s2.Name == s.Name).Select(s2 => s2.TransText).Single() //newSrcText = db.Sentences.Where(s2 => s2.PageId == s.PageId && s2.TransLang == s.SrcLang && s2.Name == s.Name).ToArray() }); //src text filter if (!string.IsNullOrEmpty(SearchSrcEd.Text)) q2 = q2.Where(s => s.oldSrcText.Contains(SearchSrcEd.Text) || s.newSrcText.Contains(SearchSrcEd.Text)); //trans text filter if (!string.IsNullOrEmpty(SearchTransEd.Text)) q2 = q2.Where(s => s.transText.Contains(SearchTransEd.Text)); //do pameti var query = q2.ToArray(); //filter na status bool doAll = false; if (!doAll) query = query.Where(s => notOkCmds.Contains(TradosLib.excelFlag(TradosLib.xmlToExcel(s.oldSrcText, sb), TradosLib.xmlToExcel(s.newSrcText, sb)))).ToArray(); //dokonceni var group = query.GroupBy(s => s.fileName).OrderBy(g => g.Key); PagesRep.DataSource = group.Select(p => new { url = "PartnerEdit.aspx?sentIds=" + p.Select(i => i.id.ToString()).Aggregate((act, res) => res + "," + act), title = p.Key }); } PagesRep.DataBind(); }
public void SetCitizenLoadOptions() { var loadOptions = new System.Data.Linq.DataLoadOptions(); loadOptions.LoadWith <Citizen>(cit => cit.ChildrenAsFather); loadOptions.LoadWith <Citizen>(cit => cit.ChildrenAsMother); loadOptions.LoadWith <Citizen>(cit => cit.BirthRegistrationAuthority); loadOptions.LoadWith <Citizen>(cit => cit.CitizenReadyAddress); loadOptions.LoadWith <Citizen>(cit => cit.CitizenReadyAddress.Roads); this.LoadOptions = loadOptions; }
public Product GetProduct(int id) { using (var dc = new EcommerceDataContext(_connectionString)) { var loadOptions = new System.Data.Linq.DataLoadOptions(); loadOptions.LoadWith <Product>(p => p.Images); loadOptions.LoadWith <Product>(p => p.Category); dc.LoadOptions = loadOptions; return(dc.Products.First(p => p.Id == id)); } }
/// <summary> /// 查询全部生产班组信息 /// </summary> /// <returns></returns> public List <ProduceTeam> QueryYieldGroups() { using (HumanResourceDataContext oContext = new HumanResourceDataContext(this.strConn)) { var options = new System.Data.Linq.DataLoadOptions(); options.LoadWith <ProduceTeam>(p => p.Department); options.LoadWith <ProduceTeam>(p => p.EquipmentInformation); oContext.LoadOptions = options; var result = from item in oContext.ProduceTeam select item; return(result.ToList()); } }
public LocalDataContext(bool readOnly) { lock (lockObject) { db = new OMLDataDataContext(); //db.DeferredLoadingEnabled = false; // if (readOnly) // db.ObjectTrackingEnabled = false; System.Data.Linq.DataLoadOptions loadOptions = new System.Data.Linq.DataLoadOptions(); loadOptions.LoadWith<Title>(i => i.Images); db.LoadOptions = loadOptions; //db.Log = OMLDBContextLogger.Logger(); db.Connection.ConnectionString = OMLEngine.DatabaseManagement.DatabaseInformation.OMLDatabaseConnectionString; } }
public LocalDataContext(bool readOnly) { lock (lockObject) { db = new OMLDataDataContext(); //db.DeferredLoadingEnabled = false; // if (readOnly) // db.ObjectTrackingEnabled = false; System.Data.Linq.DataLoadOptions loadOptions = new System.Data.Linq.DataLoadOptions(); loadOptions.LoadWith <Title>(i => i.Images); db.LoadOptions = loadOptions; //db.Log = OMLDBContextLogger.Logger(); db.Connection.ConnectionString = OMLEngine.DatabaseManagement.DatabaseInformation.OMLDatabaseConnectionString; } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/xml"; var pd = context.Request["d"]; var pv = context.Request["v"]; using (var db = new DataClasses1DataContext()) using(var xtw = new XmlTextWriter(context.Response.Output)) { var dlo = new System.Data.Linq.DataLoadOptions(); dlo.LoadWith<YasaiKensa>(x => x.Place); db.LoadOptions = dlo; db.ObjectTrackingEnabled = false; var dt = DateTime.Today.AddDays(-27.0); var q = from s in db.YasaiKensa where s.Place.緯度.HasValue && s.Place.経度.HasValue && s.公表日D.HasValue && (pd == "ALL" || s.公表日D.Value > dt) group s by new { s.産地都道府県, s.産地市町村, s.Place} into g select new { pref = g.Key.産地都道府県, city = g.Key.産地市町村, lat = g.Key.Place.緯度, lng = g.Key.Place.経度, Cs = g.Max(x => x.セシウム134D.GetValueOrDefault() + x.セシウム137D.GetValueOrDefault() + x.セシウムD.GetValueOrDefault()), I = g.Max(x => x.ヨウ素131D.GetValueOrDefault()), count = g.Count() }; xtw.WriteStartDocument(); xtw.WriteStartElement("markers"); foreach (var item in q) { xtw.WriteStartElement("marker"); xtw.WriteAttributeString("pref", item.pref); xtw.WriteAttributeString("city", item.city); xtw.WriteAttributeString("lat", Convert.ToString(item.lat)); xtw.WriteAttributeString("lng", Convert.ToString(item.lng)); xtw.WriteAttributeString("bq", Convert.ToString(pv == "I" ? item.I : item.Cs)); xtw.WriteEndElement(); } xtw.WriteEndElement(); xtw.WriteEndDocument(); } }
public static void RebuildIndex(int timeoutSeconds) { DateTime start = DateTime.Now; List <Route> routesToIndex = null; List <Route> allIndexedRoutes = null; using (DataContext context = new DataContext()) { var dlo = new System.Data.Linq.DataLoadOptions(); dlo.LoadWith <Route>(x => x.RoutePieces); dlo.LoadWith <Route>(x => x.Type); context.LoadOptions = dlo; routesToIndex = context.Routes.Where(x => x.Status == (int)StatusEnum.Active).ToList(); allIndexedRoutes = context.Routes.Where(x => x.Status == (int)StatusEnum.ActiveAndIndexed).ToList(); } foreach (var route in routesToIndex) { // add this route to index AddRouteToIndex(route, allIndexedRoutes); // add to indexed list route.Status = (int)StatusEnum.ActiveAndIndexed; allIndexedRoutes.Add(route); // save status to DB using (DataContext context = new DataContext()) { var dbRoute = context.Routes.First(x => x.ID == route.ID); dbRoute.Status = (int)StatusEnum.ActiveAndIndexed; context.SubmitChanges(); } Console.Write("."); if (DateTime.Now.Subtract(start).TotalSeconds > timeoutSeconds) { break; } } }
/// <summary> /// /// </summary> /// <param name="idInvoice"></param> /// <returns></returns> public bool Delete(string idInvoice) { using (InvoiceClassesDataContext dc = new InvoiceClassesDataContext()) { var dataOptions = new System.Data.Linq.DataLoadOptions(); dataOptions.LoadWith<Invoice>(ca => ca.InvoiceLines); dc.LoadOptions = dataOptions; var deleteOrderDetails = from details in dc.Invoices where details.idInvoice == Int32.Parse(idInvoice) select details; if (deleteOrderDetails.Count() > 0) { foreach (var invoice in deleteOrderDetails) { dc.Invoices.DeleteOnSubmit(invoice); foreach (var invoiceL in invoice.InvoiceLines) { dc.InvoiceLines.DeleteOnSubmit(invoiceL); } } try { dc.SubmitChanges(); return true; } catch (Exception ex) { return false; } } else { return false; } } }
/// <summary> /// Retrieves the subscriptions that match the supplied criteria /// </summary> /// <param name="subscriptionId"></param> /// <returns></returns> private CprBroker.Schemas.Part.SubscriptionType[] GetActiveSubscriptionsList(Nullable <Guid> subscriptionId) { List <CprBroker.Schemas.Part.SubscriptionType> listType = new List <CprBroker.Schemas.Part.SubscriptionType>(); using (EventBrokerDataContext context = new EventBrokerDataContext()) { System.Data.Linq.DataLoadOptions loadOptions = new System.Data.Linq.DataLoadOptions(); Subscription.SetLoadOptionsForChildren(loadOptions); context.LoadOptions = loadOptions; // Create basic LINQ expression System.Linq.Expressions.Expression <Func <IQueryable <Subscription> > > exp = () => from sub in context.Subscriptions where sub.ApplicationId == CprBroker.Engine.BrokerContext.Current.ApplicationId select sub; // Add filter for subscription id (if required) IQueryable <Subscription> subscriptions; if (subscriptionId.HasValue) { subscriptions = exp.Compile()().Where((Subscription sub) => sub.SubscriptionId == subscriptionId); } else { subscriptions = exp.Compile()(); } // Now create list of OIO subscriptions foreach (var sub in subscriptions) { CprBroker.Schemas.Part.SubscriptionType subscriptionType = sub.ToOioSubscription(CprBroker.Engine.BrokerContext.Current.ApplicationToken); listType.Add(subscriptionType); } return(listType.ToArray()); } }
static ServiceController() { StreetIndex = new DataContext().Streets.OrderBy(x => x.FullName).ToList(); POIIndex = new DataContext().POIs.ToList(); using (DataContext context = new DataContext()) { var dlo = new System.Data.Linq.DataLoadOptions(); dlo.LoadWith <RoutePiece>(x => x.Route); dlo.LoadWith <Route>(x => x.Type); context.LoadOptions = dlo; List <RoutePiece> pieces = new DataContext().RoutePieces.Where(x => x.Name != null && x.Route.Status == (int)StatusEnum.ActiveAndIndexed && (x.Route.TypeID == (int)TypeEnum.Metro || x.Route.TypeID == (int)TypeEnum.Metrobus || x.Route.TypeID == (int)TypeEnum.TrenLigero)).ToList(); foreach (var piece in pieces) { string name = (piece.Route.Type.Name + " " + piece.Name).ToUpper().Replace("Á", "A").Replace("É", "E").Replace("Í", "I").Replace("Ó", "O").Replace("Ú", "U"); if (!POIIndex.Exists(x => x.Name == name)) { POIIndex.Add(new POI { Name = name, Lat = piece.Lat, Lng = piece.Lng }); } } } POIIndex = POIIndex.OrderBy(x => x.Name).ToList(); }
public static void ConvertPersons(int batchSize) { Admin.LogFormattedSuccess("ExtractManager.ConvertPersons() started, batch size <{0}>", batchSize); List <Guid> succeeded = new List <Guid>(), failed = new List <Guid>(); using (var dataContext = new ExtractDataContext()) { var dataLoadOptions = new System.Data.Linq.DataLoadOptions(); dataLoadOptions.LoadWith <ExtractItem>(ei => ei.Extract); dataContext.LoadOptions = dataLoadOptions; var persons = ExtractPersonStaging.SelectTop(dataContext, batchSize); Admin.LogFormattedSuccess("ExtractManager.ConvertPersons() - <{0}> persons found", persons.Length); var conversionExtracts = ExtractConversion.CreateFromPersonStagings(persons); ExtractConversion.FillExtractItems(conversionExtracts, dataContext); // Preload UUIDs var pnrs = ExtractConversion.AllPNRs(conversionExtracts); var cache = new UuidCache(); cache.FillCache(pnrs); int personIndex = 0; foreach (var personGroup in conversionExtracts) { Admin.LogFormattedSuccess("ExtractManager.ConvertPersons() - converting persons from extract <{0}>", personGroup.Extract.ExtractId); foreach (var person in personGroup.Persons) { personIndex++; try { Admin.LogFormattedSuccess("ExtractManager.ConvertPersons() - processing PNR <{0}>, person <{1}> of <{2}>", person.ExtractPersonStaging.PNR, personIndex, persons.Length); var uuid = cache.GetUuid(person.ExtractPersonStaging.PNR); var response = Extract.ToIndividualResponseType(person.ExtractPersonStaging.Extract, person.ExtractItems.AsQueryable(), Constants.DataObjectMap); var oioPerson = response.ToRegistreringType1(cache.GetUuid); var personIdentifier = new Schemas.PersonIdentifier() { CprNumber = person.ExtractPersonStaging.PNR, UUID = uuid }; UpdateDatabase.UpdatePersonRegistration(personIdentifier, oioPerson); succeeded.Add(person.ExtractPersonStaging.ExtractPersonStagingId); Admin.LogFormattedSuccess("ExtractManager.ConvertPersons() - finished PNR <{0}>, person <{1}> of <{2}>", person.ExtractPersonStaging.PNR, personIndex, persons.Length); } catch (Exception ex) { failed.Add(person.ExtractPersonStaging.ExtractPersonStagingId); Admin.LogException(ex); } } } } // Delete the staging tables from a new data context to maximize performance using (var dataContext = new ExtractDataContext()) { var persons = dataContext.ExtractPersonStagings.Where(ep => succeeded.Contains(ep.ExtractPersonStagingId)); dataContext.ExtractPersonStagings.DeleteAllOnSubmit(persons); dataContext.SubmitChanges(); } Admin.LogFormattedSuccess("ExtractManager.ConvertPersons() ending, batch size: <{0}>, succeeded: <{1}>, failed: <{2}>", batchSize, succeeded.Count, failed.Count); }
string notUsed(bool withDump) { if (!readLangs()) return null; TradosDataContext db = Machines.getTradosContext(false); System.Data.Linq.DataLoadOptions opt = new System.Data.Linq.DataLoadOptions(); opt.LoadWith<Sentence>(s => s.Page); db.LoadOptions = opt; XElement res = new XElement("lookup"); StringBuilder sb = new StringBuilder(); //Vety k lookupu var query = db.Lookups. Where(lkp => lkp.SrcLang == (short)SrcLang && lkp.TransLang == (short)TransLang). Select(lkp => new { srcText = lkp.SrcText, transText = lkp.TransText, pages = db.Sentences. Where(s => s.SrcLang == (short)SrcLang && s.TransLang == (short)TransLang && s.Hash == lkp.Hash && s.SrcText == lkp.SrcText && s.TransText == lkp.TransText). Select(s => s.Page.FileName) //}).Where(ls => ls.pages.Count() != 1); //foreach (var ls in queryObj.ToArray().OrderBy(l => l.pages.Count())) { }).Where(ls => ls.pages.Count() == 0); var q = query.ToArray(); if (withDump) { foreach (var ls in q) { res.Add(new XElement("item", //new XAttribute("count", ls.pages.Count().ToString()), new XElement(SrcLang.ToString(), new XCData(ls.srcText)), new XElement(TransLang.ToString(), new XCData(ls.transText)), ls.pages.Select(p => new XElement("page", p)) )); } res.Save(@"c:\temp\lookup_export.xml"); } return "Počet nepoužívaných = " + q.Length.ToString(); }
public List <SearchResult> DoSearch(SearchParams searchParams) { List <SearchResult> results = new List <SearchResult>(); var startNode = new Node(searchParams.StartSearch.Lat, searchParams.StartSearch.Lng); var endNode = new Node(searchParams.EndSearch.Lat, searchParams.EndSearch.Lng); graph.CreateLinksForTemporaryNode(startNode, true, 100); graph.CreateLinksForTemporaryNode(endNode, false, 100); graph.CreateDirectLink(startNode, endNode, 15); aStar.StartNode = startNode; aStar.EndNode = endNode; bool foundResult = aStar.SearchPath(searchParams.NrOfResults); if (aStar.PathFound) { using (var context = new DataContext()) { var metroIds = context.Routes.Where(x => x.TypeID == (int)TypeEnum.Metro && x.Status != (int)StatusEnum.New).Select(x => x.ID).ToList(); var dlo = new System.Data.Linq.DataLoadOptions(); dlo.LoadWith <RoutePiece>(x => x.Route); dlo.LoadWith <Route>(x => x.Type); context.LoadOptions = dlo; Dictionary <int, RoutePiece> routePieceCache = new Dictionary <int, RoutePiece>(); Dictionary <int, Route> routeCache = new Dictionary <int, Route>(); for (int si = 0; si < aStar.NrOfFoundResults; si++) { SearchResult result = new SearchResult(); result.Start = searchParams.StartSearch; result.End = searchParams.EndSearch; result.Items = new List <SearchResultItem>(); DateTime currentTime = searchParams.StartTime ?? DateTime.Now; result.StartTravelTime = currentTime; var arcs = aStar.GetPathByArcs(si); double accumulatedTime = 0; double accumulatedDistance = 0; Node accumulatedStartNode = null; List <SearchPosition> accumulatedPath = new List <SearchPosition>(); for (int i = 0; i < arcs.Length; i++) { Arc arc = arcs[i]; if (arc.StartNode.RouteID != arc.EndNode.RouteID || arcs.Length == 1) { if (accumulatedTime > 0) { SearchResultItem item = new SearchResultItem(); Route route = GetRouteCached(arc.StartNode.RouteID, context); item.Route = ResultRoute.FromRoute(route); item.Type = ResultType.FromType(route.Type); item.Start = ResultRoutePiece.FromRoutePiece(GetRoutePieceCached(accumulatedStartNode.RoutePieceID, context)); item.StartName = GetPieceName(item.Start); item.End = ResultRoutePiece.FromRoutePiece(GetRoutePieceCached(arc.StartNode.RoutePieceID, context)); item.EndName = GetPieceName(item.End); item.Time = accumulatedTime; item.Distance = accumulatedDistance; item.InDirection = ((!item.Route.SplitRoutePieceID.HasValue && item.Start.ID < item.End.ID) || (item.Route.SplitRoutePieceID.HasValue && item.Start.ID < item.Route.SplitRoutePieceID.Value)) ? item.Route.ToName : item.Route.FromName; // if special price type and last of same type Route nextRoute = GetRouteCached(arc.EndNode.RouteID, context); if (route.Type.PriceTypeID != (int)PriceTypeEnum.FixedPriceAllLines || nextRoute == null || nextRoute.TypeID != route.TypeID) { item.Price = GetPrice(route, route.Type, item.Distance); } else { item.Price = 0; // price will be applied later } item.StartTravelTime = currentTime; currentTime = currentTime.AddMinutes(item.Time); item.EndTravelTime = currentTime; accumulatedPath.Add(new SearchPosition(arc.StartNode.X, arc.StartNode.Y, "")); item.Path = accumulatedPath; accumulatedTime = 0; accumulatedDistance = 0; accumulatedPath = new List <SearchPosition>(); result.Items.Add(item); } SearchResultItem item2 = new SearchResultItem(); item2.Type = ResultType.FromType(ViaDFGraph.WALKING_TYPE); item2.Start = ResultRoutePiece.FromRoutePiece(arc.StartNode.RoutePieceID > 0 ? GetRoutePieceCached(arc.StartNode.RoutePieceID, context) : new RoutePiece { Lat = result.Start.Lat, Lng = result.Start.Lng, Name = result.Start.Name }); item2.StartName = GetPieceName(item2.Start); item2.End = ResultRoutePiece.FromRoutePiece(arc.EndNode.RoutePieceID > 0 ? GetRoutePieceCached(arc.EndNode.RoutePieceID, context) : new RoutePiece { Lat = result.End.Lat, Lng = result.End.Lng, Name = result.End.Name }); item2.EndName = GetPieceName(item2.End); item2.Time = arc.Cost; item2.Distance = graph.GetArcDistanceInKm(arc); item2.StartTravelTime = currentTime; currentTime = currentTime.AddMinutes(item2.Time); item2.EndTravelTime = currentTime; item2.Path.Add(new SearchPosition(arc.StartNode.X, arc.StartNode.Y, "")); item2.Path.Add(new SearchPosition(arc.EndNode.X, arc.EndNode.Y, "")); result.Items.Add(item2); accumulatedStartNode = arc.EndNode; } else { accumulatedTime += arc.Cost; accumulatedDistance += graph.GetArcDistanceInKm(arc); accumulatedPath.Add(new SearchPosition(arc.StartNode.X, arc.StartNode.Y, "")); } } result.EndTravelTime = currentTime; result.TotalDistance = result.Items.Sum(x => x.Distance); result.TotalTime = result.Items.Sum(x => x.Time); result.TotalPrice = result.Items.Sum(x => x.Price); results.Add(result); } } } return(results.OrderBy(x => x.TotalTime).ToList()); }
/// <summary> /// /// </summary> /// <param name="invoiceNum"></param> /// <returns></returns> public List<Invoice> Search(string invoiceNum) { List<Invoice> lInvoices = new List<Invoice>(); using (InvoiceClassesDataContext dc = new InvoiceClassesDataContext()) { var dataOptions = new System.Data.Linq.DataLoadOptions(); dataOptions.LoadWith<Invoice>(ca => ca.InvoiceLines); dc.LoadOptions = dataOptions; var rows = from myRow in dc.Invoices where myRow.Number == Int32.Parse(invoiceNum) select myRow; lInvoices = rows.ToList(); } return lInvoices; }
/// <summary> /// /// </summary> /// <returns></returns> public List<Invoice> ShowAll() { List<Invoice> lInvoices = new List<Invoice>(); using (InvoiceClassesDataContext dc = new InvoiceClassesDataContext()) { var dataOptions = new System.Data.Linq.DataLoadOptions(); dataOptions.LoadWith<Invoice>(ca => ca.InvoiceLines); dc.LoadOptions = dataOptions; var rows = from myRow in dc.Invoices select myRow; lInvoices = rows.ToList(); } return lInvoices; }
public void LinqToSqlInsert03() { Northwind db = CreateDB(); var ds = new System.Data.Linq.DataLoadOptions(); ds.LoadWith<Employee>(p => p.EmployeeTerritories); ds.LoadWith<EmployeeTerritory>(p => p.Territory); db.LoadOptions = ds; var q = from e in db.Employees where e.FirstName == "Nancy" select e; if (db.Employees.Any(e => e.FirstName == "Kira" && e.LastName == "Smith")) Assert.Ignore(); var newEmployee = new Employee { FirstName = "Kira", LastName = "Smith" }; var newTerritory = new Territory { TerritoryID = "12345", TerritoryDescription = "Anytown", Region = db.Regions.First() }; var newEmployeeTerritory = new EmployeeTerritory { Employee = newEmployee, Territory = newTerritory }; db.Employees.InsertOnSubmit(newEmployee); db.Territories.InsertOnSubmit(newTerritory); db.EmployeeTerritories.InsertOnSubmit(newEmployeeTerritory); db.SubmitChanges(); }
static void RunL2SMergeTest() { using (var db = new L2S.AdventureWorksDataContext()) using (var con = db.Connection) { //db.ObjectTrackingEnabled = false; var lo = new System.Data.Linq.DataLoadOptions(); lo.LoadWith <L2S.SalesOrderHeader>(o => o.SalesOrderDetails); db.LoadOptions = lo; db.Connection.Open(); var customerId = (from o in db.SalesOrderHeaders where o.SalesOrderDetails.Count() > 2 select o).Take(1).First().CustomerID; var q = from o in db.SalesOrderHeaders where o.CustomerID == customerId select o; var orders = q.ToList(); foreach (var o in orders) { foreach (var od in o.SalesOrderDetails) { od.UnitPrice = od.UnitPrice * 1.04M; } } string sql = @" declare @output Sales_SalesOrderDetail_type MERGE Sales.SalesOrderDetail AS target USING ( SELECT SalesOrderID, SalesOrderDetailID, UnitPrice FROM @OrderDetails ) AS source (SalesOrderID, SalesOrderDetailID, UnitPrice) ON ( target.SalesOrderID = source.SalesOrderID and target.SalesOrderDetailID = source.SalesOrderDetailID ) WHEN MATCHED THEN UPDATE SET target.UnitPrice = source.UnitPrice, target.ModifiedDate = GETDATE() OUTPUT inserted.* into @output; select * from @output; "; var cmd = new SqlCommand(sql, (SqlConnection)db.Connection); var pOrderDetails = cmd.Parameters.Add(new SqlParameter("@OrderDetails", SqlDbType.Structured)); pOrderDetails.TypeName = "Sales_SalesOrderDetail_type"; var sql2 = @" if not exists (select * from sys.table_types where name = 'Sales_SalesOrderDetail_type') CREATE TYPE Sales_SalesOrderDetail_type as TABLE ( [SalesOrderID] [int] NOT NULL, [SalesOrderDetailID] [int] NOT NULL, [CarrierTrackingNumber] [nvarchar](25) NULL, [OrderQty] [smallint] NOT NULL, [ProductID] [int] NOT NULL, [SpecialOfferID] [int] NOT NULL, [UnitPrice] [money] NOT NULL, [UnitPriceDiscount] [money] NOT NULL, [LineTotal] MONEY, [rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL, [ModifiedDate] [datetime] NOT NULL ) "; db.ExecuteCommand(sql2); //project the results into an Anonymous type matching the TVP declaration var dtq = from od in orders.SelectMany(o => o.SalesOrderDetails).Take(1000) select new { SalesOrderID = od.SalesOrderID, SalesOrderDetailId = od.SalesOrderDetailID, CarrierTrackingNumber = od.CarrierTrackingNumber, OrderQty = od.OrderQty, ProductID = od.ProductID, SpecialOfferID = od.SpecialOfferID, UnitPrice = od.UnitPrice, UnitPriceDiscount = od.UnitPriceDiscount, LineTotal = od.LineTotal, rowguid = od.rowguid, ModifiedDate = od.ModifiedDate }; var i = 0; var f = new { a = i++, b = i++, c = i++ }; //flatten the all the OrderDetails into a single DataReader for sending to the server pOrderDetails.Value = dtq.AsDataReader(); IList <L2S.SalesOrderDetail> results; try { using (var dr = cmd.ExecuteReader()) { results = db.Translate <L2S.SalesOrderDetail>(dr).ToList(); } } catch (SqlException ex) { throw; } foreach (var r in results) { Console.WriteLine("{0} {1}", r.SalesOrderDetailID, r.UnitPrice); } if (dtq.Count() != results.Count()) { throw new InvalidOperationException("Wrong number of rows affected by MERGE"); } } }
void doSearch() { //se sentenci laduj i page TradosDataContext db = Machines.getTradosContext(false); System.Data.Linq.DataLoadOptions opt = new System.Data.Linq.DataLoadOptions(); opt.LoadWith<Sentence>(s => s.Page); db.LoadOptions = opt; StringBuilder sb = new StringBuilder(); //zakladni podminka na vsechny sentence v grupe: vyber sentenci a aktualni trans text if (!string.IsNullOrEmpty(SearchSentId.Text)) { PagesRep.DataSource = db.Sentences.Where(s => s.Id == int.Parse(SearchSentId.Text)).Select(s => new { url = "EditPage.aspx?sentIds=" + s.Id, title = s.Page.FileName }); } else { Langs srcLang, transLang; LocCfg.decodeLangs(ProjectsRad.SelectedValue, out srcLang, out transLang); //LocCfgTransDef log = LocCfg.Instance().TransDef[ProjectsRad.SelectedIndex]; IEnumerable<short> groups = Request["group"].Split(',').Select(s => Convert.ToInt16(Enum.Parse(typeof(LocPageGroup), s))); //Test na jednoznacnost jmena: var q3 = db.Sentences.Where(s => s.SrcLang == (short)srcLang && s.TransLang == (short)transLang && groups.Contains(s.Page.PageGroup)). Where(s => db.Sentences.Where(s2 => s2.PageId == s.PageId && s2.TransLang == s.SrcLang && s2.Name == s.Name).Count() > 1). Select(s => s.Name).ToArray(); //var q3 = db.Sentences.Where(s => s.SrcLang == (short)srcLang && s.TransLang == (short)transLang && groups.Contains(s.Page.PageGroup)). //Select(s => new {sent=s, other=db.Sentences.Where(s2 => s2.PageId == s.PageId && s2.TransLang == s.SrcLang && s2.Name == s.Name).ToArray}). //Where(s => s.other.Count() > 1). //ToArray(); if (q3.Length > 0) { ErrorLab.Text = "**** Error duplicitni jmena zdroju k prekladu: " + q3.Aggregate((r, i) => r + "; " + i); return; } var q2 = db.Sentences.Where(s => s.SrcLang == (short)srcLang && s.TransLang == (short)transLang && groups.Contains(s.Page.PageGroup)). Select(s => new { id = s.Id, oldSrcText = s.SrcText, transText = s.TransText, pageId = s.PageId, fileName = s.Page.FileName, name = s.Name, newSrcText = db.Sentences.Where(s2 => s2.PageId == s.PageId && s2.TransLang == s.SrcLang && s2.Name == s.Name).Select(s2 => s2.TransText).Single() //newSrcText = db.Sentences.Where(s2 => s2.PageId == s.PageId && s2.TransLang == s.SrcLang && s2.Name == s.Name).ToArray() }); //src text filter if (!string.IsNullOrEmpty(SearchSrcEd.Text)) q2 = q2.Where(s => s.oldSrcText.Contains(SearchSrcEd.Text) || s.newSrcText.Contains(SearchSrcEd.Text)); //trans text filter if (!string.IsNullOrEmpty(SearchTransEd.Text)) q2 = q2.Where(s => s.transText.Contains(SearchTransEd.Text)); //filename text filter if (!string.IsNullOrEmpty(SearchFileNameEd.Text)) q2 = q2.Where(s => s.fileName.Contains(SearchFileNameEd.Text)); //filename text filter if (!string.IsNullOrEmpty(SearchNameEd.Text)) q2 = q2.Where(s => s.name.Contains(SearchNameEd.Text)); //do pameti var query = q2.ToArray(); //filter na status LocCommand[] cmds = SentFilterChb.Items.Cast<ListItem>().Where(li => li.Selected).Select(li => (LocCommand)Enum.Parse(typeof(LocCommand), li.Value)).ToArray(); if (cmds.Length > 0) query = query.Where(s => cmds.Contains(TradosLib.excelFlag(TradosLib.xmlToExcel(s.oldSrcText, sb), TradosLib.xmlToExcel(s.newSrcText, sb)))).ToArray(); //dokonceni var group = query.GroupBy(s => s.fileName).OrderBy(g => g.Key); PagesRep.DataSource = group.Select(p => new { url = "EditPage.aspx?sentIds=" + p.Take(250).Select(i => i.id.ToString()).Aggregate((act, res) => res + "," + act), title = p.Key }); } PagesRep.DataBind(); }
public void LinqToSqlInsert02() { Northwind db = CreateDB(); var ds = new System.Data.Linq.DataLoadOptions(); ds.LoadWith<Category>(c => c.Products); db.LoadOptions = ds; var q = from c in db.Categories where c.CategoryName == "Widgets" select c; var newCategory = new Category { CategoryName = "Widgets", Description = "Widgets are the customer-facing analogues to sprockets and cogs." }; var newProduct = new Product { ProductName = "Blue Widget", UnitPrice = 34.56m, Category = newCategory }; db.Categories.InsertOnSubmit(newCategory); db.SubmitChanges(); var reloadedProduct = db.Products.First(p => p.ProductID == newProduct.ProductID); Assert.AreEqual(reloadedProduct.ProductName, newProduct.ProductName); Assert.AreEqual(reloadedProduct.UnitPrice, newProduct.UnitPrice); Assert.AreEqual(reloadedProduct.Category.CategoryID, newProduct.CategoryID); var reloadedCategory = reloadedProduct.Category; Assert.AreEqual(reloadedCategory.CategoryName, newCategory.CategoryName); Assert.AreEqual(reloadedCategory.Description, reloadedCategory.Description); }