public ActionResult Edit(KundeEditModel model)
        {
            using (var rs = new RequestScope(this))
            {
                var kunde = rs.DC.Kunders.Single(k => k.Kunde_GUID == model.Id);
                kunde.IsSupportSiteEnabled = model.IsSupportSiteEnabled;

                var standardInvoiceTypeId = model.StandardFakturaTypeId != Guid.Empty ? model.StandardFakturaTypeId : new Guid?();

                if (kunde.KundeExtensions.Any() == false)
                {
                    kunde.KundeExtensions.Add(new KundeExtension()
                    {
                        DefaultInvoiceTypeId = standardInvoiceTypeId
                    });
                }
                else
                {
                    kunde.KundeExtensions.Single().DefaultInvoiceTypeId = standardInvoiceTypeId;
                }

                rs.DC.SaveChanges();

                // Reindexer kunder
                var sm = new ElasticSearchManager(Properties.Settings.Default.ElasticSearchUrl);
                sm.IndexCustomer(kunde.Kunde_GUID);

                var kundeEditModel = BuildEditModel(kunde, rs);

                return View(kundeEditModel);
            }
        }
        public JsonResult CreateForTaskPicker(Guid companyId, Guid? contactId, string caption = "")
        {
            using (var rs = new RequestScope(this))
            {
                var company = rs.DC.Kunders.Single(k => k.Kunde_GUID == companyId);

                var systemArbejdeTaskLog = TaskTypeRepository.GetSystemArbejdeTaskType(rs.DC);
                var invoiceType = KundeRepository.FindStandardFakturaType(company);

                var newTask = TaskRepository.CreateTask(
                    companyId,
                    contactId,
                    caption,
                    string.Empty,
                    rs.DC,
                    invoiceType,
                    systemArbejdeTaskLog,
                    rs.Bruger.BrugerGuid,
                    null);

                newTask.Task_WebCreated = 1;
                newTask.Task_WebVisible = 1;

                rs.DC.Tasks.Add(newTask);

                rs.DC.SaveChanges();

                var newTaskSelectionModel = new TaskSelectionModel(rs.DC, newTask);

                return Json(newTaskSelectionModel, JsonRequestBehavior.AllowGet);
            }
        }
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="session"></param>
		/// <param name="statement"></param>
		/// <param name="commandText"></param>
		/// <param name="request"></param>
		public PreparedStatementFactory(ISqlMapSession session, RequestScope request, IStatement statement, string commandText)
		{
			_session = session;
			_request = request;
			_statement = statement;
			_commandText = commandText;
		}
        public ActionResult Index()
        {
            using (var rs = new RequestScope(this))
            {
                var model = new KundeIndexModel();

                return View(model);
            }
        }
        public ActionResult Edit(Guid id)
        {
            using (var rs = new RequestScope(this))
            {
                var kunde = rs.DC.Kunders.Single(k => k.Kunde_GUID == id);
                var kundeEditModel = BuildEditModel(kunde, rs);

                return View(kundeEditModel);
            }
        }
示例#6
0
		/// <summary>
		/// Builds a new <see cref="RequestScope"/> and the sql command text to execute.
		/// </summary>
		/// <param name="parameterObject">The parameter object (used in DynamicSql)</param>
		/// <param name="session">The current session</param>
		/// <param name="mappedStatement">The <see cref="IMappedStatement"/>.</param>
		/// <returns>A new <see cref="RequestScope"/>.</returns>
		public RequestScope GetRequestScope(IMappedStatement mappedStatement, 
			object parameterObject, ISqlMapSession session)
		{
			RequestScope request = new RequestScope(_dataExchangeFactory, session, _statement);

			request.PreparedStatement = BuildPreparedStatement(session, request, _sqlStatement);
			request.MappedStatement = mappedStatement;

			return request;
		}
示例#7
0
        internal IDictionary RunQueryForMap(RequestScope request, ISqlMapSession session, object parameterObject, string keyProperty, string valueProperty, DictionaryRowDelegate rowDelegate)
        {
            IDictionary dictionary = new Hashtable();

            using (IDbCommand command = request.IDbCommand)
            {
                IDataReader reader = command.ExecuteReader();
                try
                {
                    object obj5;
                    if (rowDelegate != null)
                    {
                        goto Label_00C4;
                    }
                    while (reader.Read())
                    {
                        object obj2 = this._resultStrategy.Process(request, ref reader, null);
                        object obj3 = ObjectProbe.GetMemberValue(obj2, keyProperty, request.DataExchangeFactory.AccessorFactory);
                        object obj4 = obj2;
                        if (valueProperty != null)
                        {
                            obj4 = ObjectProbe.GetMemberValue(obj2, valueProperty, request.DataExchangeFactory.AccessorFactory);
                        }
                        dictionary.Add(obj3, obj4);
                    }
                    goto Label_00E0;
Label_0072:
                    obj5 = this._resultStrategy.Process(request, ref reader, null);
                    object key  = ObjectProbe.GetMemberValue(obj5, keyProperty, request.DataExchangeFactory.AccessorFactory);
                    object obj7 = obj5;
                    if (valueProperty != null)
                    {
                        obj7 = ObjectProbe.GetMemberValue(obj5, valueProperty, request.DataExchangeFactory.AccessorFactory);
                    }
                    rowDelegate(key, obj7, parameterObject, dictionary);
Label_00C4:
                    if (reader.Read())
                    {
                        goto Label_0072;
                    }
                }
                catch
                {
                    throw;
                }
                finally
                {
                    reader.Close();
                    reader.Dispose();
                }
Label_00E0:
                this.ExecutePostSelect(request);
            }
            return(dictionary);
        }
示例#8
0
        public object Get(RequestScope request, IResultMap resultMap, ResultProperty mapping, ref object target, IDataReader reader)
        {
            IList  list = null;
            object obj2 = ObjectProbe.GetMemberValue(target, mapping.PropertyName, request.DataExchangeFactory.AccessorFactory);

            if (obj2 == null)
            {
                obj2 = mapping.ListFactory.CreateInstance(null);
                mapping.SetAccessor.Set(target, obj2);
            }
            list = (IList)obj2;
            object     sKIP = null;
            IResultMap map  = mapping.NestedResultMap.ResolveSubMap(reader);

            if (map.GroupByProperties.Count > 0)
            {
                string      key        = base.GetUniqueKey(map, request, reader);
                IDictionary uniqueKeys = request.GetUniqueKeys(map);
                if ((uniqueKeys != null) && uniqueKeys.Contains(key))
                {
                    sKIP = uniqueKeys[key];
                    if (sKIP != null)
                    {
                        for (int i = 0; i < map.Properties.Count; i++)
                        {
                            ResultProperty property = map.Properties[i];
                            if (property.PropertyStrategy is GroupByStrategy)
                            {
                                property.PropertyStrategy.Set(request, map, property, ref sKIP, reader, null);
                            }
                        }
                    }
                    sKIP = BaseStrategy.SKIP;
                }
                else if (((key == null) || (uniqueKeys == null)) || !uniqueKeys.Contains(key))
                {
                    sKIP = _resultMapStrategy.Get(request, resultMap, mapping, ref target, reader);
                    if (uniqueKeys == null)
                    {
                        uniqueKeys = new Hashtable();
                        request.SetUniqueKeys(map, uniqueKeys);
                    }
                    uniqueKeys[key] = sKIP;
                }
            }
            else
            {
                sKIP = _resultMapStrategy.Get(request, resultMap, mapping, ref target, reader);
            }
            if ((sKIP != null) && (sKIP != BaseStrategy.SKIP))
            {
                list.Add(sKIP);
            }
            return(sKIP);
        }
示例#9
0
        public virtual IDictionary ExecuteQueryForMapWithRowDelegate(ISqlMapSession session, object parameterObject, string keyProperty, string valueProperty, DictionaryRowDelegate rowDelegate)
        {
            RequestScope request = this._statement.Sql.GetRequestScope(this, parameterObject, session);

            if (rowDelegate == null)
            {
                throw new DataMapperException("A null DictionaryRowDelegate was passed to QueryForMapWithRowDelegate.");
            }
            this._preparedCommand.Create(request, session, this.Statement, parameterObject);
            return(this.RunQueryForMap(request, session, parameterObject, keyProperty, valueProperty, rowDelegate));
        }
示例#10
0
        public virtual IList <T> ExecuteQueryForRowDelegate <T>(ISqlMapSession session, object parameterObject, RowDelegate <T> rowDelegate)
        {
            RequestScope request = this._statement.Sql.GetRequestScope(this, parameterObject, session);

            this._preparedCommand.Create(request, session, this.Statement, parameterObject);
            if (rowDelegate == null)
            {
                throw new DataMapperException("A null RowDelegate was passed to QueryForRowDelegate.");
            }
            return(this.RunQueryForList <T>(request, session, parameterObject, null, rowDelegate));
        }
示例#11
0
        /// <summary>
        /// Builds a new <see cref="RequestScope"/> and the sql command text to execute.
        /// </summary>
        /// <param name="mappedStatement">The <see cref="IMappedStatement"/>.</param>
        /// <param name="parameterObject">The parameter object (used in DynamicSql)</param>
        /// <param name="session">The current session</param>
        /// <returns>A new <see cref="RequestScope"/>.</returns>
        public RequestScope GetRequestScope(
            IMappedStatement mappedStatement,
            object parameterObject, ISession session)
        {
            RequestScope request = new RequestScope(dataExchangeFactory, session, statement);

            request.PreparedStatement = BuildPreparedStatement(session, request, sqlStatement);
            request.MappedStatement   = mappedStatement;

            return(request);
        }
示例#12
0
 private void RetrieveOutputParameters(RequestScope request, ISqlMapSession session, IDbCommand command, object result)
 {
     if (request.ParameterMap != null)
     {
         int count = request.ParameterMap.PropertiesList.Count;
         for (int i = 0; i < count; i++)
         {
             ParameterProperty mapping = request.ParameterMap.GetProperty(i);
             if ((mapping.Direction == ParameterDirection.Output) || (mapping.Direction == ParameterDirection.InputOutput))
             {
                 string columnName = string.Empty;
                 if (!session.DataSource.DbProvider.UseParameterPrefixInParameter)
                 {
                     columnName = mapping.ColumnName;
                 }
                 else
                 {
                     columnName = session.DataSource.DbProvider.ParameterPrefix + mapping.ColumnName;
                 }
                 if (mapping.TypeHandler == null)
                 {
                     lock (mapping)
                     {
                         if (mapping.TypeHandler == null)
                         {
                             Type memberTypeForGetter = ObjectProbe.GetMemberTypeForGetter(result, mapping.PropertyName);
                             mapping.TypeHandler = request.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(memberTypeForGetter);
                         }
                     }
                 }
                 IDataParameter parameter     = (IDataParameter)command.Parameters[columnName];
                 object         obj2          = parameter.Value;
                 object         dataBaseValue = null;
                 if (obj2 == DBNull.Value)
                 {
                     if (mapping.HasNullValue)
                     {
                         dataBaseValue = mapping.TypeHandler.ValueOf(mapping.GetAccessor.MemberType, mapping.NullValue);
                     }
                     else
                     {
                         dataBaseValue = mapping.TypeHandler.NullValue;
                     }
                 }
                 else
                 {
                     dataBaseValue = mapping.TypeHandler.GetDataBaseValue(parameter.Value, result.GetType());
                 }
                 request.IsRowDataFound = request.IsRowDataFound || (dataBaseValue != null);
                 request.ParameterMap.SetOutputParameter(ref result, mapping, dataBaseValue);
             }
         }
     }
 }
示例#13
0
        public static IList <T> QueryForListWithPage <T>(this IMappedStatement mappedStatement, ISession session, object paramObject, string orderby, int willShowedPage, int pageSize, ref int totalCount)
        {
            IStatement statement = mappedStatement.Statement;
            //statement.
            RequestScope request      = statement.Sql.GetRequestScope(mappedStatement, paramObject, session);
            string       statementsql = request.PreparedStatement.PreparedSql;

            //难点2 改写自PetaPoco

            return(Page <T>(mappedStatement, request, session, willShowedPage, pageSize, statementsql, paramObject, ref totalCount));
        }
示例#14
0
        /// <summary>
        /// Build the PreparedStatement
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="sql">The SQL.</param>
        public void BuildPreparedStatement(ISession session, string sql)
        {
            //ISession对象是DataMapperSession类对象,其中包含了数据库的连接与事物类对象
            //statement则包含了sql语句字符串和参数类信息
            RequestScope request = new RequestScope(dataExchangeFactory, session, statement);
            //将分散的信息集中到PreparedStatementFactory中,其中sql参数是本次的数据库语句
            PreparedStatementFactory factory = new PreparedStatementFactory(session, dbHelperParameterCache, request, statement, sql);

            //获取PreparedStatement类
            preparedStatement = factory.Prepare(false);
        }
示例#15
0
        public TeamService(RequestScope scopeContext, ITeamRepository repository, ITeamPlayersService teamPlayerService,
                           IMatchRequestService matchRequestService,
                           IHttpContextAccessor httpContextAccessor)

            : base(scopeContext, repository)
        {
            _teamPlayerService   = teamPlayerService;
            _httpContextAccessor = httpContextAccessor;

            _matchRequestService = matchRequestService;
        }
示例#16
0
        public JsonResult Get(Guid id)
        {
            using (var rs = new RequestScope(this))
            {
                var task = rs.DC.Tasks.Single(l => l.Task_GUID == id);

                var taskModel = new TaskModel(rs.DC, task);

                return Json(taskModel, JsonRequestBehavior.AllowGet);
            }
        }
示例#17
0
        public RequestScope GetRequestScope(IMappedStatement mappedStatement, object parameterObject, ISqlMapSession session)
        {
            RequestScope request = new RequestScope(this._dataExchangeFactory, session, this._statement);

            this._paramParser = new InlineParameterMapParser();
            string sqlStatement = this.Process(request, parameterObject);

            request.PreparedStatement = this.BuildPreparedStatement(session, request, sqlStatement);
            request.MappedStatement   = mappedStatement;
            return(request);
        }
示例#18
0
        public void Dispose_EnsureDisposedInChildThread()
        {
            RequestScope scope = new RequestScope();

            scope.Dispose();

            Task.Run(
                () =>
            {
                Assert.Null(RequestScope.Current);
            }).GetAwaiter().GetResult();
        }
示例#19
0
        protected IDbCommand GetDbCommand(ISession session, IDataMapper dataMapper, string statementName,
                                          object parameterObject)
        {
            IMappedStatement statement =
                ((IModelStoreAccessor)dataMapper).ModelStore.GetMappedStatement(statementName);
            RequestScope request = statement.Statement.Sql.GetRequestScope(statement, parameterObject, session);

            statement.PreparedCommand.Create(request, session, statement.Statement, parameterObject);
            IDbCommand cmd = request.IDbCommand;

            return(cmd);
        }
        public void Execute(PostBindind postSelect, RequestScope request)
        {
            IList list  = postSelect.Statement.ExecuteQueryForList(request.Session, postSelect.Keys);
            Array array = Array.CreateInstance(postSelect.ResultProperty.SetAccessor.MemberType.GetElementType(), list.Count);
            int   count = list.Count;

            for (int i = 0; i < count; i++)
            {
                array.SetValue(list[i], i);
            }
            postSelect.ResultProperty.SetAccessor.Set(postSelect.Target, array);
        }
        /// <summary>
        /// Builds a new <see cref="RequestScope"/> and the sql command text to execute.
        /// </summary>
        /// <param name="parameterObject">The parameter object (used in DynamicSql)</param>
        /// <param name="session">The current session</param>
        /// <param name="mappedStatement">The <see cref="IMappedStatement"/>.</param>
        /// <returns>A new <see cref="RequestScope"/>.</returns>
        public RequestScope GetRequestScope(IMappedStatement mappedStatement,
                                            object parameterObject, ISqlMapSession session)
        {
            string sqlStatement = ProcessDynamicElements(parameterObject);

            RequestScope request = new RequestScope(_dataExchangeFactory, session, _statement);

            request.PreparedStatement = BuildPreparedStatement(session, request, sqlStatement);
            request.MappedStatement   = mappedStatement;

            return(request);
        }
示例#22
0
        /// <summary>
        /// Processes the specified <see cref="IDataReader"/>.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="reader">The reader.</param>
        /// <param name="resultObject">The result object.</param>
        /// <returns></returns>
        public object Process(RequestScope request, ref IDataReader reader, object resultObject)
        {
            object outObject = resultObject;

            IResultMap resultMap = request.CurrentResultMap.ResolveSubMap(reader);

            string circularKey = GetCircularKey(resultMap, reader);
            // Gets the [key, result object] already build
            IDictionary <string, object> buildObjects = request.GetCirularKeys(resultMap);

            if (buildObjects != null && buildObjects.ContainsKey(circularKey))
            {
                // circular key is already known, so get the existing result object
                outObject = buildObjects[circularKey];
            }
            else if (circularKey == null || buildObjects == null || !buildObjects.ContainsKey(circularKey))
            {
                // circular key is NOT known, so create a new result object.
                if (outObject == null)
                {
                    object[] parameters = null;
                    if (resultMap.Parameters.Count > 0)
                    {
                        parameters = new object[resultMap.Parameters.Count];
                        // Fill parameters array
                        for (int index = 0; index < resultMap.Parameters.Count; index++)
                        {
                            ResultProperty resultProperty = resultMap.Parameters[index];
                            parameters[index] = resultProperty.GetValue(request, ref reader, null);
                        }
                    }

                    outObject = resultMap.CreateInstanceOfResult(parameters);
                }

                // For each Property in the ResultMap, set the property in the object
                for (int index = 0; index < resultMap.Properties.Count; index++)
                {
                    ResultProperty resultProperty = resultMap.Properties[index];
                    resultProperty.PropertyStrategy.Set(request, resultMap, resultProperty, ref outObject, reader, null);
                }

                if (buildObjects == null)
                {
                    buildObjects = new Dictionary <string, object>();
                    request.SetCirularKeys(resultMap, buildObjects);
                }
                buildObjects[circularKey] = outObject;
            }

            return(outObject);
        }
示例#23
0
        /// <summary>
        /// Executes the SQL and retuns all rows selected in a map that is keyed on the property named
        /// in the keyProperty parameter.  The value at each key will be the value of the property specified
        /// in the valueProperty parameter.  If valueProperty is null, the entire result object will be entered.
        /// </summary>
        /// <param name="request">The request scope.</param>
        /// <param name="session">The session used to execute the statement</param>
        /// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
        /// <param name="keyProperty">The property of the result object to be used as the key.</param>
        /// <param name="valueProperty">The property of the result object to be used as the value (or null)</param>
        /// <param name="rowDelegate">A delegate called once per row in the QueryForMapWithRowDelegate method</param>
        /// <returns>A hashtable of object containing the rows keyed by keyProperty.</returns>
        ///<exception cref="DataMapperException">If a transaction is not in progress, or the database throws an exception.</exception>
        internal IDictionary RunQueryForMap(RequestScope request,
                                            ISession session,
                                            object parameterObject,
                                            string keyProperty,
                                            string valueProperty,
                                            DictionaryRowDelegate rowDelegate)
        {
            IDictionary map = new Hashtable();

            using (IDbCommand command = request.IDbCommand)
            {
                IDataReader reader = command.ExecuteReader();
                try
                {
                    if (rowDelegate == null)
                    {
                        while (reader.Read())
                        {
                            object obj   = resultStrategy.Process(request, ref reader, null);
                            object key   = ObjectProbe.GetMemberValue(obj, keyProperty, request.DataExchangeFactory.AccessorFactory);
                            object value = obj;
                            if (valueProperty != null)
                            {
                                value = ObjectProbe.GetMemberValue(obj, valueProperty, request.DataExchangeFactory.AccessorFactory);
                            }
                            map.Add(key, value);
                        }
                    }
                    else
                    {
                        while (reader.Read())
                        {
                            object obj   = resultStrategy.Process(request, ref reader, null);
                            object key   = ObjectProbe.GetMemberValue(obj, keyProperty, request.DataExchangeFactory.AccessorFactory);
                            object value = obj;
                            if (valueProperty != null)
                            {
                                value = ObjectProbe.GetMemberValue(obj, valueProperty, request.DataExchangeFactory.AccessorFactory);
                            }
                            rowDelegate(key, value, parameterObject, map);
                        }
                    }
                }
                finally
                {
                    reader.Close();
                    reader.Dispose();
                }
                ExecuteDelayedLoad(request);
            }
            return(map);
        }
        /// <summary>
        /// Processes the specified <see cref="IDataReader"/>
        /// when a 'resultClass' attribute is specified on the statement and
        /// the 'resultClass' attribute is a <see cref="DataTable"/>.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="reader">The reader.</param>
        /// <param name="resultObject">The result object.</param>
        public object Process(RequestScope request, ref IDataReader reader, object resultObject)
        {
            object outObject = resultObject;

            if (outObject == null)
            {
                outObject = new DataTable(request.Statement.Id);

                DataTable dataColumn = reader.GetSchemaTable();
                indexMapping = new int[2, dataColumn.Rows.Count];
                for (int i = 0, j = 0; i < dataColumn.Rows.Count; i++)
                {
                    indexMapping[0, i] = i;
                    indexMapping[1, i] = -1;

                    if (!((DataTable)outObject).Columns.Contains(dataColumn.Rows[i]["ColumnName"].ToString()))
                    {
                        ((DataTable)outObject).Columns.Add(dataColumn.Rows[i]["ColumnName"].ToString(),
                                                           (Type)dataColumn.Rows[i]["DataType"]);

                        indexMapping[1, i] = j++;
                    }
                }
            }

            DataRow dataRow = ((DataTable)outObject).NewRow();
            int     count   = reader.FieldCount;

            try
            {
                for (int i = 0; i < count; i++)
                {
                    //ResultProperty property = new ResultProperty();
                    //property.PropertyName = "value";
                    //property.ColumnIndex = i;
                    //property.TypeHandler = request.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(reader.GetFieldType(i));
                    //property.GetDataBaseValue(reader);
                    if (indexMapping[1, i] != -1)
                    {
                        dataRow[indexMapping[1, i]] = reader[indexMapping[0, i]] ?? DBNull.Value;
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine(e.Message + "\n" + e.StackTrace);
            }

            ((DataTable)outObject).Rows.Add(dataRow);

            return(outObject);
        }
示例#25
0
        /// <summary>
        /// Processes the specified <see cref="IDataReader"/>.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="reader">The reader.</param>
        /// <param name="resultObject">The result object.</param>
        /// <returns>The result object</returns>
        public object Process(RequestScope request, ref IDataReader reader, object resultObject)
        {
            object outObject = resultObject;

            IResultMap resultMap = request.CurrentResultMap.ResolveSubMap(reader);

            string uniqueKey = GetUniqueKey(resultMap, request, reader);
            // Gets the [key, result object] already build
            IDictionary buildObjects = request.GetUniqueKeys(resultMap);

            if (buildObjects != null && buildObjects.Contains(uniqueKey))
            {
                // Unique key is already known, so get the existing result object and process additional results.
                outObject = buildObjects[uniqueKey];
                // process resulMapping attribute wich point to a groupBy attribute
                for (int index = 0; index < resultMap.Properties.Count; index++)
                {
                    ResultProperty resultProperty = resultMap.Properties[index];
                    if (resultProperty.PropertyStrategy is PropertStrategy.GroupByStrategy)
                    {
                        resultProperty.PropertyStrategy.Set(request, resultMap, resultProperty, ref outObject, reader, null);
                    }
                }
                outObject = SKIP;
            }
            else if (uniqueKey == null || buildObjects == null || !buildObjects.Contains(uniqueKey))
            {
                // Unique key is NOT known, so create a new result object and process additional results.

                // Fix IBATISNET-241
                if (outObject == null)
                {
                    // temp ?, we don't support constructor tag with groupBy attribute
                    outObject = resultMap.CreateInstanceOfResult(null);
                }

                for (int index = 0; index < resultMap.Properties.Count; index++)
                {
                    ResultProperty resultProperty = resultMap.Properties[index];
                    resultProperty.PropertyStrategy.Set(request, resultMap, resultProperty, ref outObject, reader, null);
                }

                if (buildObjects == null)
                {
                    buildObjects = new Hashtable();
                    request.SetUniqueKeys(resultMap, buildObjects);
                }
                buildObjects[uniqueKey] = outObject;
            }

            return(outObject);
        }
示例#26
0
        public void Create_EnsureCurrent()
        {
            RequestScope scope = new RequestScope();

            try
            {
                Assert.Equal(RequestScope.Current, scope);
            }
            finally
            {
                scope.Dispose();
            }
        }
        public JsonResult Delete(Guid id)
        {
            using (var rs = new RequestScope(this))
            {
                var tasklog = rs.DC.TaskLogs.Single(tl => tl.TaskLog_GUID == id);

                rs.DC.TaskLogs.Remove(tasklog);

                rs.DC.SaveChanges();

                return Json("OK", JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult Faktors()
        {
            using (var rs = new RequestScope(this))
            {
                var faktors = rs.DC.Faktors.ToList().Select(it => new FaktorModel()
                {
                    Id = it.FAK_GUID,
                    Name = it.FAK_KortBeskrivelse
                }).OrderBy(x => x.Name).ToList();

                return Json(faktors, JsonRequestBehavior.AllowGet);
            }
        }
示例#29
0
        /// <summary>
        /// Processes the specified <see cref="IDataReader"/>.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="reader">The reader.</param>
        /// <param name="resultObject">The result object.</param>
        public object Process(RequestScope request, ref IDataReader reader, object resultObject)
        {
            IResultMap resultMap = request.CurrentResultMap.ResolveSubMap(reader);

            if (resultMap.GroupByPropertyNames.Count > 0)
            {
                return(_groupByStrategy.Process(request, ref reader, resultObject));
            }
            else
            {
                return(_resultMapStrategy.Process(request, ref reader, resultObject));
            }
        }
示例#30
0
        protected string GetSql(string statementName, object paramObject)
        {
            ISqlMapper       mapper    = GetLocalSqlMap();
            IMappedStatement statement = mapper.GetMappedStatement(statementName);

            if (!mapper.IsSessionStarted)
            {
                mapper.OpenConnection();
            }
            RequestScope scope = statement.Statement.Sql.GetRequestScope(statement, paramObject, mapper.LocalSession);

            return(scope.PreparedStatement.PreparedSql);
        }
示例#31
0
        /// <summary>
        /// Ensures all the related Execute methods are run in a consistent manner with pre and post events.
        /// </summary>
        /// <returns></returns>
        protected virtual T Execute <T>(object preEvent, object postEvent, ISession session, object parameterObject, Func <RequestScope, object, T> requestRunner)
        {
            object paramPreEvent = RaisePreEvent(preEvent, parameterObject);

            RequestScope request = statement.Sql.GetRequestScope(this, paramPreEvent, session);

            preparedCommand.Create(request, session, Statement, paramPreEvent);
            T result = requestRunner(request, paramPreEvent);

            RaiseExecuteEvent();

            return(RaisePostEvent(postEvent, paramPreEvent, result, false));
        }
示例#32
0
        private static DataTable DataTablePage(IMappedStatement mappedStatement, RequestScope request, ISession session, long page, long itemsPerPage, string sql, object paramObject, ref int totalCount)
        {
            string sqlCount, sqlPage;

            BuildPageQueries(mappedStatement, request, session, (page - 1) * itemsPerPage, itemsPerPage, sql, paramObject, out sqlCount, out sqlPage, ref totalCount, paramObject);

            request.PreparedStatement.PreparedSql = sqlPage;
            mappedStatement.PreparedCommand.Create(request, session, mappedStatement.Statement, paramObject);
            //难点三: 此处代码拷贝的MappedStatement的,就是增加了相关参数
            DataTable result = RunQueryForDataTable(mappedStatement.Statement, request, session, paramObject);

            return(result);
        }
示例#33
0
        ///<summary>
        /// Sets value of the specified <see cref="ResultProperty"/> on the target object
        /// when a 'select' attribute exists
        /// on the <see cref="ResultProperty"/> are empties.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="resultMap">The result map.</param>
        /// <param name="mapping">The ResultProperty.</param>
        /// <param name="target">The target.</param>
        /// <param name="reader">The reader.</param>
        /// <param name="selectKeys">The keys</param>
        public void Set(RequestScope request, IResultMap resultMap,
                        ResultProperty mapping, ref object target, IDataReader reader, object selectKeys)
        {
            string paramString = mapping.ColumnName;
            object keys        = null;
            bool   wasNull     = false;

            #region Finds the select keys.
            if (paramString.IndexOf(',') > 0 || paramString.IndexOf('=') > 0)         // composite parameters key
            {
                IDictionary keyMap = new Hashtable();
                keys = keyMap;
                // define which character is seperating fields
                char[] splitter = { '=', ',' };

                string[] paramTab = paramString.Split(splitter);
                if (paramTab.Length % 2 != 0)
                {
                    throw new DataMapperException("Invalid composite key string format in '" + mapping.PropertyName + ". It must be: property1=column1,property2=column2,...");
                }
                IEnumerator enumerator = paramTab.GetEnumerator();
                while (!wasNull && enumerator.MoveNext())
                {
                    string hashKey = ((string)enumerator.Current).Trim();
                    if (paramString.Contains("="))// old 1.x style multiple params
                    {
                        enumerator.MoveNext();
                    }
                    object hashValue = reader.GetValue(reader.GetOrdinal(((string)enumerator.Current).Trim()));

                    keyMap.Add(hashKey, hashValue);
                    wasNull = (hashValue == DBNull.Value);
                }
            }
            else             // single parameter key
            {
                keys    = reader.GetValue(reader.GetOrdinal(paramString));
                wasNull = reader.IsDBNull(reader.GetOrdinal(paramString));
            }
            #endregion

            if (wasNull)
            {
                // set the value of an object property to null
                mapping.SetAccessor.Set(target, null);
            }
            else             // Collection object or .Net object
            {
                _selectStrategy.Set(request, resultMap, mapping, ref target, reader, keys);
            }
        }
示例#34
0
        public virtual int ExecuteUpdate(ISqlMapSession session, object parameterObject)
        {
            int          num     = 0;
            RequestScope request = this._statement.Sql.GetRequestScope(this, parameterObject, session);

            this._preparedCommand.Create(request, session, this.Statement, parameterObject);
            using (IDbCommand command = request.IDbCommand)
            {
                num = command.ExecuteNonQuery();
                this.RetrieveOutputParameters(request, session, command, parameterObject);
            }
            this.RaiseExecuteEvent();
            return(num);
        }
示例#35
0
        public JsonResult Save(string data)
        {
            using (var rs = new RequestScope(this))
            {
                var taskModel = JsonConvert.DeserializeObject<TaskModel>(data);

                var task = rs.DC.Tasks.Single(l => l.Task_GUID == taskModel.Id);
                task.Task_IsClosed = taskModel.IsClosed ? (byte)1 : (byte)0;

                rs.DC.SaveChanges();

                return Json("OK");
            }
        }
示例#36
0
        private static void BuildPageQueries(IMappedStatement mappedStatement, RequestScope request, ISession session, long skip, long take, string sql, object args, out string sqlCount, out string sqlPage, ref int totalCount, object paramObject)
        {
            string dbType = session.SessionFactory.DataSource.DbProvider.Id.ToLower();

            // Split the SQL into the bits we need
            string sqlSelectRemoved, sqlOrderBy;

            if (!SplitSqlForPaging(sql, out sqlCount, out sqlSelectRemoved, out sqlOrderBy))
            {
                throw new Exception("Unable to parse SQL statement for paged query");
            }
            if (dbType.Contains("oracle") && sqlSelectRemoved.StartsWith("*"))
            {
                throw new Exception("Query must alias '*' when performing a paged query.\neg. select t.* from table t order by t.id");
            }

            //已经获取:查询数据总数SQL  分页SQL
            request.PreparedStatement.PreparedSql = sqlCount;
            mappedStatement.PreparedCommand.Create(request, session, mappedStatement.Statement, paramObject);
            totalCount = GetCount(request, session, sqlCount);


            if (skip >= totalCount)
            {
                skip = totalCount - take;
            }

            // Build the SQL for the actual final result
            if (dbType.Contains("sqlserver") || dbType.Contains("oracle"))
            {
                sqlSelectRemoved = rxOrderBy.Replace(sqlSelectRemoved, "");
                if (rxDistinct.IsMatch(sqlSelectRemoved))
                {
                    sqlSelectRemoved = "peta_inner.* FROM (SELECT " + sqlSelectRemoved + ") peta_inner";
                }
                sqlPage = string.Format("SELECT * FROM (SELECT  ROW_NUMBER() OVER ({0}) peta_rn,{1}) peta_paged WHERE peta_rn>{2} AND peta_rn<={3}",
                                        sqlOrderBy == null ? "ORDER BY (SELECT NULL)" : sqlOrderBy, sqlSelectRemoved, skip, skip + take);
                //args = args.Concat(new object[] { skip, skip + take }).ToArray();
            }
            else if (dbType.Contains("sqlserverce"))
            {
                sqlPage = string.Format("{0}\nOFFSET @{1} ROWS FETCH NEXT @{2} ROWS ONLY", sql, skip, skip + take);
                //args = args.Concat(new object[] { skip, take }).ToArray();
            }
            else
            {
                sqlPage = string.Format("{0}\nLIMIT @{1} OFFSET @{2}", sql, skip, skip + take);
                //args = args.Concat(new object[] { take, skip }).ToArray();
            }
        }
示例#37
0
 public PreparedStatement BuildPreparedStatement(ISqlMapSession session, RequestScope request, string commandText)
 {
     if (this._preparedStatement == null)
     {
         lock (this._synRoot)
         {
             if (this._preparedStatement == null)
             {
                 this._preparedStatement = new PreparedStatementFactory(session, request, this._statement, commandText).Prepare();
             }
         }
     }
     return(this._preparedStatement);
 }
示例#38
0
        public ActionResult Registration()
        {
            using (var rs = new RequestScope(this))
            {
                var registrationModel = new RegistrationViewModel()
                {
                    UserId = rs.Bruger.BrugerGuid,
                    InitialYear = DateTime.Today.Year,
                    InitialWeek = GetWeekNumber(DateTime.Today)
                };

                return View(registrationModel);
            }
        }
        /// <summary>
        /// Create an IDbCommand for the SqlMapSession and the current SQL Statement
        /// and fill IDbCommand IDataParameter's with the parameterObject.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="session">The SqlMapSession</param>
        /// <param name="statement">The IStatement</param>
        /// <param name="parameterObject">
        /// The parameter object that will fill the sql parameter
        /// </param>
        /// <returns>An IDbCommand with all the IDataParameter filled.</returns>
        public void Create(RequestScope request, ISqlMapSession session, IStatement statement, object parameterObject)
        {
            // the IDbConnection & the IDbTransaction are assign in the CreateCommand
            request.IDbCommand = new DbCommandDecorator(session.CreateCommand(statement.CommandType), request);

            request.IDbCommand.CommandText = request.PreparedStatement.PreparedSql;

            if (_logger.IsDebugEnabled)
            {
                _logger.Debug("Statement Id: [" + statement.Id + "] PreparedStatement : [" + request.IDbCommand.CommandText + "]");
            }

            ApplyParameterMap(session, request.IDbCommand, request, statement, parameterObject);
        }
示例#40
0
        public virtual object ExecuteInsert(ISqlMapSession session, object parameterObject)
        {
            object       memberValue = null;
            SelectKey    selectKey   = null;
            RequestScope request     = this._statement.Sql.GetRequestScope(this, parameterObject, session);

            if (this._statement is Insert)
            {
                selectKey = ((Insert)this._statement).SelectKey;
            }
            if ((selectKey != null) && !selectKey.isAfter)
            {
                memberValue = this._sqlMap.GetMappedStatement(selectKey.Id).ExecuteQueryForObject(session, parameterObject);
                ObjectProbe.SetMemberValue(parameterObject, selectKey.PropertyName, memberValue, request.DataExchangeFactory.ObjectFactory, request.DataExchangeFactory.AccessorFactory);
            }
            this._preparedCommand.Create(request, session, this.Statement, parameterObject);
            using (IDbCommand command = request.IDbCommand)
            {
                if (this._statement is Insert)
                {
                    command.ExecuteNonQuery();
                }
                else if (((this._statement is Procedure) && (this._statement.ResultClass != null)) && this._sqlMap.TypeHandlerFactory.IsSimpleType(this._statement.ResultClass))
                {
                    IDataParameter parameter = command.CreateParameter();
                    parameter.Direction = ParameterDirection.ReturnValue;
                    command.Parameters.Add(parameter);
                    command.ExecuteNonQuery();
                    memberValue = parameter.Value;
                    memberValue = this._sqlMap.TypeHandlerFactory.GetTypeHandler(this._statement.ResultClass).GetDataBaseValue(memberValue, this._statement.ResultClass);
                }
                else
                {
                    memberValue = command.ExecuteScalar();
                    if ((this._statement.ResultClass != null) && this._sqlMap.TypeHandlerFactory.IsSimpleType(this._statement.ResultClass))
                    {
                        memberValue = this._sqlMap.TypeHandlerFactory.GetTypeHandler(this._statement.ResultClass).GetDataBaseValue(memberValue, this._statement.ResultClass);
                    }
                }
                if ((selectKey != null) && selectKey.isAfter)
                {
                    memberValue = this._sqlMap.GetMappedStatement(selectKey.Id).ExecuteQueryForObject(session, parameterObject);
                    ObjectProbe.SetMemberValue(parameterObject, selectKey.PropertyName, memberValue, request.DataExchangeFactory.ObjectFactory, request.DataExchangeFactory.AccessorFactory);
                }
                this.RetrieveOutputParameters(request, session, command, parameterObject);
            }
            this.RaiseExecuteEvent();
            return(memberValue);
        }
 private Task <double> DoWithActivityAsync(double x, double y, Func <double, double, ICalculatorClientAsync, Task <double> > doAsync)
 {
     using (RequestScope scope = this.TraceStart())
     {
         try
         {
             return(this.TraceEnd(scope, doAsync(x, y, this.inner)));
         }
         catch (Exception e)
         {
             this.TraceError(e);
             throw;
         }
     }
 }
        public JsonResult FindContacts(Guid companyId, string query)
        {
            using (var rs = new RequestScope(this))
            {
                var q = rs.DC.Contacts.Where(k => k.Contact_CompanyGUID == companyId);

                if (query != ".")
                {
                    q = q.Where(k => k.Contact_Name.StartsWith(query));
                }

                var kontakter = q.Select(k => new ContactSelectionModel()
                {
                    Id = k.Contact_GUID,
                    Name = k.Contact_Name,
                    Title = k.Contact_Title
                }).ToList().OrderBy(c => c.Name);

                return Json(kontakter, JsonRequestBehavior.AllowGet);
            }
        }
        private KundeEditModel BuildEditModel(Kunder kunde, RequestScope rs)
        {
            var currentStandardFakturaTypeId = kunde.KundeExtensions.Any()
                ? kunde.KundeExtensions.Single().DefaultInvoiceTypeId ?? Guid.Empty
                : Guid.Empty;

            var kundeEditModel = new KundeEditModel()
            {
                Id = kunde.Kunde_GUID,
                Navn1 = kunde.Kunde_Navn_1,
                Navn2 = kunde.Kunde_Navn_2,
                StandardFakturaTypeId = currentStandardFakturaTypeId,
                IsSupportSiteEnabled = kunde.IsSupportSiteEnabled,
                FakturaTypeSelectList =
                    rs.DC.InvoiceTypes.Select(
                        t =>
                            new SelectListItem()
                            {
                                Selected = t.IT_GUID == currentStandardFakturaTypeId,
                                Text = t.IT_Name,
                                Value = t.IT_GUID.ToString()
                            }).ToList()
            };

            return kundeEditModel;
        }
        public JsonResult FindTasks(Guid? companyId, Guid? contactId, string query)
        {
            using (var rs = new RequestScope(this))
            {
                var tasksQuery = rs.DC.Tasks.Where(t => t.Task_IsClosed == 0).AsQueryable();

                if (companyId.HasValue)
                {
                    tasksQuery = tasksQuery.Where(t => t.Task_CompanyGUID == companyId.Value);
                }

                if (contactId.HasValue)
                {
                    tasksQuery = tasksQuery.Where(t => t.Task_ContactGUID == contactId.Value);
                }

                if (string.IsNullOrEmpty(query) == false && query != ".")
                {
                    tasksQuery = tasksQuery.Where(t => t.Task_Caption.Contains(query));
                }

                var result = tasksQuery.ToList().Select(k =>
                {
                    var newTaskSelection = new TaskSelectionModel(rs.DC, k);

                    return newTaskSelection;
                }).
                OrderBy(n => n.Name).ToList();

                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult New(Guid? optionalTaskId)
        {
            using (var rs = new RequestScope(this))
            {
                var newTaskLog = TaskRepository.CreateTaskLog(optionalTaskId, rs.DC, rs.Bruger.BrugerGuid, null);
                //newTaskLog.TaskLog_WebVisible = 1; // De ønsker ikke at de skal være web visible som standard

                rs.DC.TaskLogs.Add(newTaskLog);

                rs.DC.SaveChanges();

                var registrationModel = new RegistrationModel(rs.DC, newTaskLog);

                return Json(registrationModel, JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult Registration(Guid id)
        {
            using (var rs = new RequestScope(this))
            {
                var log = rs.DC.TaskLogs.Single(l => l.TaskLog_GUID == id);

                var registrationModel = new RegistrationModel(rs.DC, log);

                return Json(registrationModel, JsonRequestBehavior.AllowGet);
            }
        }
示例#47
0
		/// <summary>
		/// Build the PreparedStatement
		/// </summary>
		/// <param name="session"></param>
		/// <param name="request"></param>
		/// <param name="sqlStatement"></param>
		private PreparedStatement BuildPreparedStatement(ISqlMapSession session, RequestScope request, string sqlStatement)
		{
			PreparedStatementFactory factory = new PreparedStatementFactory( session, request, _statement, sqlStatement);
			return factory.Prepare();
		}
        public JsonResult Registrations(int year, int week)
        {
            using (var rs = new RequestScope(this))
            {
                var since = FirstDateOfWeekISO8601(year, week);

                var firstDayWeek = since.StartOfWeek(DayOfWeek.Monday);
                var firstDayOfNextWeek = firstDayWeek.AddDays(7);

                var logs = rs.DC.TaskLogs.
                    Where(tl =>
                        tl.TaskLog_StartDateTime >= firstDayWeek &&
                        tl.TaskLog_StartDateTime < firstDayOfNextWeek &&
                        tl.TaskLog_UserGUID == rs.Bruger.BrugerGuid).
                    ToList().
                    OrderByDescending(l => l.TaskLog_StartDateTime);

                var quickTasks = rs.DC.Tasks.Where(t =>
                    t.Task_IsClosed == 0 &&
                    t.Task_FromUserGUID == rs.Bruger.BrugerGuid
                ).ToList();

                // Sorter så dagens er øverst
                quickTasks = quickTasks
                    .OrderBy(t => t.Task_StartDate.HasValue ? t.Task_StartDate.Value.Date == DateTime.Today.Date ? 0 :1 : 1)
                    .ThenByDescending(td => td.Task_StartDate)
                .ToList();

                var registrationsModel = new RegistrationsModel()
                {
                    Registrations = logs.Select(l => new RegistrationModel(rs.DC, l)).ToList(),
                    QuickTasks = quickTasks.Select(qt => new RegistrationQuickTaskModel(rs.DC, qt)).ToList(),
                    WeekStartDate = firstDayWeek.AsJavascriptDate(),
                    WeekEndDate = firstDayOfNextWeek.AsJavascriptDate()
                };

                // Identificer dagens sidste (bruges til at beregne hvor separator skal være)
                var sidsteQuickTask =
                    registrationsModel.QuickTasks.LastOrDefault(t => t.IsToday == true);
                if (sidsteQuickTask != null)
                {
                    sidsteQuickTask.IsLastToday = true;
                }

                return Json(registrationsModel, JsonRequestBehavior.AllowGet);
            }
        }
示例#49
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="ctx"></param>
		/// <param name="parameterObject"></param>
		/// <param name="localChildren"></param>
		/// <param name="buffer"></param>
		private void ProcessBodyChildren(RequestScope request, SqlTagContext ctx, 
			object parameterObject, IEnumerator localChildren, StringBuilder buffer) 
		{
			while (localChildren.MoveNext()) 
			{
				ISqlChild child = (ISqlChild) localChildren.Current;

				if (child is SqlText) 
				{
					SqlText sqlText = (SqlText) child;
					string sqlStatement = sqlText.Text;
					if (sqlText.IsWhiteSpace) 
					{
						buffer.Append(sqlStatement);
					} 
					else 
					{
//						if (SimpleDynamicSql.IsSimpleDynamicSql(sqlStatement)) 
//						{
//							sqlStatement = new SimpleDynamicSql(sqlStatement, _statement).GetSql(parameterObject);
//							SqlText newSqlText = _paramParser.ParseInlineParameterMap( null, sqlStatement );
//							sqlStatement = newSqlText.Text;
//							ParameterProperty[] mappings = newSqlText.Parameters;
//							if (mappings != null) 
//							{
//								for (int i = 0; i < mappings.Length; i++) 
//								{
//									ctx.AddParameterMapping(mappings[i]);
//								}
//							}
//						}
						// BODY OUT
						buffer.Append(" ");
						buffer.Append(sqlStatement);

						ParameterProperty[] parameters = sqlText.Parameters;
						if (parameters != null) 
						{
							int length = parameters.Length;
							for (int i = 0; i< length; i++) 
							{
								ctx.AddParameterMapping(parameters[i]);
							}
						}
					}
				} 
				else if (child is SqlTag) 
				{
					SqlTag tag = (SqlTag) child;
					ISqlTagHandler handler = tag.Handler;
					int response = BaseTagHandler.INCLUDE_BODY;

					do 
					{
						StringBuilder body = new StringBuilder();

						response = handler.DoStartFragment(ctx, tag, parameterObject);
						if (response != BaseTagHandler.SKIP_BODY) 
						{
							if (ctx.IsOverridePrepend
								&& ctx.FirstNonDynamicTagWithPrepend == null
								&& tag.IsPrependAvailable
								&& !(tag.Handler is DynamicTagHandler)) 
							{
								ctx.FirstNonDynamicTagWithPrepend = tag;
							}

							ProcessBodyChildren(request, ctx, parameterObject, tag.GetChildrenEnumerator(), body);
            
							response = handler.DoEndFragment(ctx, tag, parameterObject, body);
							handler.DoPrepend(ctx, tag, parameterObject, body);
							if (response != BaseTagHandler.SKIP_BODY) 
							{
								if (body.Length > 0) 
								{
									// BODY OUT

									if (handler.IsPostParseRequired) 
									{
										SqlText sqlText = _paramParser.ParseInlineParameterMap(request, null, body.ToString() );
										buffer.Append(sqlText.Text);
										ParameterProperty[] mappings = sqlText.Parameters;
										if (mappings != null) 
										{
											int length = mappings.Length;
											for (int i = 0; i< length; i++) 
											{
												ctx.AddParameterMapping(mappings[i]);
											}
										}
									} 
									else 
									{
										buffer.Append(" ");
										buffer.Append(body.ToString());
									}
									if (tag.IsPrependAvailable && tag == ctx.FirstNonDynamicTagWithPrepend) 
									{
										ctx.IsOverridePrepend = false;
									}
								}
							}
						}
					} 
					while (response == BaseTagHandler.REPEAT_BODY);
				}
			}
		}
 private Task<double> TraceEnd(RequestScope scope, Task<double> task)
 {
     return task.ContinueWith<double>(this.AfterRequest, scope.Id, TaskContinuationOptions.ExecuteSynchronously);
 }
示例#51
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="ctx"></param>
		/// <param name="parameterObject"></param>
		/// <param name="localChildren"></param>
		private void ProcessBodyChildren(RequestScope request, SqlTagContext ctx, 
			object parameterObject, IList localChildren) 
		{
			StringBuilder buffer = ctx.GetWriter();
			ProcessBodyChildren(request, ctx, parameterObject, localChildren.GetEnumerator(), buffer);
		}
示例#52
0
		/// <summary>
		/// Builds a new <see cref="RequestScope"/> and the <see cref="IDbCommand"/> text to execute.
		/// </summary>
		/// <param name="parameterObject">The parameter object (used in DynamicSql)</param>
		/// <param name="session">The current session</param>
		/// <param name="mappedStatement">The <see cref="IMappedStatement"/>.</param>
		/// <returns>A new <see cref="RequestScope"/>.</returns>
		public RequestScope GetRequestScope(IMappedStatement mappedStatement, 
			object parameterObject, ISqlMapSession session)
		{ 
			RequestScope request = new RequestScope( _dataExchangeFactory, session, _statement);

			_paramParser = new InlineParameterMapParser();

			string sqlStatement = Process(request, parameterObject);
			request.PreparedStatement = BuildPreparedStatement(session, request, sqlStatement);
			request.MappedStatement = mappedStatement;

			return request;
		}
示例#53
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="parameterObject"></param>
		/// <returns></returns>
		private string Process(RequestScope request, object parameterObject) 
		{
			SqlTagContext ctx = new SqlTagContext();
			IList localChildren = _children;

			ProcessBodyChildren(request, ctx, parameterObject, localChildren);

			// Builds a 'dynamic' ParameterMap
            ParameterMap parameterMap = new ParameterMap(
                _statement.Id + "-InlineParameterMap",
                _statement.ParameterClass.FullName,
                string.Empty,
                _statement.ParameterClass,
                request.DataExchangeFactory.GetDataExchangeForClass(_statement.ParameterClass),
                _usePositionalParameters);

            //parameterMap.Id = _statement.Id + "-InlineParameterMap";
            //parameterMap.Initialize(_usePositionalParameters, request);
            //parameterMap.Class = _statement.ParameterClass;

			// Adds 'dynamic' ParameterProperty
			IList parameters = ctx.GetParameterMappings();
			int count = parameters.Count;
			for(int i=0;i<count;i++)
			{
                parameterMap.AddParameterProperty((ParameterProperty)parameters[i]);
			}
            request.ParameterMap = parameterMap;

			string dynSql = ctx.BodyText;

			// Processes $substitutions$ after DynamicSql
			if ( SimpleDynamicSql.IsSimpleDynamicSql(dynSql) ) 
			{
				dynSql = new SimpleDynamicSql(request, dynSql, _statement).GetSql(parameterObject);
			}
			return dynSql;
		}
        public JsonResult TasklogTypes()
        {
            using (var rs = new RequestScope(this))
            {
                var invoiceTypes = rs.DC.TaskLogTypes.ToList().Select(it => new InvoiceTypeModel()
                {
                    Id = it.TLT_GUID,
                    Name = it.TLT_Text
                }).OrderBy(x => x.Name).ToList();

                return Json(invoiceTypes, JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult Save(string data)
        {
            using (var rs = new RequestScope(this))
            {
                var registrationModel = JsonConvert.DeserializeObject<RegistrationModel>(data);

                var taskLog = rs.DC.TaskLogs.Single(l => l.TaskLog_GUID == registrationModel.Id);

                taskLog.TaskLog_ActivityTypeGUID = registrationModel.TaskLogTypeId;
                taskLog.TaskLog_BillKm = registrationModel.BillableKm;
                taskLog.TaskLog_BillTime = registrationModel.BillableTime;
                taskLog.TaskLog_CompanyGUID = registrationModel.SelectedCompany != null ? registrationModel.SelectedCompany.Id : new Guid?();
                taskLog.TaskLog_ContactGUID = registrationModel.SelectedContact != null ? registrationModel.SelectedContact.Id : new Guid?();
                taskLog.TaskLog_ExternalText = registrationModel.ExternalText.AsEol();
                taskLog.TaskLog_FactorGUID = registrationModel.FaktorId != Guid.Empty ? registrationModel.FaktorId : new Guid?();
                taskLog.TaskLog_InternalText = registrationModel.InternalText.AsEol();
                taskLog.TaskLog_InvoiceTypeGUID = registrationModel.InvoiceTypeId != Guid.Empty ? registrationModel.InvoiceTypeId : new Guid?();
                taskLog.TaskLog_NoBillKm = registrationModel.NonBillableKm;
                taskLog.TaskLog_NoBillTime = registrationModel.NonBillableTime;
                taskLog.TaskLog_StartDateTime = DateTime.Parse(registrationModel.StartDate);
                taskLog.TaskLog_EndDateTime = taskLog.TaskLog_StartDateTime.Value.AddMinutes(30);
                taskLog.TaskLog_TaskGUID = registrationModel.SelectedTask != null ? registrationModel.SelectedTask.Id : new Guid?();
                taskLog.TaskLog_UpdatedByUserDate = DateTime.Now;
                taskLog.TaskLog_UpdatedByUserGUID = rs.Bruger.BrugerGuid;

                rs.DC.SaveChanges();

                return Json("OK");
            }
        }
示例#56
0
		/// <summary>
		/// Build the PreparedStatement
		/// </summary>
		/// <param name="session"></param>
		/// <param name="commandText"></param>
		/// <param name="request"></param>
		public PreparedStatement BuildPreparedStatement(ISqlMapSession session, RequestScope request, string commandText)
		{
			if ( _preparedStatement == null )
			{
				lock(_synRoot)
				{
					if (_preparedStatement==null)
					{
						PreparedStatementFactory factory = new PreparedStatementFactory( session, request, _statement, commandText);
						_preparedStatement = factory.Prepare();
					}
				}
			}
			return _preparedStatement;
		}
示例#57
0
		/// <summary>
		/// Build the PreparedStatement
		/// </summary>
		/// <param name="session"></param>
		/// <param name="sqlStatement"></param>
		public void BuildPreparedStatement(ISqlMapSession session, string sqlStatement)
		{
			RequestScope request = new RequestScope( _dataExchangeFactory, session, _statement);

			PreparedStatementFactory factory = new PreparedStatementFactory( session, request, _statement, sqlStatement);
			_preparedStatement = factory.Prepare();
		}