public IActionResult Get()
        {
            using (OracleConnection conn = new OracleConnection(ConnStr.getConnStr()))
            {
                conn.ConnectionString = ConnStr.getConnStr();
                conn.Open();
                string        procedureName = "FUNC_GET_MESSAGE_NUMS";
                OracleCommand cmd           = new OracleCommand(procedureName, conn);
                cmd.CommandType = CommandType.StoredProcedure;
                OracleParameter p1 = new OracleParameter();
                p1           = cmd.Parameters.Add("state", OracleDbType.Int32);
                p1.Direction = ParameterDirection.ReturnValue;

                OracleParameter p2 = new OracleParameter();
                p2           = cmd.Parameters.Add("user_id", OracleDbType.Int32);
                p2.Direction = ParameterDirection.Input;
                p2.Value     = 8;

                OracleParameter p3 = new OracleParameter();
                p3           = cmd.Parameters.Add("search_result", OracleDbType.RefCursor);
                p3.Direction = ParameterDirection.Output;

                var reader = cmd.ExecuteReader();



                return(new JsonResult(p1.Value.ToString()));
            }
        }
        private void Initialize(bool isMasterDb = false)
        {
            try
            {
                string connString = ConnStr;
                if (ConnStr.Contains(DBNAME_PLACEHOLDER))
                {
                    Database.Connection.ConnectionString = connString.Replace(DBNAME_PLACEHOLDER, DatabaseName);
                }
                else
                {
                    Database.Connection.ConnectionString = connString;
                }

                if (isMasterDb)
                {
                    System.Data.Entity.Database.SetInitializer <RlmDbEntities>(null);
                }
                else
                {
                    System.Data.Entity.Database.SetInitializer <RlmDbEntities>(new RLMCreateDBIfNotExists());
                }
                //Database.SetInitializer<RnnDbEntities>(new MigrateDatabaseToLatestVersion<RnnDbEntities, Configuration>(true));
                //Database.SetInitializer<RnnDbEntities>(null);
                ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 0;
            }
            catch (Exception Ex)
            {
                System.Diagnostics.Debug.WriteLine(Ex.ToString());
                throw;
            }
        }
        public async Task <IActionResult> UploadAvatar([Required][FromForm] int user_id)
        {
            ////TODO 需要验证登录态
            ////返回成功与否
            //int userId = -1;
            //if (HttpContext.User.Identity.IsAuthenticated)
            //{
            //    //这里通过 HttpContext.User.Claims 可以将我们在Login这个Action中存储到cookie中的所有
            //    //claims键值对都读出来,比如我们刚才定义的UserName的值Wangdacui就在这里读取出来了
            //    userId = int.Parse(HttpContext.User.Claims.ElementAt(0).Value);
            //}
            //else
            //{
            //    //TODO
            //    //进入到这部分意味着用户登录态已经失效,需要返回给客户端信息,即需要登录。
            //    RestfulResult.RestfulData rr = new RestfulResult.RestfulData();
            //    rr.Code = 200;
            //    rr.Message = "Need Authentication";
            //    return new JsonResult(rr);
            //}

            using (OracleConnection conn = new OracleConnection(ConnStr.getConnStr()))
            {
                try
                {
                    conn.ConnectionString = ConnStr.getConnStr();
                    conn.Open();
                    RestfulResult.RestfulData rr = new RestfulResult.RestfulData();
                    rr.Code    = 200;
                    rr.Message = "success";

                    var imgfile   = Request.Form.Files[0];
                    int avatar_id = await addAvatarAndGetAvatarID(user_id);

                    Directory.CreateDirectory(@"wwwroot\avatars\" + user_id.ToString());

                    if (imgfile.Length > 0)
                    {
                        var img_path = @"wwwroot\avatars\" + user_id.ToString() + @"\" + avatar_id.ToString() + ".jpg";
                        using (var stream = new FileStream(img_path, FileMode.Create))
                        {
                            await imgfile.CopyToAsync(stream);
                        }
                    }
                    await ChangeAvatar(avatar_id);

                    return(new JsonResult(rr));
                }
                catch (Exception e)
                {
                    return(null);
                }
            }
        }
Exemple #4
0
        public object SelectAll()
        {
            List <PatientXref> ptInfo = null;

            using (var ct = new ContractEntities(ConnStr.GetConnectionStringEF(_contract)))
            {
                var query = Implementor.GetPatientXrefQuery(ct);

                ptInfo = query.ToList();
            }

            return(ptInfo);
        }
        public object SelectAll()
        {
            try
            {
                List <PatientNote> ptInfo = null;
                using (var ct = new ContractEntities(ConnStr.GetConnectionStringEF(_contract)))
                {
                    var query = Implementor.GetPatientNotesQuery(ct);
                    ptInfo = query.ToList();
                }

                return(ptInfo);
            }
            catch (Exception ex)
            {
                LoggerDomainEvent.Raise(LogStatus.Create("PatientsNotesRepository:SelectAll(): " + ex.Message, false));
                throw;
            }
        }
        public object SelectAll()
        {
            try
            {
                Dictionary <int, PatientInfo> ptInfo = null;
                using (var ct = new ContractEntities(ConnStr.GetConnectionStringEF(_contract)))
                {
                    var query = Implementor.GetPatientInfoQuery(ct);
                    ptInfo = query.ToDictionary(r => Convert.ToInt32(r.PatientId));
                }

                return(ptInfo);
            }
            catch (Exception ex)
            {
                LoggerDomainEvent.Raise(LogStatus.Create("PatientsContractRepository:SelectAll(): " + ex.Message, false));
                throw;
            }
        }
Exemple #7
0
        public object Insert(object list)
        {
            LoggerDomainEvent.Raise(LogStatus.Create("3) Register integrationpatientxrefs for patients...", true));
            try
            {
                var xrefList = (List <EIntegrationPatientXref>)list;

                using (var bcc = new SqlBulkCopy(ConnStr.GetConnectionString(_contract), SqlBulkCopyOptions.Default))
                {
                    using (var objRdr = ObjectReader.Create(xrefList))
                    {
                        try
                        {
                            bcc.BulkCopyTimeout = 580;
                            bcc.ColumnMappings.Add("SendingApplication", "SendingApplication");
                            bcc.ColumnMappings.Add("ExternalPatientID", "ExternalPatientID");
                            bcc.ColumnMappings.Add("PhytelPatientID", "PhytelPatientID");
                            bcc.ColumnMappings.Add("CreateDate", "CreateDate");
                            bcc.ColumnMappings.Add("UpdateDate", "UpdateDate");
                            bcc.ColumnMappings.Add("UpdatedBy", "UpdatedBy");
                            bcc.ColumnMappings.Add("ExternalDisplayPatientId", "ExternalDisplayPatientId");

                            bcc.DestinationTableName = "IntegrationPatientXref";
                            bcc.WriteToServer(objRdr);
                            LoggerDomainEvent.Raise(LogStatus.Create("3) Success", true));
                        }
                        catch (Exception ex)
                        {
                            Utils.FormatError(ex, bcc);
                        }
                    }
                }

                return(null);
            }
            catch (Exception ex)
            {
                throw new ArgumentException("XrefContractRepository:Insert(): " + ex.Message);
            }
        }
        public static async Task <string> getAvatarUrl(int user_id)
        {
            //FUNC_GET_USER_AVATAR(in_user_id in INTEGER, avatar_id out INTEGER)
            //return INTEGER
            OracleConnection conn = new OracleConnection(ConnStr.getConnStr());

            conn.ConnectionString = ConnStr.getConnStr();
            conn.Open();
            string        procedureName = "FUNC_GET_USER_AVATAR";
            OracleCommand cmd           = new OracleCommand(procedureName, conn);

            cmd.CommandType = CommandType.StoredProcedure;
            OracleParameter p1 = new OracleParameter();

            p1           = cmd.Parameters.Add("state", OracleDbType.Int32);
            p1.Direction = ParameterDirection.ReturnValue;

            OracleParameter p2 = new OracleParameter();

            p2           = cmd.Parameters.Add("in_user_id", OracleDbType.Int32);
            p2.Direction = ParameterDirection.Input;
            p2.Value     = user_id;

            OracleParameter p3 = new OracleParameter();

            p3           = cmd.Parameters.Add("avatar_id", OracleDbType.Int32);
            p3.Direction = ParameterDirection.Output;

            await cmd.ExecuteReaderAsync();

            if (int.Parse(p1.Value.ToString()) == 0)
            {
                conn.Close();
                return("http://localhost:12293/avatars/0.jpg");
            }
            conn.Close();
            return("http://localhost:12293/avatars/" + user_id.ToString() + "/" + int.Parse(p3.Value.ToString()).ToString() + ".jpg");
        }
Exemple #9
0
        /// <summary>
        /// 获取数据库连接串中涉及的数据库名,通过database关键字获取
        /// </summary>
        /// <returns></returns>
        public string GetDBName()
        {
            try
            {
                var ary = ConnStr.ToLower().Trim().Split(';');

                foreach (var item in ary)
                {
                    if (item.Contains("database"))
                    {
                        if (item.IndexOf('=') > -1)
                        {
                            return(item.Split('=')[1]);
                        }
                    }
                }
                return(null);
            }
            catch
            {
                return(null);
            }
        }
Exemple #10
0
 /// <summary>
 /// 初始化
 /// </summary>
 /// <param name="connStr">链接字符串</param>
 public void Init(string connStr = null)
 {
     // 如果初始化参数为空,使用默认参数
     if (!string.IsNullOrEmpty(connStr))
     {
         if (ConnStr.Contains(";"))
         {
             var m = ToLink(connStr);
             ConnStr = string.Format("{0}@{1}:{2}", m.Password, m.Server, m.Port);
             if (long.TryParse(m.Database, out var db))
             {
                 DB = db;
             }
         }
         else
         {
             ConnStr = connStr;
         }
     }
     conn = new PooledRedisClientManager(10000, 10, new string[] { ConnStr })
     {
         ConnectTimeout = 1200000 // 1000 * 60 * 20
     };
 }
        static public async Task <AtInfos[]> SearchAtsInTwitter(string content)
        {
            System.Text.RegularExpressions.Regex           atRegex      = new System.Text.RegularExpressions.Regex(@"@\w+");
            System.Text.RegularExpressions.MatchCollection atCollection = atRegex.Matches(content);
            AtInfos[] atInfos = new AtInfos[atCollection.Count];
            for (int i = 0; i < atCollection.Count; i++)
            {
                AtInfos at = new AtInfos();
                at.atName  = atCollection[i].ToString();
                atInfos[i] = at;
            }
            if (atInfos.Count() == 0)
            {
                return(atInfos);
            }

            using (OracleConnection conn = new OracleConnection(ConnStr.getConnStr()))
            {
                try
                {
                    conn.ConnectionString = ConnStr.getConnStr();
                    conn.Open();

                    foreach (AtInfos temp_at in atInfos)
                    {
                        string at = temp_at.atName.Replace("@", "");
                        //对于ats列表里的每一个话题,分别作为函数参数来执行一次FUNC_AT_USER函数

                        //FUNC_GET_USER_ID_BY_NAME(Searchkey in VARCHAR2, Search_Result out INTEGER)
                        //return INTEGER
                        string        procedureName2 = "FUNC_GET_USER_ID_BY_NAME";
                        OracleCommand cmd2           = new OracleCommand(procedureName2, conn);
                        cmd2.CommandType = CommandType.StoredProcedure;

                        //Add return value
                        OracleParameter p5 = new OracleParameter();
                        p5           = cmd2.Parameters.Add("state", OracleDbType.Int32);
                        p5.Direction = ParameterDirection.ReturnValue;

                        //Add first parameter Searchkey
                        OracleParameter p6 = new OracleParameter();
                        p6           = cmd2.Parameters.Add("Searchkey", OracleDbType.Varchar2);
                        p6.Direction = ParameterDirection.Input;
                        p6.Value     = at;

                        //Add second parameter Search_Result
                        OracleParameter p7 = new OracleParameter();
                        p7           = cmd2.Parameters.Add("Search_Result", OracleDbType.Int32);
                        p7.Direction = ParameterDirection.Output;

                        await cmd2.ExecuteReaderAsync();

                        if (int.Parse(p5.Value.ToString()) == 0)
                        {
                            throw new Exception("failed");
                        }
                        temp_at.atIds = int.Parse(p7.Value.ToString());
                    }
                }
                catch (Exception e)
                {
                    conn.Close();
                    RestfulResult.RestfulData rr = new RestfulResult.RestfulData(500, "fail");
                    Console.Write(e.Message);
                    Console.Write(e.StackTrace);
                    return(new AtInfos[] { });
                }
                conn.Close();
            }

            return(atInfos);
        }
        static public async Task <TopicInfos[]> SearchTopicsInTwitter(string content)
        {
            System.Text.RegularExpressions.Regex           topicRegex      = new System.Text.RegularExpressions.Regex(@"#\w+#");
            System.Text.RegularExpressions.MatchCollection topicCollection = topicRegex.Matches(content);
            TopicInfos[] topicInfos = new TopicInfos[topicCollection.Count];
            for (int i = 0; i < topicCollection.Count; i++)
            {
                TopicInfos topic = new TopicInfos();
                topic.topicName = topicCollection[i].ToString();
                topicInfos[i]   = topic;
            }
            if (topicInfos.Count() == 0)
            {
                return(topicInfos);
            }

            using (OracleConnection conn = new OracleConnection(ConnStr.getConnStr()))
            {
                try
                {
                    conn.ConnectionString = ConnStr.getConnStr();
                    conn.Open();

                    foreach (TopicInfos temp_topic in topicInfos)
                    {
                        string topic = temp_topic.topicName.Replace("#", "");

                        //FUNC_GET_TOPIC_ID_BY_NAME(Searchkey in VARCHAR2, Search_Result out INTEGER)
                        //return INTEGER
                        string        procedureName2 = "FUNC_GET_TOPIC_ID_BY_NAME";
                        OracleCommand cmd2           = new OracleCommand(procedureName2, conn);
                        cmd2.CommandType = CommandType.StoredProcedure;

                        //Add return value
                        OracleParameter p4 = new OracleParameter();
                        p4           = cmd2.Parameters.Add("state", OracleDbType.Int32);
                        p4.Direction = ParameterDirection.ReturnValue;

                        //Add first parameter Searchkey
                        OracleParameter p5 = new OracleParameter();
                        p5           = cmd2.Parameters.Add("Searchkey", OracleDbType.Varchar2);
                        p5.Direction = ParameterDirection.Input;
                        p5.Value     = topic;

                        //Add second parameter Search_Result
                        OracleParameter p6 = new OracleParameter();
                        p6           = cmd2.Parameters.Add("Search_Result", OracleDbType.Int32);
                        p6.Direction = ParameterDirection.Output;

                        await cmd2.ExecuteReaderAsync();

                        if (int.Parse(p4.Value.ToString()) == 0)
                        {
                            throw new Exception("failed");
                        }
                        temp_topic.topicId = int.Parse(p6.Value.ToString());
                    }
                }
                catch (Exception e)
                {
                    RestfulResult.RestfulData rr = new RestfulResult.RestfulData(500, "fail");
                    Console.Write(e.Message);
                    Console.Write(e.StackTrace);
                    return(new TopicInfos[] { });
                }
            }

            return(topicInfos);
        }
Exemple #13
0
        public async Task <IActionResult> Send([Required][FromForm] MessageForSender message)
        {
            //TODO 需要验证身份
            //有很多参数都是有初始化的
            //!!!!!与Topic的联动
            //首先要检查message中是否有两个#号括起来的连续无空格字符串
            //若有,则去数据库中检索该Topic是否存在,若不存在则添加,若存在则将其热度提高

            int           userId;
            List <string> topics = new List <string>();
            List <string> ats    = new List <string>();

            System.Text.RegularExpressions.Regex topicRegex = new System.Text.RegularExpressions.Regex(@"#(\w+)#");
            System.Text.RegularExpressions.Regex atRegex    = new System.Text.RegularExpressions.Regex(@"@(\w+)");

            if (HttpContext.User.Identity.IsAuthenticated)
            {
                userId = int.Parse(HttpContext.User.Claims.First().Value);

                //检查message_content里含有的话题,用两个#包含的内容作为话题。若出现两个连续的#,则忽略之。
                //所有的话题内容会被保存到topics列表内,并在调用第二个函数FUNC_ADD_TOPIC时,逐一对topic的内容进行处理(不存在则创建,存在则热度+1)
                //对艾特内容同理
                System.Text.RegularExpressions.MatchCollection topicCollection = topicRegex.Matches(message.message_content);
                System.Text.RegularExpressions.MatchCollection atCollection    = atRegex.Matches(message.message_content);
                for (int i = 0; i < topicCollection.Count; i++)
                {
                    topics.Add(topicCollection[i].Groups[1].ToString());
                }
                for (int i = 0; i < atCollection.Count; i++)
                {
                    ats.Add(atCollection[i].Groups[1].ToString());
                }
            }
            else
            {
                RestfulResult.RestfulData rr = new RestfulResult.RestfulData();
                rr.Code    = 200;
                rr.Message = "Need Authentication";
                return(new JsonResult(rr));
            }

            using (OracleConnection conn = new OracleConnection(ConnStr.getConnStr()))
            {
                try
                {
                    conn.ConnectionString = ConnStr.getConnStr();
                    conn.Open();
                    //FUNC_SEND_MESSAGE(message_content in VARCHAR2, message_has_image in INTEGER, user_id in INTEGER, message_image_count in INTEGER, message_id out INTEGER)
                    //return INTEGER
                    string        procedureName = "FUNC_SEND_MESSAGE";
                    OracleCommand cmd           = new OracleCommand(procedureName, conn);
                    cmd.CommandType = CommandType.StoredProcedure;

                    //Add return value
                    OracleParameter p1 = new OracleParameter();
                    p1           = cmd.Parameters.Add("state", OracleDbType.Int32);
                    p1.Direction = ParameterDirection.ReturnValue;

                    //Add first parameter message_content
                    OracleParameter p2 = new OracleParameter();
                    p2           = cmd.Parameters.Add("message_content", OracleDbType.Varchar2);
                    p2.Direction = ParameterDirection.Input;
                    p2.Value     = message.message_content;

                    //Add second parameter message_has_image
                    OracleParameter p3 = new OracleParameter();
                    p3           = cmd.Parameters.Add("message_has_image", OracleDbType.Int32);
                    p3.Direction = ParameterDirection.Input;
                    p3.Value     = message.message_has_image;

                    //Add third parameter user_id
                    OracleParameter p4 = new OracleParameter();
                    p4           = cmd.Parameters.Add("user_id", OracleDbType.Int32);
                    p4.Direction = ParameterDirection.Input;
                    p4.Value     = userId;

                    //Add fourth parameter message_image_count
                    OracleParameter p5 = new OracleParameter();
                    p5           = cmd.Parameters.Add("message_image_count", OracleDbType.Int32);
                    p5.Direction = ParameterDirection.Input;
                    p5.Value     = message.message_image_count;

                    //Add fifth parameter message_id
                    OracleParameter p6 = new OracleParameter();
                    p6           = cmd.Parameters.Add("message_id", OracleDbType.Int32);
                    p6.Direction = ParameterDirection.Output;

                    await cmd.ExecuteReaderAsync();

                    if (int.Parse(p1.Value.ToString()) == 0)
                    {
                        throw new Exception("failed");
                    }

                    await TopicController.AddTopicsInTwitter(message.message_content, int.Parse(p6.Value.ToString()));

                    await AtController.AddAtsInTwitter(message.message_content, int.Parse(p6.Value.ToString()), userId);

                    //若推特含图,从POST体内获得图的内容并保存到服务器
                    if (message.message_has_image == 1)
                    {
                        var images  = Request.Form.Files;
                        int img_num = 0;
                        Directory.CreateDirectory(@"wwwroot\Messages\" + p6.Value.ToString());
                        foreach (var imgfile in images)
                        {
                            if (imgfile.Length > 0)
                            {
                                string img_path;
                                if (imgfile.ContentType.Substring(0, 5) == "image")
                                {
                                    img_path = @"wwwroot\Messages\" + p6.Value.ToString() + @"\" + img_num.ToString() + ".jpg";
                                }
                                else
                                {
                                    string videoFormat = imgfile.ContentType.Split("/")[1];
                                    img_path = @"wwwroot\Messages\" + p6.Value.ToString() + @"\" + img_num.ToString() + "." + videoFormat;
                                }
                                using (var stream = new FileStream(img_path, FileMode.Create))
                                {
                                    await imgfile.CopyToAsync(stream);
                                }
                                img_num++;
                            }
                        }
                    }

                    RestfulResult.RestfulData rr = new RestfulResult.RestfulData(200, "success");
                    conn.Close();
                    return(new JsonResult(rr));
                }
                catch (Exception e)
                {
                    RestfulResult.RestfulData rr = new RestfulResult.RestfulData(500, "fail");
                    Console.Write(e.Message);
                    Console.Write(e.StackTrace);
                    conn.Close();
                    return(new JsonResult(rr));
                }
            }
        }
Exemple #14
0
        //public ProductList Product_Details()
        public AllProductDetails Product_Details()
        {
            AllProductDetails objallProductDet = new AllProductDetails();
            SqlConnection     connection       = _context.GetConnection();

            try
            {
                string  SqlString = "getHomeimage";
                DataSet ds        = ConnStr.GetDataSet(SqlString);

                if (ds != null && ds.Tables.Count > 0)
                {
                    DataTable         dtHomePage = ds.Tables[0];
                    List <HomeImages> lstHome    = new List <HomeImages>();

                    #region HomeImages -- Start

                    HomeImages              objHome             = new HomeImages();
                    HomeImageDetails        objHomeImageDetails = new HomeImageDetails();
                    List <HomeImageDetails> lstHomeImageDetails = new List <HomeImageDetails>();

                    if (dtHomePage.Rows.Count > 0)
                    {
                        List <DataTable> dts = GetGroupByDatables(dtHomePage, "Section");
                        if (dts != null)
                        {
                            if (dts.Count > 0)
                            {
                                foreach (DataTable dtHome in dts)
                                {
                                    objHome             = new HomeImages();
                                    lstHomeImageDetails = new List <HomeImageDetails>();
                                    objHome.Section     = Convert.ToInt32(dtHome.Rows[0]["Section"]);
                                    foreach (DataRow dr in dtHome.Rows)
                                    {
                                        objHomeImageDetails           = new HomeImageDetails();
                                        objHomeImageDetails.ImageName = Convert.ToString(dr["ImageName"]);
                                        objHomeImageDetails.ImagePath = Convert.ToString(dr["ImagePath"]);

                                        lstHomeImageDetails.Add(objHomeImageDetails);
                                        objHome.HomeImageDetails = lstHomeImageDetails;
                                    }
                                    lstHome.Add(objHome);
                                }
                            }
                        }
                        #endregion HomeImages -- End

                        #region Category Detail -- Start

                        CategoryName        objcategoryName = new CategoryName();
                        List <CategoryName> lstCategoryName = new List <CategoryName>();

                        SubCategoryName        objsubCategoryName = new SubCategoryName();
                        List <SubCategoryName> lstSubCategoryName = new List <SubCategoryName>();

                        ProductName        objProductName = new ProductName();
                        List <ProductName> lstProductName = new List <ProductName>();

                        DataTable dtCatgory     = ds.Tables[1];
                        DataTable dtSubCatgory  = ds.Tables[2];
                        DataTable dtProductName = ds.Tables[3];

                        if (dtCatgory != null)
                        {
                            if (dtCatgory.Rows.Count > 0)
                            {
                                foreach (DataRow drCat in dtCatgory.Rows)
                                {
                                    objcategoryName         = new CategoryName();
                                    objcategoryName.CatName = Convert.ToString(drCat["CName"]);

                                    int CatID = Convert.ToInt32(drCat["CID"]);

                                    if (dtSubCatgory != null)
                                    {
                                        if (dtSubCatgory.Rows.Count > 0)
                                        {
                                            DataRow[] SubCatrows = dtSubCatgory.Select("CatID = " + CatID);
                                            if (SubCatrows != null)
                                            {
                                                if (SubCatrows.Length > 0)
                                                {
                                                    foreach (DataRow drSubCat in SubCatrows)
                                                    {
                                                        //lstSubCategoryName = new List<SubCategoryName>();

                                                        objsubCategoryName            = new SubCategoryName();
                                                        objsubCategoryName.SubCatName = Convert.ToString(drSubCat["SubCatName"]);

                                                        int SubCatID = Convert.ToInt32(drSubCat["SubCatID"]);

                                                        if (dtProductName != null)
                                                        {
                                                            if (dtProductName.Rows.Count > 0)
                                                            {
                                                                DataRow[] Productsrows = dtProductName.Select("SubCatID = " + SubCatID);

                                                                if (Productsrows != null)
                                                                {
                                                                    if (Productsrows.Length > 0)
                                                                    {
                                                                        foreach (DataRow drProduct in Productsrows)
                                                                        {
                                                                            objProductName       = new ProductName();
                                                                            objProductName.PName = Convert.ToString(drProduct["PName"]);
                                                                            objProductName.PID   = Convert.ToInt32(drProduct["PID"]);

                                                                            lstProductName.Add(objProductName);
                                                                        }
                                                                        objsubCategoryName.ProductName = lstProductName;

                                                                        lstProductName = new List <ProductName>();

                                                                        lstSubCategoryName.Add(objsubCategoryName);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }

                                                    objcategoryName.SubCategoryNames = lstSubCategoryName;
                                                    lstCategoryName.Add(objcategoryName);

                                                    lstSubCategoryName = new List <SubCategoryName>();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }


                        objallProductDet.CategoryNames = lstCategoryName;
                        objallProductDet.HomeImages    = lstHome;
                    }

                    #endregion Category Detail -- End
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                }
            }
            return(objallProductDet);
        }
Exemple #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            _services = services;
            ServiceInjection.Register(new List <Assembly>()
            {
                Assembly.GetExecutingAssembly()
            });
            services.AddServiceInjection();
            ConnStr = Configuration.GetConnectionString("DataContext");
#if TEST
            ConnStr = ConnStr.Replace("{envConfig}", ".Test");
#else
            ConnStr = ConnStr.Replace("{envConfig}", "");
#endif

            services.AddDbContext <DataContext>(options =>
                                                options.UseSqlServer(ConnStr).UseLazyLoadingProxies());
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            });
            Data.Global.Init(services);
            Business.Global.Init(services);
            #region OAuth
            services.AddIdentityCore <AppUser>(options =>
            {
                options.SignIn.RequireConfirmedEmail = false;
            }).AddRoles <AppRole>()
            .AddDefaultTokenProviders()
            .AddSignInManager()
            .AddEntityFrameworkStores <DataContext>();
            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequiredUniqueChars    = 0;

                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;

                options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = false;
            });
            //required
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = Business.Constants.JWT.ISSUER,
                    ValidAudience    = Business.Constants.JWT.AUDIENCE,
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.Default.GetBytes(Business.Constants.JWT.SECRET_KEY)),
                    ClockSkew = TimeSpan.Zero
                };
                //jwtBearerOptions.Events = new JwtBearerEvents
                //{
                //    OnMessageReceived = (context) =>
                //    {
                //        StringValues values;
                //        if (!context.Request.Query.TryGetValue("access_token", out values))
                //            return Task.CompletedTask;
                //        var token = values.FirstOrDefault();
                //        context.Token = token;
                //        return Task.CompletedTask;
                //    }
                //};
            });
            services.AddAuthorization(options =>
            {
                options.AddPolicy(Constants.Policy.And.APP_CLIENT, policy =>
                                  policy.Requirements.Add(new AppClientRequirement(isOR: false)));
                options.AddPolicy(Constants.Policy.Or.APP_CLIENT, policy =>
                                  policy.Requirements.Add(new AppClientRequirement(isOR: true)));

                options.AddPolicy(Constants.Policy.And.AUTH_USER, policy =>
                                  policy.Requirements.Add(new AuthUserRequirement(isOR: false)));
                options.AddPolicy(Constants.Policy.Or.AUTH_USER, policy =>
                                  policy.Requirements.Add(new AuthUserRequirement(isOR: true)));

                options.AddPolicy(Constants.Policy.And.ADMIN_USER, policy =>
                                  policy.Requirements.Add(new AuthUserRequirement(isOR: false, role: Data.Constants.RoleName.ADMIN)));
                options.AddPolicy(Constants.Policy.Or.ADMIN_USER, policy =>
                                  policy.Requirements.Add(new AuthUserRequirement(isOR: true, role: Data.Constants.RoleName.ADMIN)));
            });
            services.AddScoped <IAuthorizationHandler, AppClientAuthHandler>();
            services.AddScoped <IAuthorizationHandler, AuthUserAuthHandler>();
            #endregion
            services.AddSingleton(new DefaultDateTimeModelBinder());
            services.AddControllers(options =>
            {
                options.ModelBinderProviders.Insert(0, new QueryObjectModelBinderProvider());
            }).AddNewtonsoftJson();
            services.AddSwaggerGenNewtonsoftSupport();
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version        = "v1",
                    Title          = "My API",
                    Description    = "A simple example ASP.NET Core Web API",
                    TermsOfService = new Uri("https://example.com/terms"),
                });

                c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme,
                                        new OpenApiSecurityScheme
                {
                    In          = ParameterLocation.Header,
                    Description = "Please enter into field the word 'Bearer' following by space and JWT",
                    Name        = "Authorization",
                    Type        = SecuritySchemeType.ApiKey
                });

                var requirement = new OpenApiSecurityRequirement();
                requirement[new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType.SecurityScheme,
                                    Id = JwtBearerDefaults.AuthenticationScheme
                                }
                            }] = new string[] { };
                c.AddSecurityRequirement(requirement);
            });
        }
Exemple #16
0
 public SqlDBService(ConnStr conStr)
 {
     conn = new SqlConnection($"Data Source={conStr.DataSource};Initial Catalog={conStr.InitialCatalog};User ID={conStr.UserId};Password={conStr.Password};");
 }
Exemple #17
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            DateTime dt = System.IO.File.GetLastWriteTime(System.Reflection.Assembly.GetEntryAssembly().Location);

            string AboutText = "";

            AboutText      += "Приложение: " + Application.ProductName + "\r\n";
            AboutText      += "Версия: " + Application.ProductVersion + "\r\n";
            AboutText      += "Дата: " + dt.ToString("dd.MM.yyyy HH:mm") + "\r\n";
            AboutText      += "Пользователь: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name + "\r\n";
            labelAbout.Text = AboutText;

            ListViewGroup Assemb      = new ListViewGroup("Сборки");
            ListViewGroup Connect     = new ListViewGroup("Подключения");
            ListViewGroup Developers  = new ListViewGroup("Разработчики");
            ListViewGroup Consultants = new ListViewGroup("Консультанты");

            listViewAbout.Groups.Add(Assemb);
            listViewAbout.Groups.Add(Connect);
            listViewAbout.Groups.Add(Developers);
            listViewAbout.Groups.Add(Consultants);

            foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                AssemblyName asName = asm.GetName();
                ListViewItem l      = new ListViewItem(new string[] { asName.Name, asName.Version.ToString() });
                l.Group = Assemb;
                listViewAbout.Items.Add(l);
            }

            foreach (string ConnStr in DA.Global.Connections.Keys)
            {
                ListViewItem l = new ListViewItem(ConnStr.Split(':'));
                l.Group = Connect;
                listViewAbout.Items.Add(l);
            }
            {
                ListViewItem l = null;
                //l = new ListViewItem("А. Бугаев");
                //l.Group = Developers;
                //listViewAbout.Items.Add(l);

                //l = new ListViewItem("И. Кишик");
                //l.Group = Developers;
                //listViewAbout.Items.Add(l);

                l       = new ListViewItem("Л. Медведев");
                l.Group = Developers;
                listViewAbout.Items.Add(l);

                //l = new ListViewItem("А. Корнейчук");
                //l.Group = Developers;
                //listViewAbout.Items.Add(l);

                //l = new ListViewItem("К. Волынкин");
                //l.Group = Consultants;
                //listViewAbout.Items.Add(l);
            }

            this.Opacity = 0.0;
            this.Activate();
            this.Refresh();
            fadeTimer.Start();
        }