Esempio n. 1
0
        public static bool Delete(this IOrmModel me, int PrimaryKeyValue)
        {
            //Note, this returns true if no row is found matching the key... bubble exception maybe from SQL?
            KeyValuePair <string, int?> _PrimaryKey = ReflectionHelper.PrimaryKey(me);
            /*Move donot use reflection unless error*/
            string _message = string.Format("Process {0} failed;", ReflectionHelper.GetProcessName(me));

            _message = string.Format("Process {0} failed; {1}={2}", ReflectionHelper.GetProcessName(me), _PrimaryKey.Key, _PrimaryKey.Value);
            try {
                using (SqlConnection cn = new SqlConnection(Connstring())) {
                    cn.Open();
                    SqlCommand cmd = new SqlCommand(me.OrmContext.Delete, cn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(new SqlParameter(_PrimaryKey.Key, SqlDbType.Int));
                    cmd.Parameters[_PrimaryKey.Key].Direction = ParameterDirection.InputOutput;
                    cmd.Parameters[_PrimaryKey.Key].Value     = PrimaryKeyValue;
                    cmd.Parameters.AddWithValue("delete", true);
                    cmd.ExecuteNonQuery();
                    cn.Close();
                }
                OrmCaching.ClearCacheForProcessType(me.GetType().FullName);
                return(true);
            }
            catch (SqlException ex) {
                //err.WriteError("SQL Exception: " + _message, GetProcessName(me), ex);
                throw;
            }
            catch (Exception ex) {
                //err.WriteError(_message, GetProcessName(me), ex);
            }
            return(false);
        }
        protected ActionResult Delete <T>(int?id, IOrmModel Item) where T : IOrmModel, new()
        {
            int?Pk = Item.PrimaryKey().Value ?? id;

            if (Pk != null && Pk > 0)
            {
                try {
                    var model = (IOrmModel) new T();
                    var item  = model.Get <T>((int)Pk);
                    try {
                        item.Delete();
                    } catch (Exception) {
                        return(new HttpStatusCodeResult(505, "Found but not deleted"));
                    }
                } catch (SqlException) {
                    return(new HttpStatusCodeResult(404, "Not Found"));
                } catch (Exception) {
                    return(new HttpStatusCodeResult(400, "Bad Request"));
                }

                return(new HttpStatusCodeResult(204, "No Content"));
            }
            else
            {
                return(new HttpStatusCodeResult(404, "Not Found"));
            }
        }
 static public bool CacheStatus(this IOrmModel me, string CacheName)
 {
     if (!Convert.ToBoolean(ConfigurationManager.AppSettings["caching"]))
     {
         return(Convert.ToBoolean(ConfigurationManager.AppSettings["caching"]));
     }
     if (HttpRuntime.Cache[CacheName] == null)
     {
         return(false);
     }
     return(true);
 }
        public static void SetProperty(this IOrmModel me, string Name, object Value)
        {
            string _message = string.Format("Set Property {0}={1} Dynamic Operation failed;", Name, Value);

            object[] SystemValue = { Value };
            try {
                me.GetType().InvokeMember(Name, System.Reflection.BindingFlags.SetProperty, Type.DefaultBinder, me, SystemValue);
            }
            catch (Exception ex) {
                //err.WriteError(_message, GetProcessName(me), ex);
            }
        }
Esempio n. 5
0
        public static IOrmModel Create(this IOrmModel me)
        {
            KeyValuePair <string, int?> _PrimaryKey = ReflectionHelper.PrimaryKey(me);

            /*Move donot use reflection unless error*/
            //string _message = string.Format("Process {0} failed;", ReflectionHelper.GetProcessName(me));
            //_message = string.Format("Process {0} failed; {1}={2}", ReflectionHelper.GetProcessName(me), _PrimaryKey.Key, _PrimaryKey.Value);
            try {
                using (SqlConnection cn = new SqlConnection(Connstring())) {
                    cn.Open();
                    SqlCommand cmd = new SqlCommand(me.OrmContext.Create, cn);
                    cmd.CommandType = CommandType.StoredProcedure;

                    foreach (DataAnnotationsModelMetadata field in ModelMetadataProviders.Current.GetMetadataForProperties(me, me.GetType()))
                    {
                        if (
                            field.AdditionalValues.Contains(new KeyValuePair <string, object>("ORM", true))
                            & !field.AdditionalValues.Contains(new KeyValuePair <string, object>("ORM_Update", false))
                            )
                        {
                            if (field.AdditionalValues.Contains(new KeyValuePair <string, object>("ORM_PrimaryKey", true)))
                            {
                                cmd.Parameters.Add(new SqlParameter(field.PropertyName, SqlDbType.Int));
                                cmd.Parameters[field.PropertyName].Direction = ParameterDirection.Output;
                            }
                            else
                            {
                                System.Reflection.PropertyInfo PropInfo = me.GetType().GetProperty(field.PropertyName);
                                object PropVal = PropInfo.GetValue(me, null);
                                cmd.Parameters.AddWithValue(field.PropertyName, PropVal);
                            }
                        }
                    }
                    cmd.ExecuteNonQuery();
                    ReflectionHelper.SetProperty(
                        me
                        , _PrimaryKey.Key
                        , cmd.Parameters[_PrimaryKey.Key].Value
                        );
                    cn.Close();
                }
                OrmCaching.ClearCacheForProcessType(me.GetType().FullName);
            }
            catch (SqlException ex) {
                // err.WriteError("SQL Exception: " + _message, GetProcessName(me), ex);
                throw;
            }
            catch (Exception ex) {
                // err.WriteError(_message, GetProcessName(me), ex);
            }
            return(me);
        }
Esempio n. 6
0
        //as a general rule of thumb, consider the parallel library as being faster on
        //recordsets of greater then 100 rows, don't use this for small datasets.
        public static List <T> GetInParallel <T>(this IOrmModel me) where T : IOrmModel, new()
        {
            string ProcessName         = ReflectionHelper.GetProcessName(me);
            string _message            = string.Format("Process {0} failed;", ProcessName);
            string _cacheName          = ProcessName;
            ConcurrentQueue <T> retval = new ConcurrentQueue <T>();

            object sync = new object();

            if (!me.CacheStatus(_cacheName))
            {
                try {
                    using (SqlConnection cn = new SqlConnection(Connstring())) {
                        cn.Open();
                        SqlCommand cmd = new SqlCommand(me.OrmContext.Read, cn);
                        cmd.CommandType = CommandType.StoredProcedure;
                        SqlDataReader r = cmd.ExecuteReader();

                        Parallel.ForEach(r.Cast <System.Data.Common.DbDataRecord>(), row => {
                            IOrmModel item = (IOrmModel) new T();
                            item.AutoMapFromDictionary(row.ToDataRow());
                            lock (sync) {
                                retval.Enqueue((T)item);
                            }
                        });
                        while (r.NextResult())
                        {
                            ;                   //get Error from SQL... Foobar..
                        }
                        cn.Close();
                    }
                    if (retval.Count > 0)
                    {
                        OrmCaching.SetCache(_cacheName, retval.ToList <T>());
                    }
                }
                catch (SqlException ex) {
                    // err.WriteError("SQL Exception: " + _message, GetProcessName(me), ex);
                    throw;
                }
                catch (Exception ex) {
                    // err.WriteError(_message, GetProcessName(me), ex);
                }
                return(retval.ToList <T>());
            }
            else
            {
                return((List <T>)OrmCaching.GetCache(_cacheName));
            }
        }
        protected JsonResult Update <T>(IOrmModel item)
        {
            int?Pk = item.PrimaryKey().Value;

            if (Pk != null && Pk > 0)
            {
                item.Update();
            }
            else
            {
                item.Create();
            }
            return(Json(item, JsonRequestBehavior.AllowGet));
        }
 public static string PrimaryKeyName(this IOrmModel me)
 {
     try {
         foreach (System.Web.Mvc.ModelMetadata field in System.Web.Mvc.ModelMetadataProviders.Current.GetMetadataForProperties(me, me.GetType()))
         {
             if (field.AdditionalValues.Contains(new KeyValuePair <string, object>("ORM_PrimaryKey", true)))
             {
                 return(field.PropertyName);
             }
         }
     }
     catch (Exception ex) {
     }
     return(string.Empty);
 }
Esempio n. 9
0
        public static List <T> GetCollection <T>(this IOrmModel me) where T : IOrmModel, new()
        {
            string   _message   = string.Format("Process {0} failed;", ReflectionHelper.GetProcessName(me));
            string   _cacheName = ReflectionHelper.GetProcessName(me);
            List <T> retval     = new List <T>();
            object   sync       = new object();

            if (!me.CacheStatus(_cacheName))
            {
                try {
                    using (SqlConnection cn = new SqlConnection(Connstring())) {
                        cn.Open();
                        SqlCommand cmd = new SqlCommand(me.OrmContext.Read, cn);
                        cmd.CommandType = CommandType.StoredProcedure;
                        SqlDataReader r = cmd.ExecuteReader();

                        while (r.Read())
                        {
                            Dictionary <string, object> row = r.ToDataRow();
                            IOrmModel item = (IOrmModel) new T();
                            item.AutoMapFromDictionary(row);
                            retval.Add((T)item);
                        }
                        while (r.NextResult())
                        {
                            ;                   //get Error... Foobar..
                        }
                        cn.Close();
                    }
                    if (retval.Count > 0)
                    {
                        OrmCaching.SetCache(_cacheName, me);
                    }
                }
                catch (SqlException ex) {
                    // err.WriteError("SQL Exception: " + _message, GetProcessName(me), ex);
                    throw;
                }
                catch (Exception ex) {
                    // err.WriteError(_message, GetProcessName(me), ex);
                }
                return(retval);
            }
            else
            {
                return((List <T>)OrmCaching.GetCache(_cacheName));
            }
        }
Esempio n. 10
0
        public static T Get <T> (this IOrmModel me, int id) where T : IOrmModel, new()
        {
            KeyValuePair <string, int?> _PrimaryKey = ReflectionHelper.PrimaryKey(me);
            string ProcessName = ReflectionHelper.GetProcessName(me);
            string _message    = string.Format("Process {0} failed;", ProcessName);

            _message = string.Format("Process {0} failed; {1}={2}", ProcessName, _PrimaryKey.Key, _PrimaryKey.Value);
            string _cacheName = string.Format("{0}/{1}", ProcessName, _PrimaryKey.Value);

            if (!me.CacheStatus(_cacheName))
            {
                try {
                    using (SqlConnection cn = new SqlConnection(Connstring())) {
                        cn.Open();
                        SqlCommand cmd = new SqlCommand(me.OrmContext.Read, cn);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue(_PrimaryKey.Key, id);
                        SqlDataReader r = cmd.ExecuteReader();
                        while (r.Read())
                        {
                            Dictionary <string, object> row = r.ToDataRow();
                            IOrmModel item = (IOrmModel) new T();
                            item.AutoMapFromDictionary(row);
                            OrmCaching.SetCache(_cacheName, item);
                            return((T)item);
                        }
                        while (r.NextResult())
                        {
                            ;                   //get Error... Foobar..
                        }
                        cn.Close();
                    }
                }
                catch (SqlException ex) {
                    // err.WriteError("SQL Exception: " + _message, GetProcessName(me), ex);
                    throw;
                }
                catch (Exception ex) {
                    // err.WriteError(_message, GetProcessName(me), ex);
                }
                return((T)me);
            }
            else
            {
                return((T)OrmCaching.GetCache(_cacheName));
            }
        }
Esempio n. 11
0
        public static List <T> Query <T>(this IOrmModel me) where T : IOrmModel, new()
        {
            /*Move donot use reflection unless error*/
            string   _message = string.Format("Process {0} failed;", ReflectionHelper.GetProcessName(me));
            List <T> retval   = new List <T>();

            try {
                using (SqlConnection cn = new SqlConnection(Connstring())) {
                    cn.Open();
                    SqlCommand cmd = new SqlCommand(me.OrmContext.Read, cn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    foreach (DataAnnotationsModelMetadata field in ModelMetadataProviders.Current.GetMetadataForProperties(me, me.GetType()))
                    {
                        if (field.AdditionalValues.Contains(new KeyValuePair <string, object>("ORM", true)))
                        {
                            object PropertyVal = ReflectionHelper.GetProperty(me, field.PropertyName);
                            if ((PropertyVal != null))
                            {
                                cmd.Parameters.AddWithValue(field.PropertyName, PropertyVal);
                            }
                        }
                    }
                    SqlDataReader r = cmd.ExecuteReader();
                    while (r.Read())
                    {
                        Dictionary <string, object> row = r.ToDataRow();
                        IOrmModel item = (IOrmModel) new T();
                        item.AutoMapFromDictionary(row);

                        retval.Add((T)item);
                    }
                    while (r.NextResult())
                    {
                        ;                   //get Error... Foobar..
                    }
                    cn.Close();
                }
            }
            catch (SqlException ex) {
                //err.WriteError("SQL Exception: " + _message, GetProcessName(me), ex);
                throw;
            }
            catch (Exception ex) {
                //err.WriteError(_message, GetProcessName(me), ex);
            }
            return(retval);
        }
Esempio n. 12
0
        static public void AutoMapFromDictionary(this IOrmModel me, Dictionary <string, object> row)
        {
            string _message = string.Format("Deserialize of object {0} Failed", me.ToString());

            try {
                foreach (KeyValuePair <string, object> Field in row)
                {
                    _message = string.Format("Deserialize/Cast of Object '{0}' Failed at Property '{1}' with Value '{2}'", me.ToString(), Field.Key, Field.Value);
                    System.Object[] intVal = { Field.Value };

                    me.GetType().InvokeMember(Field.Key, System.Reflection.BindingFlags.SetProperty, Type.DefaultBinder, me, intVal);
                }
            }
            catch (Exception ex) {
                //err.WriteError(_message, ProcessHelper.GetProcessName(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType), ex);
            }
        }
Esempio n. 13
0
        public static bool Delete(this IOrmModel me)
        {
            KeyValuePair <string, int?> _PrimaryKey = ReflectionHelper.PrimaryKey(me);
            /*Move donot use reflection unless error*/
            string _message = string.Format("Process {0} failed;", ReflectionHelper.GetProcessName(me));

            _message = string.Format("Process {0} failed; {1}={2}", ReflectionHelper.GetProcessName(me), _PrimaryKey.Key, _PrimaryKey.Value);
            try {
                Delete(me, (int)_PrimaryKey.Value);
                return(true);
            }
            catch (SqlException ex) {
                //err.WriteError("SQL Exception: " + _message, GetProcessName(me), ex);
                throw;
            }
            catch (Exception ex) {
                //err.WriteError(_message, GetProcessName(me), ex);
            }
            return(false);
        }
        public static KeyValuePair <string, int?> PrimaryKey(this IOrmModel me)
        {
            string _primaryKeyFieldName = string.Empty;
            int?   Id = 0;

            try {
                foreach (System.Web.Mvc.ModelMetadata field in System.Web.Mvc.ModelMetadataProviders.Current.GetMetadataForProperties(me, me.GetType()))
                {
                    if (field.AdditionalValues.Contains(new KeyValuePair <string, object>("ORM_PrimaryKey", true)))
                    {
                        _primaryKeyFieldName = field.PropertyName;
                        break; // TODO: might not be correct. Was : Exit For
                    }
                }
                System.Reflection.PropertyInfo _PrimaryKey = me.GetType().GetProperty(_primaryKeyFieldName);
                Id = (int?)_PrimaryKey.GetValue(me, null);
            }
            catch (Exception ex) {
            }
            return(new KeyValuePair <string, int?>(_primaryKeyFieldName, Id));
        }
Esempio n. 15
0
        //public static List<T> Query<T>(this IOrmModel me, params IEnumerable<dynamic> Constraints) where T : IOrmModel, new() {
        public static List <T> Query <T>(this IOrmModel me, params Parameter[] Constraints) where T : IOrmModel, new()
        {
            /*Move donot use reflection unless error*/
            string   _message = string.Format("Process {0} failed;", ReflectionHelper.GetProcessName(me));
            List <T> retval   = new List <T>();

            try {
                using (SqlConnection cn = new SqlConnection(Connstring())) {
                    cn.Open();
                    SqlCommand cmd = new SqlCommand(me.OrmContext.Read, cn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    foreach (Parameter Constraint in Constraints)
                    {
                        cmd.Parameters.AddWithValue(Constraint.Name, Constraint.Value);
                    }
                    SqlDataReader r = cmd.ExecuteReader();
                    while (r.Read())
                    {
                        Dictionary <string, object> row = r.ToDataRow();
                        IOrmModel item = (IOrmModel) new T();
                        item.AutoMapFromDictionary(row);
                        retval.Add((T)item);
                    }
                    while (r.NextResult())
                    {
                        ;                   //get Error... Foobar..
                    }
                    cn.Close();
                }
            }
            catch (SqlException ex) {
                //err.WriteError("SQL Exception: " + _message, GetProcessName(me), ex);
                throw;
            }
            catch (Exception ex) {
                //err.WriteError(_message, GetProcessName(me), ex);
            }
            return(retval);
        }
Esempio n. 16
0
 // POST Data/Products/Types
 public void Post([FromBody] IOrmModel model)
 {
     base.Post <Types>((IOrmModel)model);
 }
Esempio n. 17
0
 // PUT Data/Products/Proximity/1
 public void Put(int id, [FromBody] IOrmModel model)
 {
     base.Put <Proximity>(id, (IOrmModel)model);
 }
Esempio n. 18
0
 // POST Data/Products/Proximity
 public void Post([FromBody] IOrmModel model)
 {
     base.Post <Proximity>((IOrmModel)model);
 }
 public static object GetProperty(this IOrmModel me, string Name)
 {
     System.Reflection.PropertyInfo PropInfo = me.GetType().GetProperty(Name);
     return(PropInfo.GetValue(me, null));
 }
Esempio n. 20
0
 protected void Post <T>(IOrmModel model) where T : IOrmModel, new()
 {
     model.Create();
 }
Esempio n. 21
0
 // POST Data/Products/Pairings
 public void Post([FromBody] IOrmModel model)
 {
     base.Post <Pairings>((IOrmModel)model);
 }
Esempio n. 22
0
 // POST Data/Products/Ingredients
 public void Post([FromBody] IOrmModel model)
 {
     base.Post <Ingredients>((IOrmModel)model);
 }
Esempio n. 23
0
 // PUT Data/Products/Ingredients/1
 public void Put(int id, [FromBody] IOrmModel model)
 {
     base.Put <Ingredients>(id, (IOrmModel)model);
 }
        /// <summary>
        /// Returns the CacheStatus of the Cache by CacheName
        /// </summary>
        /// <remarks>
        /// Returns False, Meaning, do not utilize Caching.
        /// Return True, Meaning, Application is set to use Cache and Cache is not empty.
        /// </remarks>
        /*[Extension()]*/

        //application cache status, mostly for testing state of app.
        static public bool CacheStatus(this IOrmModel me)
        {
            return(Convert.ToBoolean(ConfigurationManager.AppSettings["caching"]));
        }
Esempio n. 25
0
 // PUT Data/Products/Pairings/1
 public void Put(int id, [FromBody] IOrmModel model)
 {
     base.Put <Pairings>(id, (IOrmModel)model);
 }
Esempio n. 26
0
        protected void Put <T>(int id, IOrmModel model) where T : IOrmModel, new()
        {
            int?Pk = model.PrimaryKey().Value;

            model.Update();
        }