Example #1
0
        void CallMultiple()
        {
            // <Snippet5>
            Northwnd db = new Northwnd(@"c:\northwnd.mdf");

            // Assign the results of the procedure with an argument
            // of (1) to local variable 'result'.
            IMultipleResults result = db.VariableResultShapes(1);

            // Iterate through the list and write results (the company names)
            // to the console.
            foreach (VariableResultShapesResult1 compName in
                     result.GetResult <VariableResultShapesResult1>())
            {
                Console.WriteLine(compName.CompanyName);
            }

            // Pause to view company names; press Enter to continue.
            Console.ReadLine();

            // Assign the results of the procedure with an argument
            // of (2) to local variable 'result'.
            IMultipleResults result2 = db.VariableResultShapes(2);

            // Iterate through the list and write results (the order IDs)
            // to the console.
            foreach (VariableResultShapesResult2 ord in
                     result2.GetResult <VariableResultShapesResult2>())
            {
                Console.WriteLine(ord.OrderID);
            }
            // </Snippet5>
        }
Example #2
0
        // Performance Indicator Report section
        public static IList <PIMetricInfo> GetPIReportValues(Guid?OrgLocationID, Guid GroupID, int FrequencyID, Guid?OrgLocationTypeID, DateTime BeginDate, DateTime EndDate)
        {
            LinqMicajahDataContext dc                     = new LinqMicajahDataContext();
            IMultipleResults       results                = dc.Sp_SelectPIReportValues(LinqMicajahDataContext.InstanceId, OrgLocationID, GroupID, FrequencyID, OrgLocationTypeID, BeginDate, EndDate);
            IList <PIMetricInfo>   MetricInfo             = results.GetResult <PIMetricInfo>().ToList();
            IList <PIMetricValue>  MetricValues           = results.GetResult <PIMetricValue>().ToList();
            List <Micajah.Common.Bll.MeasureUnit> OrgUoMs = Mc_UnitsOfMeasure.GetOrganizationUoMs();

            foreach (PIMetricInfo mi in MetricInfo)
            {
                mi.LocationFullName = (OrgLocationID == Guid.Empty && !String.IsNullOrEmpty(mi.LocationFullName)) ? LinqMicajahDataContext.OrganizationName : mi.LocationFullName;

                mi.InputUoMName = GetMeasureUnitPluralName(OrgUoMs, mi.InputUnitOfMeasureID);
                mi.UoMName      = GetMeasureUnitPluralName(OrgUoMs, mi.UnitOfMeasureID);
                CompositeDailyValues cdv = new CompositeDailyValues();
                foreach (PIMetricValue mv in MetricValues)
                {
                    decimal Val = 0;
                    if (mv.MetricID == mi.MetricID && mv.OrgLocationID == mi.OrgLocationID) // add one more linq select
                    {
                        if ((mv.ValueMetricDataTypeID == 1) && (mv.UnitOfMeasureID == mv.MetricUnitOfMeasureID))
                        {
                            // !!! for now we ignore values when its output uom != metric output uom
                            if (decimal.TryParse(mv.ConvertedValue, out Val))
                            {
                                cdv.AddCompositeDailyValue((DateTime)mv.InputDate, Val, (int)mv.FrequencyID, (DateTime)mv.Date, (int)mi.FrequencyID);
                            }
                        }
                    }
                }
                decimal?res = cdv.GetCompositeValue(BeginDate, EndDate, false);
                mi.SumValue = res == null ? "0" : res.ToString();
            }
            return(MetricInfo);
        }
        public int SendEmailWithOutTemplate(string fromAddress, string fromAddressName, string toAddress, string bccAddress, string ccAddress, string subject, string body)
        {
            int mailQId = 0;

            try
            {
                using (MailQDataContext mailqContextWithOutTemplate = new MailQDataContext())
                {
                    IMultipleResults results = mailqContextWithOutTemplate.SendEmailWithOutTemplate(
                        Sitecore.Configuration.Settings.GetSetting(FROM_ADDRESS_KEYNAME)
                        , Sitecore.Configuration.Settings.GetSetting(FROM_KEYNAME)
                        , bccAddress
                        , ccAddress
                        , toAddress
                        , subject
                        , body
                        , HTML_CONTENT
                        );

                    MailQID mailQ = results.GetResult <MailQID>().FirstOrDefault();

                    if (mailQ != null)
                    {
                        mailQId = mailQ.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(String.Format("Genworth.SitecoreExt.MailSender: SendEmailWithOutTemplate failed due to {0}", ex.Message), this);
                throw;
            }

            return(mailQId);
        }
Example #4
0
        public IMultipleResults GetCategory(int resultType)
        {
            IExecuteResult   executeResult = ExecuteMethodCall(this, (MethodInfo)(MethodInfo.GetCurrentMethod()), resultType);
            IMultipleResults result        = (IMultipleResults)executeResult.ReturnValue;

            return(result);
        }
        private void DoSearch()
        {
            CSBooster_DataAccessMRS csb     = new CSBooster_DataAccessMRS();
            IMultipleResults        results = csb.hisp_Navigation_GetNavigations(0, currentPage, PAGESIZE);

            var NavRSInfo = results.GetResult <_4screen.CSB.DataAccess.Data.CSBooster_DataAccessMRS.RecordNumerInfos>().FirstOrDefault();
            List <hitbl_NavigationStructure_NST> Navigations = results.GetResult <hitbl_NavigationStructure_NST>().ToList();

            numberItems = NavRSInfo.RowTotal;
            int checkedPage = IPagTop.CheckPageRange(this.currentPage, numberItems);

            if (checkedPage != currentPage) // Reload if the current and the checked page are different
            {
                this.currentPage = checkedPage;
                DoSearch();
            }
            else
            {
                IPagTop.InitPager(currentPage, numberItems);
                SaveState();
                if (numberItems > 0)
                {
                    RepNav.DataSource = Navigations;
                    RepNav.DataBind();
                }
                else
                {
                }
            }
        }
        /// <summary>
        /// Sets the underling value after the query has been executed.
        /// </summary>
        /// <param name="result">The <see cref="IMultipleResults"/> to get the result from.</param>
        protected virtual void SetResult(IMultipleResults result)
        {
            _isLoaded = true;
            List <T> resultList = null;

            try
            {
                var resultSet = result.GetResult <T>();
                resultList = resultSet != null?resultSet.ToList() : new List <T>();

                _result = resultList;
            }
            catch (Exception ex)
            {
                Exception = ex;
            }

            if (_cacheSettings == null || resultList == null)
            {
                return;
            }

            // cache the result
            string key = GetKey();

            QueryResultCache.SetResultCache(key, _cacheSettings, resultList);
        }
        public void LinqToSqlStoredProc03_2()
        {
            IMultipleResults result = DB.WholeOrPartialCustomersSet(2);
            IEnumerable <PartialCustomersSetResult> shape2 = result.GetResult <PartialCustomersSetResult> ();

            TestExecutor.Execute(shape2, MethodBase.GetCurrentMethod());
        }
        private void  射存储过程_Click(object sender, EventArgs e)
        {
            CRSContext context = new CRSContext(@"Data Source=10.1.2.249\sql2005;Initial Catalog=ECRS;Persist Security Info=True;User ID=sa;Password=$#@!;");

            //IEnumerable<DiscountByRule> result= context.GetDiscountByRule("12",'g001','001','001',3,'0',DateTime.Now);

            #region  射sp之单一结果集
            ISingleResult <DiscountByRule> result = context.GetDiscountByRule("12", "SVCARD", "T011", "0099", 3, "0");
            foreach (DiscountByRule discount in result)
            {
                textBox1.Text = "Disc_food=" + discount.Disc_food + "Disc_beve=" + discount.Disc_beve + "Disc_misc=" + discount.Disc_misc;
            }
            #endregion
            #region  射sp之标量返回
            int count = context.Customers_Count_By_Region("WA");
            Console.WriteLine(count);
            #endregion
            #region  射sp之多个可能形状的单一结果集
            //分别返回各自的结果集合,如下:
            //返回全部Customer结果集
            IMultipleResults result_multi = context.Whole_Or_Partial_Customers_Set(1);
            IEnumerable <WholeCustomersSetResult> shape1 =
                result_multi.GetResult <WholeCustomersSetResult>();
            foreach (WholeCustomersSetResult compName in shape1)
            {
                Console.WriteLine(compName.CompanyName);
            }
            //返回部分Customer结果集
            result_multi = context.Whole_Or_Partial_Customers_Set(2);
            IEnumerable <PartialCustomersSetResult> shape2 =
                result_multi.GetResult <PartialCustomersSetResult>();
            foreach (PartialCustomersSetResult con in shape2)
            {
                Console.WriteLine(con.ContactName);
            }
            #endregion
            #region  射sp之多个结果集
            IMultipleResults multi_result = context.Get_Customer_And_Orders("SEVES");
            //返回Customer结果集
            IEnumerable <CustomerResultSet> customer =
                multi_result.GetResult <CustomerResultSet>();
            //返回Orders结果集
            IEnumerable <OrdersResultSet> orders =
                multi_result.GetResult <OrdersResultSet>();
            //在这里,我们读取CustomerResultSet中的数据
            foreach (CustomerResultSet cust in customer)
            {
                Console.WriteLine(cust.CustomerID);
            }
            #endregion
            #region  射sp之带输出参数
            //我们使用下面的语句调用此存储过程:注意:输出参数是按引用传递的,以支持参数为“in/out”的方案。在这种情况下,参数仅为“out”
            decimal?totalSales = 0;
            string  customerID = "ALFKI";
            context.CustOrderTotal(customerID, ref totalSales);
            Console.WriteLine("Total Sales for Customer '{0}' = {1:C}",
                              customerID, totalSales);
            #endregion
        }
Example #9
0
        //検索処理
        private List <tblAgentAHT> SearchData(string pageIndex, string pageSize, string pageTotal, DateTime dtST, DateTime dtEnd, string vAgentID, bool isGroupBySkill)
        {
            AppLog.WriteLog("AHTController SearchData start");
            List <tblAgentAHT> result = new List <tblAgentAHT>();

            try
            {
                int currentPageIndex = m_CurPageIndex;
                int currentPageSize  = m_CurrentPageSize;

                int.TryParse(pageIndex, out currentPageIndex);
                int.TryParse(pageSize, out currentPageSize);

                m_CurPageIndex    = currentPageIndex;
                m_CurrentPageSize = currentPageSize;

                string strSortField = GetSortField(m_SortField);
                string strSort      = AppFunction.GetSortDefine(m_Sort);
                ViewBag.vTenantID         = this.TenantID;
                ViewBag.vTenantSpeciaFlag = this.TenantSpecialFlag;
                //ページを再計算する
                CalcPage(pageTotal);

                using (WFMDBDataContext db = new WFMDBDataContext())
                {
                    if (isGroupBySkill)
                    {
                        IMultipleResults results = db.uspWFMSearchAHTGroupBySkillPaged(m_CurPageIndex, m_CurrentPageSize, strSortField, strSort,
                                                                                       this.TenantID, dtST, dtEnd, this.TenantSpecialFlag, vAgentID);

                        result = results.GetResult <tblAgentAHT>().ToList();
                        tblDataPaged tblPage = results.GetResult <tblDataPaged>().FirstOrDefault();

                        m_TotalRowCount  = tblPage.TotalRowCount;
                        m_CurPageIndex   = tblPage.CurPageIndex;
                        m_TotlePageCount = tblPage.TotalPageCount;
                    }
                    else
                    {
                        IMultipleResults results = db.uspWFMSearchAHTGroupByAggregationPaged(m_CurPageIndex, m_CurrentPageSize, strSortField, strSort,
                                                                                             this.TenantID, dtST, dtEnd, this.TenantSpecialFlag, vAgentID);

                        result = results.GetResult <tblAgentAHT>().ToList();
                        tblDataPaged tblPage = results.GetResult <tblDataPaged>().FirstOrDefault();

                        m_TotalRowCount  = tblPage.TotalRowCount;
                        m_CurPageIndex   = tblPage.CurPageIndex;
                        m_TotlePageCount = tblPage.TotalPageCount;
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteLog("AHTController SearchData system error:" + ex.Message + ex.StackTrace);
            }


            return(result);
        }
        public void LinqToSqlStoredProc04_2()
        {
            IMultipleResults result = DB.GetCustomerAndOrders("SEVES");

            IEnumerable <OrdersResultSet> orders = result.GetResult <OrdersResultSet> ();

            TestExecutor.Execute(orders, MethodBase.GetCurrentMethod());
        }
Example #11
0
        /// <summary>
        /// 获取产品库存信息表
        /// </summary>
        /// <returns></returns>
        public Search_Result_Info GetProductInfos(string searchT, string searchV, int page, out int total)
        {
            Search_Result_Info infos = new Search_Result_Info();

            using (dataContext = new DataClassesDataContext())
            {
                #region
                //return (from q in dataContext.kucun_kdt_view
                //            group q by new { q.Com_nm, q.Sty_no } into g
                //            select new StyleInfo
                //            {
                //                Style_Name=g.Key.Com_nm,
                //                Style_No = g.Key.Sty_no,
                //                Count = g.Sum(p => p.Com_qu)
                //            }).OrderBy(p=>p.Style_No).Skip(0).Take(10).ToList();
                #endregion
                IMultipleResults query = null;
                switch (searchT)
                {
                case "1":    //按款式查询
                    query = dataContext.kdt_style_kucun_proc2(searchV, string.Empty, 0, 1, page);
                    break;

                case "2":    //按名称查询
                    query = dataContext.kdt_style_kucun_proc2(string.Empty, searchV, 0, 2, page);
                    break;

                case "3":    //按库存数查询
                    query = dataContext.kdt_style_kucun_proc2(string.Empty, string.Empty, Convert.ToDecimal(searchV), 3, page);
                    break;

                default:    //查询所有
                    query = dataContext.kdt_style_kucun_proc2(string.Empty, string.Empty, 0, 4, page);
                    break;
                }

                var kucun = query.GetResult <kdt_style_kucun_procResult>().ToList();
                if (page == 1)
                {
                    HttpContext.Current.Cache.Remove("total");
                }

                if (HttpContext.Current.Cache["total"] == null)
                {
                    total = query.GetResult <int>().FirstOrDefault();
                    HttpContext.Current.Cache["total"] = total;
                    infos.TotalPage = total;
                }
                else
                {
                    total = (int)HttpContext.Current.Cache["total"];
                }
                infos.Infos = kucun;
                return(infos);
                //.Skip((page-1)*10).Take(10).ToList();
            }
        }
Example #12
0
 public void StoreProcedureWithMultipleResultsTest()
 {
     using (AdventureWorks adventureWorks = new AdventureWorks())
         using (IMultipleResults results = adventureWorks.uspGetCategoryAndSubcategory(1))
         {
             EnumerableAssert.Single(results.GetResult <ProductCategory>());
             EnumerableAssert.Any(results.GetResult <ProductSubcategory>());
         }
 }
        /// <summary>
        /// Loads the data.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="password">The password.</param>
        /// <param name="windowsUserName">Name of the windows user.</param>
        private void LoadData(string userName, string password, string windowsUserName)
        {
            IMultipleResults multipleResults = GetData(userName, password, windowsUserName);

            IList <User> users = multipleResults.GetResult <User>().ToList();

            if (users.Count > 0)
            {
                User = users[0];
                _authorizationInfo = multipleResults.GetResult <AuthorizationInfo>().ToList();
            }
        }
Example #14
0
 public void Test_Batch_Queries()
 {
     using (var db = new TrackerDataContext {
         Log = Console.Out
     })
     {
         var q1 = from u in db.User select u;
         var q2 = from ur in db.UserRole select ur;
         IMultipleResults results = db.ExecuteQuery(q1, q2);
         List <User>      users   = results.GetResult <User>().ToList();
         List <UserRole>  roles   = results.GetResult <UserRole>().ToList();
     }
 }
        public IEnumerable <AuthorizationInfo> GetAuthorizationInfo(string username, string password)
        {
            IMultipleResults multipleResults = GetData(username, password, "");
            IEnumerable <AuthorizationInfo> authorizationInfo = null;

            IList <User> users = multipleResults.GetResult <User>().ToList();

            if (users != null && users.Count > 0)
            {
                User = users[0];
                authorizationInfo = multipleResults.GetResult <AuthorizationInfo>().ToList();
            }
            return(authorizationInfo);
        }
Example #16
0
        //検索処理
        private List <tblPedictionCall> SearchData(string pageIndex, string pageSize, string pageTotal, DateTime dtST, DateTime dtEnd, string dateType, string vSkillIDs, string vSkillAgregationIDs)
        {
            AppLog.WriteLog("CallReportController SearchData start");
            List <tblPedictionCall> result = new List <tblPedictionCall>();

            try
            {
                int currentPageIndex = m_CurPageIndex;
                int currentPageSize  = m_CurrentPageSize;

                int.TryParse(pageIndex, out currentPageIndex);
                int.TryParse(pageSize, out currentPageSize);
                int isByAggregation = 0;
                m_CurPageIndex    = currentPageIndex;
                m_CurrentPageSize = currentPageSize;

                string strSortField = GetSortField(m_SortField);
                string strSort      = AppFunction.GetSortDefine(m_Sort);
                ViewBag.vTenantID         = this.TenantID;
                ViewBag.vTenantSpeciaFlag = this.TenantSpecialFlag;
                if (ViewBag.RadioChecked == "byAgregation")
                {
                    isByAggregation = 1;
                }
                //ページを再計算する
                CalcPage(pageTotal);

                AppLog.WriteLog("CallReportController SearchData  db excute start");
                using (WFMDBDataContext db = new WFMDBDataContext())
                {
                    IMultipleResults results = db.uspWFMRptOfRealAndPredictionInboundCall(m_CurPageIndex, m_CurrentPageSize, strSortField, strSort,
                                                                                          this.TenantID, dtST, dtEnd, dateType, isByAggregation, vSkillIDs, vSkillAgregationIDs);

                    result = results.GetResult <tblPedictionCall>().ToList();
                    tblDataPaged tblPage = results.GetResult <tblDataPaged>().FirstOrDefault();

                    m_TotalRowCount  = tblPage.TotalRowCount;
                    m_CurPageIndex   = tblPage.CurPageIndex;
                    m_TotlePageCount = tblPage.TotalPageCount;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteLog(ex.Message + ex.StackTrace);
            }


            return(result);
        }
Example #17
0
        void method7seq()
        {
            // <Snippet7>
            Northwnd db = new Northwnd(@"c:\northwnd.mdf");

            IMultipleResults sprocResults =
                db.MultipleResultTypesSequentially();

            // First read products.
            foreach (Product prod in sprocResults.GetResult <Product>())
            {
                Console.WriteLine(prod.ProductID);
            }

            // Next read customers.
            foreach (Customer cust in sprocResults.GetResult <Customer>())
            {
                Console.WriteLine(cust.CustomerID);
            }
            // </Snippet7>
        }
        //検索処理
        private List <tblCallDetailV3> SearchData(string pageIndex, string pageSize, string pageTotal, DateTime dtST, DateTime dtEnd, string vCalleeid, string vCallerid, int skillID, int isessionprofileid, int iConntype, int iCompletedCall, int iQueCall, int iHasTransfer, int iHasACD, int iGroupID)
        {
            AppLog.WriteLog(string.Format("CallDetailController SearchData paramter is pageIndex:{0},pageSize:{1},pageTotal:{2},dtST:{3},dtEnd:{4},vCalleeid:{5},skillID:{6},groupid:{7}", pageIndex, pageSize, pageTotal, dtST.ToString(AppConst.Const_Format_YMDHMS)
                                          , dtEnd.ToString(AppConst.Const_Format_YMDHMS), vCalleeid, skillID.ToString(), iGroupID.ToString()));
            List <tblCallDetailV3> result = new List <tblCallDetailV3>();

            int currentPageIndex = m_CurPageIndex;
            int currentPageSize  = m_CurrentPageSize;

            int.TryParse(pageIndex, out currentPageIndex);
            int.TryParse(pageSize, out currentPageSize);

            m_CurPageIndex    = currentPageIndex;
            m_CurrentPageSize = currentPageSize;

            string strSortField = GetSortField(m_SortField);
            string strSort      = AppFunction.GetSortDefine(m_Sort);

            ViewBag.vTenantID         = this.TenantID;
            ViewBag.vTenantSpeciaFlag = this.TenantSpecialFlag;
            //ページを再計算する
            CalcPage(pageTotal);

            using (WFMDBDataContext db = new WFMDBDataContext(string.Format(System.Configuration.ConfigurationManager.ConnectionStrings["SpecialConnection"].ConnectionString, DBServer)))
            {
                IMultipleResults results = db.uspWFMGetCallDetailV3(m_CurPageIndex, m_CurrentPageSize, strSortField, strSort,
                                                                    this.TenantID, dtST.ToString(AppConst.Const_Format_YMDHMS), dtEnd.ToString(AppConst.Const_Format_YMDHMS), skillID, vCalleeid, vCallerid, isessionprofileid, iConntype, iCompletedCall, iQueCall, iHasTransfer, iHasACD, iGroupID);

                result = results.GetResult <tblCallDetailV3>().ToList();
                tblDataPaged tblPage = results.GetResult <tblDataPaged>().FirstOrDefault();

                m_TotalRowCount  = tblPage.TotalRowCount;
                m_CurPageIndex   = tblPage.CurPageIndex;
                m_TotlePageCount = tblPage.TotalPageCount;
            }

            return(result);
        }
Example #19
0
        /// <summary>
        /// Executes the future queries.
        /// </summary>
        public void ExecuteFutureQueries()
        {
            if (_futureQueries.Count == 0)
            {
                return;
            }

            // Get all the db comands
            var queries = new List <DbCommand>();
            var futures = new List <ILinqToSqlFutureQuery>();

            foreach (var future in _futureQueries)
            {
                if (future.IsLoaded)
                {
                    continue;
                }

                var command = future.GetCommand(this);
                // keep queries and futures in sync to apply result later
                queries.Add(command);
                futures.Add(future);
            }

            // run all non cached queries
            if (queries.Count > 0)
            {
                using (IMultipleResults results = this.ExecuteQuery(queries))
                    foreach (ILinqToSqlFutureQuery future in futures)
                    {
                        future.SetResult(results);
                    }
            }

            // once all queries processed, clear from queue
            _futureQueries.Clear();
        }
Example #20
0
        //検索処理
        private List <tblAgentWeekShift> SearchData(string pageIndex, string pageSize, string pageTotal, DateTime currentDate, string vAgentID)
        {
            List <tblAgentWeekShift> result = new List <tblAgentWeekShift>();

            int currentPageIndex = m_CurPageIndex;
            int currentPageSize  = m_CurrentPageSize;

            int.TryParse(pageIndex, out currentPageIndex);
            int.TryParse(pageSize, out currentPageSize);

            m_CurPageIndex    = currentPageIndex;
            m_CurrentPageSize = currentPageSize;

            string strSortField = GetSortField(m_SortField);
            string strSort      = AppFunction.GetSortDefine(m_Sort);

            ViewBag.vTenantID         = this.TenantID;
            ViewBag.vTenantSpeciaFlag = this.TenantSpecialFlag;
            ViewBag.currentDate       = currentDate.ToString(AppConst.Const_Format_YMD);
            //ページを再計算する
            CalcPage(pageTotal);

            using (WFMDBDataContext db = new WFMDBDataContext())
            {
                IMultipleResults results = db.uspWFMSearchShiftAgentPaged(m_CurPageIndex, m_CurrentPageSize, strSortField, strSort,
                                                                          this.TenantID, currentDate, this.TenantSpecialFlag, vAgentID);

                result = results.GetResult <tblAgentWeekShift>().ToList();
                tblDataPaged tblPage = results.GetResult <tblDataPaged>().FirstOrDefault();

                m_TotalRowCount  = tblPage.TotalRowCount;
                m_CurPageIndex   = tblPage.CurPageIndex;
                m_TotlePageCount = tblPage.TotalPageCount;
            }

            return(result);
        }
        //検索処理
        private List <tblAgentDetailV3> SearchData(string pageIndex, string pageSize, string pageTotal, DateTime dtST, DateTime dtEnd, string vLogin, int iAgentStatus)
        {
            List <tblAgentDetailV3> result = new List <tblAgentDetailV3>();

            int currentPageIndex = m_CurPageIndex;
            int currentPageSize  = m_CurrentPageSize;

            int.TryParse(pageIndex, out currentPageIndex);
            int.TryParse(pageSize, out currentPageSize);

            m_CurPageIndex    = currentPageIndex;
            m_CurrentPageSize = currentPageSize;

            string strSortField = GetSortField(m_SortField);
            string strSort      = AppFunction.GetSortDefine(m_Sort);

            ViewBag.vTenantID         = this.TenantID;
            ViewBag.vTenantSpeciaFlag = this.TenantSpecialFlag;
            //ページを再計算する
            CalcPage(pageTotal);

            using (WFMDBDataContext db = new WFMDBDataContext(string.Format(System.Configuration.ConfigurationManager.ConnectionStrings["SpecialConnection"].ConnectionString, DBServer)))
            {
                IMultipleResults results = db.uspWFMGetAgentDetailV3(m_CurPageIndex, m_CurrentPageSize, strSortField, strSort,
                                                                     this.TenantID, dtST.ToString(AppConst.Const_Format_YMDHMS), dtEnd.ToString(AppConst.Const_Format_YMDHMS), vLogin, iAgentStatus);

                result = results.GetResult <tblAgentDetailV3>().ToList();
                tblDataPaged tblPage = results.GetResult <tblDataPaged>().FirstOrDefault();

                m_TotalRowCount  = tblPage.TotalRowCount;
                m_CurPageIndex   = tblPage.CurPageIndex;
                m_TotlePageCount = tblPage.TotalPageCount;
            }

            return(result);
        }
Example #22
0
        public static List <MetricValue.Extend> MetricValuesForCalculation(int ActGen, out List <Bll.MetricValue.Extend> _OutputValues)
        {
            LinqMicajahDataContext dc = new LinqMicajahDataContext();

            //http://omaralzabir.com/linq_to_sql_solve_transaction_deadlock_and_query_timeout_problem_using_uncommitted_reads/
            // WITH (NOLOCK)
            int OldTimeOut = dc.CommandTimeout;

            dc.CommandTimeout = 600;

            IQueryable <MetricValue> metricValue =
                from mv in dc.MetricValue
                join m in dc.Metric on
                new { mv.InstanceId, mv.MetricID } equals
            new { m.InstanceId, m.MetricID }
            where
            mv.Status == true &&
            mv.IsCalc == true &&
            m.Generation == (ActGen - 1)
            select mv;

            foreach (MetricValue mv in metricValue)
            {
                mv.InProcess = true;
                mv.IsCalc    = false;
            }
            dc.SubmitChanges();

            IMultipleResults results = dc.Sp_SelectOutputMetricValues(ActGen);

            _OutputValues = results.GetResult <Sp_SelectOutputMetricValuesResult1>()
                            .Select(r => new Extend
            {
                // metric
                InstanceId  = (Guid)r.InstanceId,
                MetricID    = (Guid)r.MetricID,
                FrequencyID = (int)r.FrequencyID,
                MetricInputUnitOfMeasureID = r.MetricInputUnitOfMeasureID,
                MetricUnitOfMeasureID      = r.MetricUnitOfMeasureID,
                RelatedFormulaID           = r.MetricFormulaID,
                VariableFormula            = r.VariableFormula,
                // value
                MetricValueID = (Guid)r.MetricValueID,
                OrgLocationID = (Guid)r.OrgLocationID,
                Date          = (DateTime)r.Date
            })    //.OrderBy(r=>r.Date)
                            .ToList();

            List <MetricValue.Extend> _InputValues = results.GetResult <Sp_SelectOutputMetricValuesResult2>()
                                                     .Select(r => new Extend
            {
                // metric
                MetricID = (Guid)r.MetricID,
                Variable = r.Variable,
                MetricInputUnitOfMeasureID = r.MetricInputUnitOfMeasureID,
                MetricUnitOfMeasureID      = r.MetricUnitOfMeasureID,
                RelatedFormulaID           = r.MetricFormulaID,
                // value
                MetricValueID                 = (Guid)r.MetricValueID,
                OrgLocationID                 = (Guid)r.OrgLocationID,
                Date                          = (DateTime)r.Date,
                Value                         = r.Value,
                MissedCalc                    = (bool)r.MissedCalc,
                ConvertedValue                = r.ConvertedValue,
                InputUnitOfMeasureID          = r.ValueInputUnitOfMeasureID,
                UnitOfMeasureID               = r.ValueUnitOfMeasureID,
                RelatedOrgLocationUoMRecordID = r.MetricOrgLocationUoMID,
                OrgLocationUnitOfMeasureID    = r.OrgLocationUnitOfMeasureID
            })    //.OrderBy(r => r.Date) //???
                                                     .ToList();

            dc.CommandTimeout = OldTimeOut;
            return(_InputValues);
            //=========================

            /*Guid? _CurMetricID = null;
             * Guid? _CurOrgLocationID = null;
             * bool start = true;
             * foreach (MetricValue.Extend me in _OutputValues)
             * {
             *  if (start)
             *  {
             *      _CurMetricID = me.MetricID;
             *      _CurOrgLocationID = me.OrgLocationID;
             *  }
             *  me.UnitOfMeasureID = me.MetricUnitOfMeasureID;
             *  Guid? DefUoM = me.RelatedOrgLocationUoMRecordID == null ? me.MetricInputUnitOfMeasureID : me.OrgLocationUnitOfMeasureID;
             *  List<MetricValue.Extend> _RelatedInputValues = _InputValues.FindAll(r => (r.RelatedFormulaID == me.RelatedFormulaID) && (r.Date == me.Date) && (r.OrgLocationID == me.OrgLocationID));
             *  if (_RelatedInputValues.Count == 0)
             *      me.InputUnitOfMeasureID = DefUoM;
             *  bool IsSameInputUoMs = true;
             *  bool IsSameOutputUoMs = true;
             *  for (int i = 0; i < _RelatedInputValues.Count - 1; i++)
             *  {
             *      Guid? CurInputUoM = _RelatedInputValues[i].InputUnitOfMeasureID;
             *      Guid? CurOutputUoM = _RelatedInputValues[i].UnitOfMeasureID;
             *      for (int j = i + 1; j < _RelatedInputValues.Count; j++)
             *      {
             *          if (CurInputUoM != _RelatedInputValues[j].InputUnitOfMeasureID)
             *              IsSameInputUoMs = false;
             *          if (CurOutputUoM != _RelatedInputValues[j].UnitOfMeasureID)
             *              IsSameOutputUoMs = false;
             *      }
             *  }
             *  if (IsSameInputUoMs)
             *      me.InputUnitOfMeasureID = _RelatedInputValues[0].InputUnitOfMeasureID;
             *  else
             *      if (IsSameOutputUoMs)
             *          me.InputUnitOfMeasureID = _RelatedInputValues[0].UnitOfMeasureID;
             *      else
             *          me.InputUnitOfMeasureID = DefUoM;
             *
             *  if ((_CurMetricID != me.MetricID) || (_CurOrgLocationID != me.OrgLocationID) || start)
             *  {
             *      UpdateMetricOrgLocationUoM(me.InstanceId, me.MetricID, me.OrgLocationID, me.InputUnitOfMeasureID);
             *      _CurMetricID = me.MetricID;
             *      _CurOrgLocationID = me.OrgLocationID;
             *  }
             *  start = false;
             * }            */
        }
Example #23
0
        public QueryMapResultSet(IMultipleResults queryMapResultSets)
        {
            var queryMapResultSet = queryMapResultSets.GetResult <QueryMapMultiDepthResult>();

            while (queryMapResultSet != null)
            {
                foreach (var queryMapResult in queryMapResultSet)
                {
                    if (queryMapResult.Level != null)
                    {
                        if (queryMapResult.NodeUid.HasValue && queryMapResult.NodeUid != Guid.Empty)
                        {
                            /// Make sure that we aren't displaying a domain node.
                            if (queryMapResult.NodeTypeUid.HasValue && queryMapResult.NodeTypeUid != new Guid("263754C2-2F31-4D21-B9C4-6509E00A5E94"))
                            {
                                /// The QueryMap procedure returns ALL nodes by following relationships to max depth meaning some nodes are repeated in some of the levels multiple nodes may connect to them.
                                if (!Nodes.ContainsKey(queryMapResult.NodeUid.Value))
                                {
                                    /// TODO: Need to consider if we require the NodeOriginalId.
                                    QueryMapNode node = new QueryMapNode(queryMapResult);

                                    Nodes[queryMapResult.NodeUid.Value] = node;
                                }
                            }
                        }
                    }
                    else if (queryMapResult.MetadataId != null)
                    {
                        if (queryMapResult.MetadataId.HasValue && queryMapResult.MetadataId != Guid.Empty)
                        {
                            QueryMapMetadata metadatum = new QueryMapMetadata(queryMapResult);

                            if (metadatum.NodeUid.HasValue)
                            {
                                if (Nodes.ContainsKey(metadatum.NodeUid.Value))
                                {
                                    Nodes[metadatum.NodeUid.Value].AddMetadata(metadatum);
                                }
                            }

                            Metadata.Add(metadatum);
                        }
                    }
                    else if (queryMapResult.DescriptorUid != null)
                    {
                        if (queryMapResult.DescriptorUid.HasValue && queryMapResult.DescriptorUid != Guid.Empty)
                        {
                            QueryMapDescriptor descriptor = new QueryMapDescriptor(queryMapResult);

                            Descriptors.Add(descriptor);
                            AddDescriptorByNode(descriptor);
                            AddDescriptorByRelationship(descriptor);
                        }
                    }
                    else
                    {
                        if (queryMapResult.RelationshipUid.HasValue && queryMapResult.RelationshipUid != Guid.Empty)
                        {
                            /// TODO: Need to consider if we require the RelationshipOriginalId.
                            QueryMapRelationship relationship = new QueryMapRelationship(queryMapResult);

                            Relationships[relationship.RelationshipUid] = relationship;
                        }
                    }
                }

                queryMapResultSet = queryMapResultSets.GetResult <QueryMapMultiDepthResult>();
            }
        }
 /// <summary>
 /// Sets the underling value after the query has been executed.
 /// </summary>
 /// <param name="result">The <see cref="IMultipleResults"/> to get the result from.</param>
 void IFutureQuery.SetResult(IMultipleResults result)
 {
     SetResult(result);
 }
Example #25
0
        public QueryMapResultSet(IMultipleResults queryMapResultSets)
        {
            var queryMapResultSet = queryMapResultSets.GetResult<QueryMapMultiDepthResult>();

            while (queryMapResultSet != null)
            {
                foreach (var queryMapResult in queryMapResultSet)
                {
                    if (queryMapResult.Level != null)
                    {
                        if (queryMapResult.NodeUid.HasValue && queryMapResult.NodeUid != Guid.Empty)
                        {
                            /// Make sure that we aren't displaying a domain node.
                            if (queryMapResult.NodeTypeUid.HasValue && queryMapResult.NodeTypeUid != new Guid("263754C2-2F31-4D21-B9C4-6509E00A5E94"))
                            {
                                /// The QueryMap procedure returns ALL nodes by following relationships to max depth meaning some nodes are repeated in some of the levels multiple nodes may connect to them.
                                if (!Nodes.ContainsKey(queryMapResult.NodeUid.Value))
                                {
                                    /// TODO: Need to consider if we require the NodeOriginalId.
                                    QueryMapNode node = new QueryMapNode(queryMapResult);

                                    Nodes[queryMapResult.NodeUid.Value] = node;
                                }
                            }
                        }
                    }
                    else if (queryMapResult.MetadataId != null)
                    {
                        if (queryMapResult.MetadataId.HasValue && queryMapResult.MetadataId != Guid.Empty)
                        {
                            QueryMapMetadata metadatum = new QueryMapMetadata(queryMapResult);

                            if (metadatum.NodeUid.HasValue)
                            {
                                if (Nodes.ContainsKey(metadatum.NodeUid.Value))
                                {
                                    Nodes[metadatum.NodeUid.Value].AddMetadata(metadatum);
                                }
                            }

                            Metadata.Add(metadatum);
                        }
                    }
                    else if (queryMapResult.DescriptorUid != null)
                    {
                        if (queryMapResult.DescriptorUid.HasValue && queryMapResult.DescriptorUid != Guid.Empty)
                        {
                            QueryMapDescriptor descriptor = new QueryMapDescriptor(queryMapResult);

                            Descriptors.Add(descriptor);
                            AddDescriptorByNode(descriptor);
                            AddDescriptorByRelationship(descriptor);
                        }
                    }
                    else
                    {
                        if (queryMapResult.RelationshipUid.HasValue && queryMapResult.RelationshipUid != Guid.Empty)
                        {
                            /// TODO: Need to consider if we require the RelationshipOriginalId.
                            QueryMapRelationship relationship = new QueryMapRelationship(queryMapResult);

                            Relationships[relationship.RelationshipUid] = relationship;
                        }
                    }
                }

                queryMapResultSet = queryMapResultSets.GetResult<QueryMapMultiDepthResult>();
            }
        }
        public void Consume(IMultipleResults resultSets)
        {
            IEnumerable <QueryMapMultiDepthResult> resultSet = resultSets.GetResult <QueryMapMultiDepthResult>();

            while (resultSet != null)
            {
                foreach (var queryMapResult in resultSet)
                {
                    if (queryMapResult.Level != null)
                    {
                        if (queryMapResult.NodeUid.HasValue && queryMapResult.NodeUid != Guid.Empty)
                        {
                            /// The QueryMap procedure returns ALL nodes by following relationships to max depth meaning some nodes are repeated in some of the levels multiple nodes may connect to them.
                            if (!Nodes.ContainsKey(queryMapResult.NodeUid.Value))
                            {
                                /// TODO: Need to consider copying the NodeOriginalId.
                                QueryMapNode node = new QueryMapNode();
                                node.NodeUid     = queryMapResult.NodeUid.Value;
                                node.DomainUid   = queryMapResult.DomainUid.Value;
                                node.NodeTypeUid = queryMapResult.NodeTypeUid;

                                Nodes[queryMapResult.NodeUid.Value] = node;
                            }
                        }
                    }
                    else if (queryMapResult.MetadataId != null)
                    {
                        if (queryMapResult.MetadataId.HasValue && queryMapResult.MetadataId != Guid.Empty)
                        {
                            QueryMapMetadata metadatum = new QueryMapMetadata();
                            metadatum.MetadataId        = queryMapResult.MetadataId.Value;
                            metadatum.NodeUid           = queryMapResult.NodeUid;
                            metadatum.RelationshipUid   = queryMapResult.RelationshipUid;
                            metadatum.DescriptorTypeUid = queryMapResult.DescriptorTypeUid;
                            metadatum.MetadataTypeUid   = queryMapResult.MetadataTypeUid;
                            metadatum.MetadataName      = queryMapResult.MetadataName;
                            metadatum.MetadataValue     = queryMapResult.MetadataValue;

                            Metadata.Add(metadatum);
                        }
                    }
                    else if (queryMapResult.DescriptorUid != null)
                    {
                        if (queryMapResult.DescriptorUid.HasValue && queryMapResult.DescriptorUid != Guid.Empty)
                        {
                            QueryMapDescriptor descriptor = new QueryMapDescriptor();
                            descriptor.DescriptorUid     = queryMapResult.DescriptorUid.Value;
                            descriptor.NodeUid           = queryMapResult.NodeUid;
                            descriptor.RelationshipUid   = queryMapResult.RelationshipUid;
                            descriptor.DescriptorTypeUid = queryMapResult.DescriptorTypeUid;

                            Descriptors.Add(descriptor);
                        }
                    }
                    else
                    {
                        if (queryMapResult.RelationshipUid.HasValue && queryMapResult.RelationshipUid != Guid.Empty)
                        {
                            /// TODO: Need to consider copying the RelationshipOriginalId.
                            QueryMapRelationship relationship = new QueryMapRelationship();
                            relationship.RelationshipUid     = queryMapResult.RelationshipUid.Value;
                            relationship.DomainUid           = queryMapResult.DomainUid.Value;
                            relationship.RelationshipTypeUid = queryMapResult.RelationshipTypeUid;

                            Relationships[relationship.RelationshipUid] = relationship;
                        }
                    }
                }

                resultSet = resultSets.GetResult <QueryMapMultiDepthResult>();
            }
        }
        public void Consume(IMultipleResults resultSets)
        {
            IEnumerable<QueryMapMultiDepthResult> resultSet = resultSets.GetResult<QueryMapMultiDepthResult>();

            while (resultSet != null)
            {
                foreach (var queryMapResult in resultSet)
                {
                    if (queryMapResult.Level != null)
                    {
                        if (queryMapResult.NodeUid.HasValue && queryMapResult.NodeUid != Guid.Empty)
                        {
                            /// The QueryMap procedure returns ALL nodes by following relationships to max depth meaning some nodes are repeated in some of the levels multiple nodes may connect to them.
                            if (!Nodes.ContainsKey(queryMapResult.NodeUid.Value))
                            {
                                /// TODO: Need to consider copying the NodeOriginalId.
                                QueryMapNode node = new QueryMapNode();
                                node.NodeUid = queryMapResult.NodeUid.Value;
                                node.DomainUid = queryMapResult.DomainUid.Value;
                                node.NodeTypeUid = queryMapResult.NodeTypeUid;

                                Nodes[queryMapResult.NodeUid.Value] = node;
                            }
                        }
                    }
                    else if (queryMapResult.MetadataId != null)
                    {
                        if (queryMapResult.MetadataId.HasValue && queryMapResult.MetadataId != Guid.Empty)
                        {
                            QueryMapMetadata metadatum = new QueryMapMetadata();
                            metadatum.MetadataId = queryMapResult.MetadataId.Value;
                            metadatum.NodeUid = queryMapResult.NodeUid;
                            metadatum.RelationshipUid = queryMapResult.RelationshipUid;
                            metadatum.DescriptorTypeUid = queryMapResult.DescriptorTypeUid;
                            metadatum.MetadataTypeUid = queryMapResult.MetadataTypeUid;
                            metadatum.MetadataName = queryMapResult.MetadataName;
                            metadatum.MetadataValue = queryMapResult.MetadataValue;

                            Metadata.Add(metadatum);
                        }
                    }
                    else if (queryMapResult.DescriptorUid != null)
                    {
                        if (queryMapResult.DescriptorUid.HasValue && queryMapResult.DescriptorUid != Guid.Empty)
                        {
                            QueryMapDescriptor descriptor = new QueryMapDescriptor();
                            descriptor.DescriptorUid = queryMapResult.DescriptorUid.Value;
                            descriptor.NodeUid = queryMapResult.NodeUid;
                            descriptor.RelationshipUid = queryMapResult.RelationshipUid;
                            descriptor.DescriptorTypeUid = queryMapResult.DescriptorTypeUid;

                            Descriptors.Add(descriptor);
                        }
                    }
                    else
                    {
                        if (queryMapResult.RelationshipUid.HasValue && queryMapResult.RelationshipUid != Guid.Empty)
                        {
                            /// TODO: Need to consider copying the RelationshipOriginalId.
                            QueryMapRelationship relationship = new QueryMapRelationship();
                            relationship.RelationshipUid = queryMapResult.RelationshipUid.Value;
                            relationship.DomainUid = queryMapResult.DomainUid.Value;
                            relationship.RelationshipTypeUid = queryMapResult.RelationshipTypeUid;

                            Relationships[relationship.RelationshipUid] = relationship;
                        }
                    }
                }

                resultSet = resultSets.GetResult<QueryMapMultiDepthResult>();
            }
        }
Example #28
0
 /// <summary>
 /// Sets the underling value after the query has been executed.
 /// </summary>
 /// <param name="result">The <see cref="IMultipleResults"/> to get the result from.</param>
 void ILinqToSqlFutureQuery.SetResult(IMultipleResults result)
 {
     SetResult(result);
 }
        static void Main(string[] args)
        {
            AdventureWorks dc = new AdventureWorks(@"Data Source=(local);Initial Catalog=AdventureWorks2012;User Id=sa;Password=saadmin;");

            #region Consulta com uma tabela (Consulta manual - via código)
            var result = from pc in dc.ProductCategories
                         orderby pc.Name
                         select pc;

            //Em sintaxe de método ficaria da seguinte forma:
            //var result = dc.ProductCategories.OrderBy(pc => pc.Name);

            foreach (var item in result)
            {
                Console.WriteLine(item.Name);
            }
            #endregion

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

            #region Consulta com relacionamento chave primária/chave estrangeira (Consulta manual - via código)
            var result2 = from pc in dc.ProductCategories
                          orderby pc.Name
                          select new { Nome = pc.Name, SubCategorias = pc.ProductSubcategories };

            //Em sintaxe de método ficaria da seguinte forma:
            //var result = dc.ProductCategories.OrderBy(pc => pc.Name).Select(pc => new {Nome = pc.Name, SubCategorias = pc.ProductSubcategories });

            foreach (var item in result2)
            {
                Console.WriteLine("******************************");
                Console.WriteLine("Subcategorias de {0}:", item.Nome);
                foreach (var sub in item.SubCategorias)
                {
                    Console.WriteLine("{0}", sub.Name);
                }
                Console.WriteLine("******************************");
                Console.WriteLine("");
            }
            #endregion

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

            #region Consulta (via ferramenta)
            AdventureWorksByToolDataContext dc2 = new AdventureWorksByToolDataContext();

            // Retorna o comando SQL
            dc2.Log = Console.Out;

            var result3 = from pc in dc2.ProductCategories
                          orderby pc.Name
                          select pc;

            //Em sintaxe de método ficaria da seguinte forma:
            //var result = dc.ProductCategories.OrderBy(pc => pc.Name);

            foreach (var item in result3)
            {
                Console.WriteLine(item.Name);
            }
            #endregion

            #region Inclusão, alteração, deleção e consulta
            int op = 1;
            while (op != 0)
            {
                Console.Clear();
                Console.WriteLine("Dentre as alternativas abaixo:");
                Console.WriteLine("1 - Consultar");
                Console.WriteLine("2 - Incluir");
                Console.WriteLine("3 - Alterar");
                Console.WriteLine("4 - Excluir");
                Console.WriteLine("0 - Sair");
                Console.WriteLine("Selecione uma opcao:");
                if (!Int32.TryParse(Console.ReadLine().ToString(), out op))
                {
                    op = -1;
                }

                switch (op)
                {
                case 1:
                    RealizarConsulta();
                    break;

                case 2:
                    RealizarInclusao();
                    break;

                case 3:
                    RealizarAlteracao();
                    break;

                case 4:
                    RealizarExclusao();
                    break;

                case 0:
                    Console.WriteLine("Bye!");
                    break;

                default:
                    Console.WriteLine("Opcao invalida!\n\n");
                    Console.ReadKey();
                    break;
                }
            }
            #endregion

            #region Lidando com procedures (via código)
            IMultipleResults resultProcedure = dc.GetCategory(1);
            Console.WriteLine("Categorias:");
            foreach (var item in resultProcedure.GetResult <CodeFirst.ProductCategory>())
            {
                Console.WriteLine("{0} - {1}", item.ProductCategoryID, item.Name);
            }
            #endregion

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

            #region Lidando com procedures (via ferramenta)
            AdventureWorksByToolDataContext dcFerramenta = new AdventureWorksByToolDataContext();
            var resultProcedureFerramenta = from pc in dcFerramenta.usp_GetCategory(1)
                                            orderby pc.Name
                                            select pc;

            //Em sintaxe de método ficaria da seguinte forma:
            //var result = dc.usp_GetCategory(1).OrderBy(pc => pc.Name);

            Console.WriteLine("Categorias:");
            foreach (var item in result)
            {
                Console.WriteLine("{0} - {1}", item.ProductCategoryID, item.Name);
            }
            #endregion

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

            #region Lidando com functions (via código)
            var resultFunction = from p in dc.FindSubcategories("bike")
                                 orderby p.Name descending
                                 select new { p.Name, p.ProductSubcategoryID, MaxPrice = dc.MaxPriceBySubcategory(p.ProductSubcategoryID) };

            //Em sintaxe de método ficaria da seguinte forma:
            //var result = dc.FindSubcategories("bike").OrderByDescending(pc => pc.Name).Select(p => new { p.Name, p.ProductSubcategoryID, MaxPrice = dc.MaxPriceBySubcategory(p.ProductSubcategoryID) });

            Console.WriteLine("Subcategorias com bike no nome:");
            foreach (var item in resultFunction)
            {
                Console.WriteLine("{0} - {1} - {2}", item.ProductSubcategoryID, item.Name, item.MaxPrice.GetValueOrDefault(0).ToString("C"));
            }
            #endregion

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

            #region Lidando com functions (via ferramenta)
            AdventureWorksByToolDataContext dcFunction = new AdventureWorksByToolDataContext();
            var resultFunction2 = from pc in dcFunction.FindProductSubcategoriesByName("Shorts")
                                  orderby pc.Name
                                  select new { pc.Name, pc.ProductSubcategoryID, MaxPrice = dcFunction.GetMaxPriceBySubcategory(pc.ProductSubcategoryID) };

            //Em sintaxe de método ficaria da seguinte forma:
            //var result = dc.FindProductSubcategoriesByName("Shorts").OrderByDescending(pc => pc.Name).Select(p => new { p.Name, p.ProductSubcategoryID, MaxPrice = dc.GetMaxPriceBySubcategory(p.ProductSubcategoryID) });

            Console.WriteLine("Subcategorias com shorts no nome:");
            foreach (var item in resultFunction2)
            {
                Console.WriteLine("{0} - {1} - {2}", item.ProductSubcategoryID, item.Name, item.MaxPrice.GetValueOrDefault(0).ToString("C"));
            }
            #endregion

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

            #region Consultas compiladas
            AdventureWorksByToolDataContext dcComplida           = new AdventureWorksByToolDataContext();
            Table <ProductSubcategory>      ProductSubcategories = dcComplida.GetTable <ProductSubcategory>();

            var query = CompiledQuery.Compile(
                (DataContext context, string filterName) =>
                from p in ProductSubcategories
                where p.Name.Contains(filterName)
                select new { p.Name, p.ProductSubcategoryID });

            Console.WriteLine("Subcategorias com Bike no nome:");
            foreach (var item in query(dc, "Bike"))
            {
                Console.WriteLine("{0} - {1}", item.ProductSubcategoryID, item.Name);
            }

            Console.WriteLine("\n\nSubcategorias com Shorts no nome:");
            foreach (var item in query(dc, "Shorts"))
            {
                Console.WriteLine("{0} - {1}", item.ProductSubcategoryID, item.Name);
            }
            #endregion

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

            #region Executando consultas diretas
            AdventureWorksByToolDataContext dcDiretas = new AdventureWorksByToolDataContext();

            var resultDiretas = dcDiretas.ExecuteQuery <ProductSubcategory>(@"SELECT TOP(50)PERCENT ProductSubcategoryID, Name, rowguid, ModifiedDate FROM Production.ProductSubcategory");

            Console.WriteLine("50% das subcategorias cadastradas:");
            foreach (var item in resultDiretas)
            {
                Console.WriteLine("{0} - {1}", item.ProductSubcategoryID, item.Name);
            }
            #endregion

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

            Console.ReadKey();
        }
Example #30
0
        public void ProcessRequest(HttpContext context)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                context.Response.Expires         = -1;
                context.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
                context.Response.AddHeader("cache-control", "private");
                context.Response.CacheControl = "no-cache";
                context.Response.ContentType  = "text/javascript";

                string serverUrl      = HttpUtility.UrlDecode(context.Request.QueryString["site"]);
                string mapIdString    = context.Request.QueryString["MapId"];
                string domainIdString = context.Request.QueryString["DomainId"];

                if (string.IsNullOrEmpty(mapIdString) || string.IsNullOrEmpty(domainIdString))
                {
                    /// We haven't been given enough information to be able to bring back a map.
                    context.Response.Write("[]");

                    return;
                }

                Guid mapId;
                Guid domainId;

                try
                {
                    mapId    = new Guid(mapIdString);
                    domainId = new Guid(domainIdString);
                }
                catch
                {
                    /// Means we got an illegally formed ID.
                    context.Response.Write("[]");

                    return;
                }

                ConnectionStringBuilder connectionStringBuilder = new ConnectionStringBuilder(serverUrl);
                string connectionString = connectionStringBuilder.BuildMapConnectionString();

                using (MappingToolDatabaseDataContext dataContext = new MappingToolDatabaseDataContext(connectionString))
                {
                    IMultipleResults results = dataContext.QueryMapMultiDepth(domainId, mapId, 1, false);

                    QueryMapResultSet resultSet = new QueryMapResultSet(results);

                    List <QueryMapNode> nodesInMap = new List <QueryMapNode>();
                    Dictionary <Guid, Dictionary <Guid, QueryMapDescriptor> > arrowsInMap = new Dictionary <Guid, Dictionary <Guid, QueryMapDescriptor> >();

                    HashSet <Guid> relatedMapsNodeSet = new HashSet <Guid>();

                    #region Find all the nodes in the current map and get their relationships to other nodes.
                    var mapRelationships = resultSet.GetRelationshipsByDescriptorType(mapId, QueryMapResultSet.ToDescriptorType);

                    foreach (QueryMapRelationship mapRelationship in mapRelationships)
                    {
                        QueryMapNode node = resultSet.GetNode(mapRelationship.RelationshipUid, QueryMapResultSet.FromDescriptorType);
                        node.SetMetadataView(mapRelationship.RelationshipUid);

                        if (node != null)
                        {
                            nodesInMap.Add(node);
                        }

                        IEnumerable <QueryMapRelationship> queryMapRelationships = resultSet.GetRelationshipsByRelationshipType(node.NodeUid, QueryMapResultSet.FromToRelationshipType, QueryMapResultSet.TransclusionFromToRelationshipType);

                        foreach (QueryMapRelationship relationship in queryMapRelationships)
                        {
                            Dictionary <Guid, QueryMapDescriptor> descriptors = resultSet.GetNodes(relationship.RelationshipUid);

                            if (relationship.RelationshipTypeUid.Value == QueryMapResultSet.TransclusionFromToRelationshipType)
                            {
                                if (!descriptors.ContainsKey(QueryMapResultSet.TransclusionMapDescriptorType))
                                {
                                    continue;
                                }

                                if (descriptors[QueryMapResultSet.TransclusionMapDescriptorType].NodeUid.Value != mapId)
                                {
                                    continue;
                                }
                            }

                            arrowsInMap[relationship.RelationshipUid] = descriptors;
                        }
                    }
                    #endregion

                    JsonMapObjects mapObjects = new JsonMapObjects();
                    mapObjects.domain         = domainId;

                    QueryMapNode rootMapNode = null;
                    QueryMapNode mapNode     = null;

                    #region Build out the nodes
                    List <JsonNode> nodes = new List <JsonNode>();

                    int nodeCount = 0;
                    Dictionary <Guid, int> nodeIndexes = new Dictionary <Guid, int>();

                    foreach (QueryMapNode node in nodesInMap)
                    {
                        if (node.NodeUid == mapId)
                        {
                            /// If we encounter the map node, don't include this in the returned nodes as we don't need it present on the map. We will put aside though as we will need it for the breadcrumb.
                            mapNode = node;
                            continue;
                        }

                        JsonNode jsonNode = new JsonNode(node);

                        if (jsonNode.IsProperlyStructured)
                        {
                            nodeIndexes[node.NodeUid] = nodeCount;
                            nodes.Add(jsonNode);
                            nodeCount++;

                            /// The following procedure is to get the related maps.
                            resultSet.FindNodeIdsByRelationshipType(node.NodeUid, ref relatedMapsNodeSet, mapId, QueryMapResultSet.ToDescriptorType, QueryMapResultSet.MapContainerRelationshipType);
                        }
                    }

                    #region Find transcluded maps
                    Dictionary <Guid, SearchedNode> relatedMapsNodes = null;

                    if (relatedMapsNodeSet.Count > 0)
                    {
                        using (SqlConnection connection = new SqlConnection(connectionString))
                        {
                            connection.Open();

                            DataTable relatedMapsNodeList = new DataTable();
                            relatedMapsNodeList.Columns.Add("NodeUid");

                            foreach (Guid relatedMapsNode in relatedMapsNodeSet)
                            {
                                relatedMapsNodeList.Rows.Add(relatedMapsNode);
                            }

                            using (SPSite site = new SPSite(serverUrl))
                            {
                                SPWeb web = site.OpenWeb();

                                QueryNodes queryNodes = new QueryNodes(web, connection);
                                relatedMapsNodes      = queryNodes.GetNodes(relatedMapsNodeList);
                            }

                            connection.Close();
                        }
                    }

                    if (relatedMapsNodes != null)
                    {
                        foreach (JsonNode node in nodes)
                        {
                            HashSet <Guid> relatedMapIds = new HashSet <Guid>();

                            if (node.IsProperlyStructured)
                            {
                                resultSet.FindNodeIdsByRelationshipType(node.UniqueId, ref relatedMapIds, mapId, QueryMapResultSet.ToDescriptorType, QueryMapResultSet.MapContainerRelationshipType);

                                List <JsonRelatedMap> jsonRelatedMaps = new List <JsonRelatedMap>();

                                foreach (Guid relatedMapId in relatedMapIds)
                                {
                                    if (relatedMapsNodes.ContainsKey(relatedMapId))
                                    {
                                        JsonRelatedMap jsonRelatedMap = new JsonRelatedMap();
                                        jsonRelatedMap.DomainId       = domainId;
                                        jsonRelatedMap.NodeId         = node.UniqueId;
                                        jsonRelatedMap.MapNodeId      = relatedMapId;
                                        jsonRelatedMap.Name           = Uri.EscapeDataString(relatedMapsNodes[relatedMapId].Metadata["Name"]);

                                        jsonRelatedMaps.Add(jsonRelatedMap);
                                    }
                                }

                                if (jsonRelatedMaps.Count > 0)
                                {
                                    node["RelatedMaps"] = jsonRelatedMaps.ToArray();
                                }
                            }
                        }
                    }
                    #endregion
                    #endregion

                    mapObjects.nodes = nodes.ToArray();

                    #region Build out the arrows
                    List <JsonArrow> arrows = new List <JsonArrow>();

                    int arrowCount = 0;

                    foreach (Dictionary <Guid, QueryMapDescriptor> arrowDescriptors in arrowsInMap.Values)
                    {
                        int fromIndex = -1;
                        int toIndex   = -1;

                        foreach (KeyValuePair <Guid, QueryMapDescriptor> arrowDescriptorPair in arrowDescriptors)
                        {
                            if (arrowDescriptorPair.Key == QueryMapResultSet.FromDescriptorType)
                            {
                                if (nodeIndexes.ContainsKey(arrowDescriptorPair.Value.NodeUid.Value))
                                {
                                    fromIndex = nodeIndexes[arrowDescriptorPair.Value.NodeUid.Value];
                                }
                            }
                            else if (arrowDescriptorPair.Key == QueryMapResultSet.ToDescriptorType)
                            {
                                if (nodeIndexes.ContainsKey(arrowDescriptorPair.Value.NodeUid.Value))
                                {
                                    toIndex = nodeIndexes[arrowDescriptorPair.Value.NodeUid.Value];
                                }
                            }
                        }

                        arrowCount++;

                        if (fromIndex >= 0 && toIndex >= 0)
                        {
                            JsonArrow arrow = new JsonArrow();
                            arrow.from      = fromIndex;
                            arrow.to        = toIndex;

                            arrows.Add(arrow);
                        }
                    }
                    #endregion

                    mapObjects.arrows = arrows.ToArray();

                    #region Build the root map node details
                    if (mapNode == null && resultSet.Nodes.ContainsKey(mapId))
                    {
                        mapNode = resultSet.Nodes[mapId];
                    }

                    Guid rootMapId = mapNode.RootMapUid.Value;

                    IMultipleResults rootMapResults    = dataContext.QueryMapMultiDepth(domainId, rootMapId, 0, false);
                    QueryMapResultSet rootMapResultSet = new QueryMapResultSet(rootMapResults);

                    if (rootMapResultSet.Nodes.ContainsKey(rootMapId))
                    {
                        rootMapNode = rootMapResultSet.Nodes[rootMapId];
                        JsonNode rootMapJsonNode = new JsonNode(rootMapNode);

                        mapObjects.rootMap = rootMapJsonNode;
                    }
                    #endregion

                    #region Build out the breadcrumbs
                    /// TODO: This is just a basic breadcrumb for now.
                    List <JsonBreadcrumb> breadcrumbs = new List <JsonBreadcrumb>();

                    if (rootMapNode != null)
                    {
                        breadcrumbs.Add(new JsonBreadcrumb(rootMapNode));
                    }

                    if (mapId != rootMapNode.NodeUid)
                    {
                        if (mapNode != null)
                        {
                            breadcrumbs.Add(new JsonBreadcrumb(mapNode));
                        }
                    }
                    #endregion

                    mapObjects.breadcrumbs = breadcrumbs.ToArray();

                    JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                    string mapObjectsAsJson             = jsonSerializer.Serialize(mapObjects);

                    context.Response.Write(mapObjectsAsJson);
                }
            });
        }