コード例 #1
1
ファイル: MockContext.cs プロジェクト: LeoLcy/cnblogsbywojilu
        public static MvcContext GetOne( IMember objOwner )
        {
            MvcContext ctx = getContextInit();

            // route
            Route route = new wojilu.Web.Mvc.Routes.Route();
            ctx.utils.setRoute( route );

            // viewer: 某些地方需要判断viewer
            ViewerContext viewer = new ViewerContext();
            viewer.obj = new User();
            ctx.utils.setViewerContext( viewer );

            // owner
            OwnerContext owner = new OwnerContext();
            owner.Id = objOwner.Id;
            owner.obj = objOwner;
            ctx.utils.setOwnerContext( owner );

            // app
            IAppContext app = new AppContext();
            app.obj = null;
            ctx.utils.setAppContext( app );

            return ctx;
        }
コード例 #2
1
ファイル: MockContext.cs プロジェクト: LeoLcy/cnblogsbywojilu
        public static MvcContext GetOne( IMember objOwner, Type appType, int appId )
        {
            MvcContext ctx = getContextInit();

            // route
            Route route = new wojilu.Web.Mvc.Routes.Route();
            route.setAppId( appId ); // 为了让生成的link链接中有appId,必须设置此项
            ctx.utils.setRoute( route );

            // viewer: 某些地方需要判断viewer
            ViewerContext viewer = new ViewerContext();
            viewer.obj = new User();
            ctx.utils.setViewerContext( viewer );

            // owner
            OwnerContext owner = new OwnerContext();
            owner.Id = objOwner.Id;
            owner.obj = objOwner;
            ctx.utils.setOwnerContext( owner );

            // app
            IAppContext app = new AppContext();
            app.Id = appId;
            app.obj = ndb.findById( appType, appId );
            app.setAppType( appType ); // 如果要使用alang语言包,必须设置此项
            ctx.utils.setAppContext( app );

            return ctx;
        }
コード例 #3
0
ファイル: AppContext.cs プロジェクト: Bruhankovi4/Emotyper
        public AppContext(string filepath)
        {
            Context = this;
            if (Settings.Default.RecentFileList == null)
            {
                Settings.Default.RecentFileList = new StringCollection();
                Settings.Default.Save();
            }

            var diagramForm = new DiagramForm();

            MainForm = diagramForm;
            diagramForm.Show();
            if (string.IsNullOrEmpty(filepath))
            {
                LoadLastFile(diagramForm);
            }
            else
            {
                try
                {
                    diagramForm.OpenFileByPath(filepath);
                }
                catch (Exception exception)
                {
                    MessageBox.Show(string.Format("{0}:{1}{2}", DesignerResources.FileCouldntBeOpened, Environment.NewLine, exception.Message), DesignerResources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            diagramForm.Focus();
        }
コード例 #4
0
        public ReportLogoControl()
        {
            InitializeComponent();

            _db = new AppContext();
            _settingRepository = new ReportSettingRepository(_db);
        }
コード例 #5
0
ファイル: MockContext.cs プロジェクト: LeoLcy/cnblogsbywojilu
        public static MvcContext GetOne( IMember objOwner, int appId )
        {
            IWebContext webContext = MockWebContext.New( 1, "http://localhost/", new System.IO.StringWriter() );

            MvcContext ctx = new MvcContext( webContext );

            // route
            Route route = new wojilu.Web.Mvc.Routes.Route();
            route.setAppId( appId ); // 为了让生成的link链接中有appId,必须设置此项
            ctx.utils.setRoute( route );

            // viewer: 某些地方需要判断viewer
            ViewerContext viewer = new ViewerContext();
            viewer.obj = new User();
            ctx.utils.setViewerContext( viewer );

            // owner
            OwnerContext owner = new OwnerContext();
            owner.Id = objOwner.Id;
            owner.obj = objOwner;
            ctx.utils.setOwnerContext( owner );

            // app
            IAppContext app = new AppContext();
            app.Id = appId;
            app.obj = BlogApp.findById( appId );
            app.setAppType( typeof( BlogApp ) ); // 如果要使用alang语言包,必须设置此项
            ctx.utils.setAppContext( app );

            return ctx;
        }
コード例 #6
0
ファイル: FileReaderForm.cs プロジェクト: shoaib-ijaz/geosoft
 public FileReaderForm()
 {
     _db = new AppContext();
     _preferenceRepository = new AppPreferencesRepository(_db);
     rangeList = _preferenceRepository.GetFieldRangeList();
     InitializeComponent();
 }
コード例 #7
0
 public ManageCustomersForm()
 {
     InitializeComponent();
     _db = new AppContext();
     _customerRepository = new CustomerRepository(_db);
     _searchCustomer = new Repository.Models.Customer();
 }
コード例 #8
0
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            int length = 5;

            using (var db = new AppContext())
            {
                for (int index = 0; index < length; index++)
                {
                    Paymessage message = new Paymessage();
                    message.id = index + 1;
                    message.error = "None";
                    message.state = "initial";
                    if (index == 0)
                        message.EventId = new Guid("8b265223-dc9e-4789-a6df-69d19f644ad7");
                    else if (index == 1)
                        message.EventId = new Guid("3721ba5d-4733-4d98-a5e2-8e8afa3e61f4");
                    else if (index == 2)
                        message.EventId = new Guid("1ac188ec-4b2e-436c-b989-db88c65db1fa");
                    else if (index == 3)
                        message.EventId = new Guid("9bf180fa-f8f4-4b2b-8fac-cca73a4e2cab");
                    else if (index == 4)
                        message.EventId = new Guid("ee2c56f7-6d42-4314-bce5-4825ed294437");
                    db.Paymessages.Add(message);
                    db.SaveChanges();
                }
            }
        }
コード例 #9
0
 public bool Authenticate(String username, String password)
 {
     using (var ctx = new AppContext())
     {
         return ctx.Users.Any(u => u.Username == username && u.Password == password);
     }
 }
コード例 #10
0
ファイル: Program.cs プロジェクト: buzakovpa/ccpublic
        public static int Main(string[] args)
        {
            const string outputPath = @"C:\Users\buzakovpa\YandexDisk\databases\oil-screens";
            var inputPath = @"C:\Users\buzakovpa\YandexDisk\databases\oil-result\";

            using (var context = new AppContext()) {
                var import = new MakesImport(context);

                var files = Directory
                    .GetFiles(outputPath, "*.json", SearchOption.AllDirectories)
                    .ToList();

                files.ForEach(
                    a => {
                        var fn = Path.GetFileName(a);

                        var file0Info = new FileInfo(a);

                        var file1Info = new FileInfo(inputPath + fn);

                        if (File.Exists(inputPath + fn) && file0Info.Length != file1Info.Length) {
                            inputPath += new Random().Next(100000, 999999);
                        }
                        File.Move(a, inputPath + fn);
                    });
            }
            return 0;
        }
コード例 #11
0
ファイル: UserPageTests.cs プロジェクト: rocketeerbkw/DNA
        public void Setup()
        {
            using (FullInputContext inputcontext = new FullInputContext(""))
            {
                _appContext = new AppContext(TestConfig.GetConfig().GetRipleyServerPath());
                _siteOptionList = new SiteOptionList();
                _siteOptionList.CreateFromDatabase(inputcontext.ReaderCreator, inputcontext.dnaDiagnostics);
            }
            
            DnaTestURLRequest request = new DnaTestURLRequest("haveyoursay");
            request.SetCurrentUserNormal();
            IInputContext inputContext = DnaMockery.CreateDatabaseInputContext();
            using (IDnaDataReader dataReader = inputContext.CreateDnaDataReader(""))
            {
                SetSiteID(dataReader, "h2g2");

                _includeContentFromOtherSites = _siteOptionList.GetValueBool(_siteId, "PersonalSpace", "IncludeContentFromOtherSites");

                //Create a post on h2g2
                SetForumID(dataReader);
                request = new DnaTestURLRequest("h2g2");
                request.SetCurrentUserNormal();
                int id = request.CurrentUserID;
                request.RequestPage("AddThread?subject=test&body=blahblah&post=1&skin=purexml&forum=" + Convert.ToString(_forumId));

                //Create a post on have your say.
                SetSiteID(dataReader, "haveyoursay");
                SetForumID(dataReader);
                request = new DnaTestURLRequest("haveyoursay");
                request.SetCurrentUserNormal();
                request.RequestPage("AddThread?subject=test&body=blahblah&post=1&skin=purexml&forum=" + Convert.ToString(_forumId));
            }
        }
コード例 #12
0
 public ManageCustomerFarmsForm()
 {
     InitializeComponent();
     _db = new AppContext();
     _customerRepository = new CustomerRepository(_db);
     _farmRepository = new CustomerFarmRepository(_db);
 }
コード例 #13
0
ファイル: Connection.cs プロジェクト: shoaib-ijaz/geosoft
        public static bool CreateDatabse()
        {
            try
            {
                if (!Directory.Exists(DatabaseDirectory))
                {
                    Directory.CreateDirectory(DatabaseDirectory);
                }

                AppContext db = new AppContext();
                db.Database.CreateIfNotExists();

                if (db.Database.Exists())
                {
                    Database.SetInitializer<AppContext>(new AppContextInitializer());
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: scrato/IDD_Test
 public void Start()
 {
     AppContext app = new AppContext();
     app.AddObject<IMessageOutput>(this);
     _comm = new CommunicationStarter(app);
     _comm.Connect();
 }
コード例 #15
0
		/// <summary>
		/// Shows control
		/// </summary>
		/// <param name="context"></param>
		public override void ShowControl(AppContext context)
		{
			base.ShowControl(context);
			if (!IsInitialized)
			{
				ComponentConfigElement element = context.ScopeNode.Tag as ComponentConfigElement;
				if (element != null)
				{
					txtApplication.Text = element.GetStringSetting("ApplicationName");
					txtComponent.Text = element.GetStringSetting("ComponentName");
					txtVersion.Text = element.GetStringSetting("Release");
					lblDescription.Text = element.GetStringSetting("ComponentDescription");

					string installer = element.GetStringSetting("Installer");
					string path = element.GetStringSetting("InstallerPath");
					string type = element.GetStringSetting("InstallerType");
					if ( string.IsNullOrEmpty(installer) ||
						string.IsNullOrEmpty(path) || 
						string.IsNullOrEmpty(type))
					{
						btnRemove.Enabled = false;
						btnSettings.Enabled = false;
					}
				}
				IsInitialized = true;
			}
		}
コード例 #16
0
        public IgnoreFieldsControl()
        {
            _db = new AppContext();
            _preferenceRepository = new AppPreferencesRepository(_db);

            InitializeComponent();
        }
コード例 #17
0
        public ActionResult GetAvatar(int size)
        {
            string uid = Session["currentUserId"].ToString();
            AccountModel user = null;
            byte[] avatar = null;

            using (var db = new AppContext())
            {
                user = db.Accounts.Where(a => a.WeiboId == uid).ToList().First();
            }

            using (var client = new WebClient())
            {
                switch (size)
                {
                    case 50:
                        avatar = client.DownloadData(user.Avatar50Url);
                        break;
                    case 180:
                    default:
                        avatar = client.DownloadData(user.Avatar180Url);
                        break;
                }
            }

            return File(avatar, "image/jpeg");
        }
コード例 #18
0
        public RangeRulesControl()
        {
            _db = new AppContext();
            _preferenceRepository = new AppPreferencesRepository(_db);

            InitializeComponent();
        }
コード例 #19
0
 public IAppContext CreateContext()
 {
     var ctx = new AppContext();
     ctx.AppTypeName = GetType().Name;
     ctx.Parent = Context;
     return ctx;
 }
コード例 #20
0
        public bool AuthenticateUser(string username, string password, UserTypeEnum userType)
        {
            LoggedUser = null;
            UserType = null;

            AppContext ctx = new AppContext();

            switch (userType)
            {
                case UserTypeEnum.Administrator:
                    AdministratorRepository adminRepo = new AdministratorRepository(new AppContext());
                    LoggedUser = unitOfWork.AdminRepository.GetByUsername(username);
                    break;
                case UserTypeEnum.Student:
                    StudentRepository studentRepo = new StudentRepository(new AppContext());
                    LoggedUser = unitOfWork.StudentRepository.GetByUsername(username);
                    break;
                case UserTypeEnum.Teacher:
                    TeacherRepository teacherRepo = new TeacherRepository(new AppContext());
                    LoggedUser = unitOfWork.TeacherRepository.GetByUsername(username);
                    break;
            }

            if (LoggedUser != null)
            {
                if (PasswordHasher.Equals(password, LoggedUser.Salt, LoggedUser.Hash))
                {
                    UserType = userType;
                    return true;
                }
                LoggedUser = null;
            }

            return false;
        }
コード例 #21
0
ファイル: Startup.cs プロジェクト: RoelofSol/DeOps
        public DeOpsMutex(AppContext context, string[] args)
        {
            try
            {
                string name = "DeOps" + Application.ProductVersion;

                TheMutex = new Mutex(true, name, out First);

                string objectName = "SingleInstanceProxy";
                string objectUri = "ipc://" + name + "/" + objectName;

                if (First)
                {
                    IpcChannel = new IpcServerChannel(name);
                    ChannelServices.RegisterChannel(IpcChannel, false);
                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(IpcObject), objectName, WellKnownObjectMode.Singleton);

                    IpcObject obj = new IpcObject();
                    obj.NewInstance += context.SecondInstanceStarted;

                    RemotingServices.Marshal(obj, objectName);
                }

                else
                {
                    IpcChannel = new IpcClientChannel();
                    ChannelServices.RegisterChannel(IpcChannel, false);

                    IpcObject obj = Activator.GetObject(typeof(IpcObject), objectUri) as IpcObject;

                    obj.SignalNewInstance(args);
                }
            }
            catch { }
        }
コード例 #22
0
        protected void Application_Start()
        {
            try
            {

                //Read the application mode
                //Remember to set it to Production before release!
                Application["ApplicationMode"] = Enum.Parse(typeof(ApplicationMode), ConfigurationManager.AppSettings["ApplicationMode"]);

                //Recreate database with test data if model changes
                if (ApplicationState.Mode == ApplicationMode.Development)
                {
                    Database.SetInitializer<AppContext>(new AppDbInitializer());
                    //Force recreation of model
                    using (var db = new AppContext())
                    {
                        db.Users.FirstOrDefault();
                    }
                }
                //Inicialización de entidades que siempre debe ocurrir
                var initService = new InitializationService();
                initService.Init();

                AreaRegistration.RegisterAllAreas();

                RegisterGlobalFilters(GlobalFilters.Filters);
                RegisterRoutes(RouteTable.Routes);
            }
            catch (Exception ex)
            {

                //TODO: Handle and log start exceptions
                throw ex;
            }
        }
コード例 #23
0
 public ApplicationBase()
 {
     var ctx = new AppContext();
     ctx.AppTypeName = GetType().FullName;
     OriginalContext = ctx;
     Context = ctx;
 }
コード例 #24
0
ファイル: ReportForm.cs プロジェクト: shoaib-ijaz/geosoft
        public ReportForm()
        {
            _db = new AppContext();
            _fieldRepository = new InterpolatedFieldRepository(_db);

            InitializeComponent();
        }
コード例 #25
0
        public async Task<ActionResult> Login(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var appContext = new AppContext();
            var user = await appContext.Users.Find(x => x.Email == model.Email).SingleOrDefaultAsync();
            if (user == null)
            {
                ModelState.AddModelError("Email", "Email address has not been registered.");
                return View(model);
            }

            var claims = new[]
                {
                    new Claim(ClaimTypes.Name, user.Name),
                    new Claim(ClaimTypes.Email, user.Email)
                };
            var identity = new ClaimsIdentity(claims, "ApplicationCookie");

            var context = Request.GetOwinContext();
            var authManager = context.Authentication;

            authManager.SignIn(identity);

            return Redirect(GetRedirectUrl(model.ReturnUrl));
        }
コード例 #26
0
        private static void PersonAddresses(int? skip = 0, int? takecount = 0)
        {
            var startTime = DateTime.Now;
            var w = FluentConsole.Instance;
            var db = new ACDBContext();
            var count = 0;
            var savedCount = 0;
            if (takecount == 0) takecount = db.AddressPersonRels.Count();
            var entityName = "Person-Address";

            w.White.Line($"Creating {takecount} {entityName}s");
            using (var context = new AppContext())
            {
                foreach (var item in db.AddressPersonRels.OrderBy(x => x.Id).Skip(skip ?? 0).Take(takecount ?? 0))
                {
                    count++;
                    var person = context.Persons.Include("PersonAddresses").FirstOrDefault(x => x.Id == item.CommonPerson.Id);
                    if (person == null)
                    {
                        w.Red.Line($"Error {entityName} {count} of {takecount}: {entityName} not found");
                        continue;
                    }
                    //todo: verify query
                    if (person.PersonAddresses.Any(
                        x => x.Street == item.Address.Address1?.Trim() &&
                             x.City == item.Address.City?.Trim() &&
                             x.StateId == item.Address.StateId &&
                             x.PrimaryStatus == (PrimaryStatus)item.PrimaryStatusId))
                    {
                        w.Yellow.Line($"Warning {entityName} {count} of {takecount}: {entityName} {person.ReverseFullName}-{item.Address.Address1} already exists");
                        continue;
                    }
                    person.PersonAddresses.Add(new PersonAddress()
                    {
                        Street = item.Address.Address1?.Trim(),
                        Street2 = item.Address.Address2?.Trim(),
                        City = item.Address.City?.Trim(),
                        County = item.Address.County?.Trim(),
                        StateId = item.Address.StateId,
                        ZipCode = $"{item.Address.Zip5?.Trim()}-{item.Address.Zip4?.Trim()}",
                        Country = item.Address.Country?.Trim(),
                        Latitude = item.Address.Latitude,
                        Longitude = item.Address.Longitude,
                        PrimaryStatus = (PrimaryStatus)item.PrimaryStatusId,
                        DateCreated = item.DateCreated,
                        DateUpdated = item.DateModified
                    });
                    person.LogEntries.Add(new PersonLogEntry() { Note = $"Added Address {item.Address.Address1}" });
                    w.Green.Line($"Adding {count} of {takecount} {entityName}: {person.ReverseFullName}-{item.Address.Address1}");
                    savedCount++;
                    context.SaveChanges();
                }
                w.Gray.Line($"Saving {entityName}s...");
                context.SaveChanges();

                var totalTime = DateTime.Now - startTime;
                w.Green.Line($"Saved {savedCount} {entityName}s in {totalTime.Hours}:{totalTime.Minutes}:{totalTime.Seconds} ");
            }
        }
コード例 #27
0
ファイル: Loader.cs プロジェクト: jordan49/websitepanel
		public Loader(AppContext context, string localFile, string componentCode, string version )	: this()
		{
			this.appContext = context;
			this.localFile = localFile;
			this.componentCode = componentCode;
			this.version = version;
			Start();
		}
コード例 #28
0
 public void Create(string username, string password)
 {
     using (var ctx = new AppContext())
     {
         ctx.Users.Add(new User { Id = 123123123, Username = username, Password = password });
         ctx.SaveChanges();
     }
 }
コード例 #29
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            ApplicationContext appcontext = new AppContext();
            Application.Run(appcontext);
        }
コード例 #30
0
ファイル: Program.cs プロジェクト: zeved/ycnotify
 static void Main()
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);    
     mf = new mainForm();
     checker = new Checker();
     ac = new AppContext();
     Application.Run(ac);
 }
コード例 #31
0
 public Repository(AppContext context)
 {
     this._context = context ?? throw new ArgumentNullException(nameof(context));
     _dbSet        = this._context.Set <TEntity>();
 }
コード例 #32
0
 public EditModel(AppContext context)
 {
     _context = context;
 }
コード例 #33
0
ファイル: SubdivisionRepository.cs プロジェクト: grroma/mems
 public SubdivisionRepository(AppContext context, IMapper mapper) : base(context, mapper)
 {
     _context = context;
     _mapper  = mapper;
 }
コード例 #34
0
    private TermContext term(int _p)
    {
        ParserRuleContext _parentctx = Context;
        int         _parentState     = State;
        TermContext _localctx        = new TermContext(Context, _parentState);
        TermContext _prevctx         = _localctx;
        int         _startState      = 6;

        EnterRecursionRule(_localctx, 6, RULE_term, _p);
        try {
            int _alt;
            EnterOuterAlt(_localctx, 1);
            {
                State = 32;
                ErrorHandler.Sync(this);
                switch (TokenStream.LA(1))
                {
                case T__1:
                {
                    _localctx = new ParContext(_localctx);
                    Context   = _localctx;
                    _prevctx  = _localctx;

                    State = 23; Match(T__1);
                    State = 24; term(0);
                    State = 25; Match(T__2);
                }
                break;

                case VAR:
                {
                    _localctx = new VarContext(_localctx);
                    Context   = _localctx;
                    _prevctx  = _localctx;
                    State     = 27; Match(VAR);
                }
                break;

                case LAMBDA:
                {
                    _localctx = new AbsContext(_localctx);
                    Context   = _localctx;
                    _prevctx  = _localctx;
                    State     = 28; Match(LAMBDA);
                    State     = 29; Match(VAR);
                    State     = 30; Match(DOT);
                    State     = 31; term(1);
                }
                break;

                default:
                    throw new NoViableAltException(this);
                }
                Context.Stop = TokenStream.LT(-1);
                State        = 38;
                ErrorHandler.Sync(this);
                _alt = Interpreter.AdaptivePredict(TokenStream, 3, Context);
                while (_alt != 2 && _alt != global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER)
                {
                    if (_alt == 1)
                    {
                        if (ParseListeners != null)
                        {
                            TriggerExitRuleEvent();
                        }
                        _prevctx = _localctx;
                        {
                            {
                                _localctx = new AppContext(new TermContext(_parentctx, _parentState));
                                PushNewRecursionContext(_localctx, _startState, RULE_term);
                                State = 34;
                                if (!(Precpred(Context, 2)))
                                {
                                    throw new FailedPredicateException(this, "Precpred(Context, 2)");
                                }
                                State = 35; term(3);
                            }
                        }
                    }
                    State = 40;
                    ErrorHandler.Sync(this);
                    _alt = Interpreter.AdaptivePredict(TokenStream, 3, Context);
                }
            }
        }
        catch (RecognitionException re) {
            _localctx.exception = re;
            ErrorHandler.ReportError(this, re);
            ErrorHandler.Recover(this, re);
        }
        finally {
            UnrollRecursionContexts(_parentctx);
        }
        return(_localctx);
    }
コード例 #35
0
        static BsonMessageSerializer()
        {
            ListJsonConverter = new ListJsonConverter();
            CaseInsensitiveDictionaryJsonConverter = new CaseInsensitiveDictionaryJsonConverter();
            InterfaceProxyConverter  = new InterfaceProxyConverter();
            MessageDataJsonConverter = new MessageDataJsonConverter();
            IsoDateTimeConverter     = new IsoDateTimeConverter {
                DateTimeStyles = DateTimeStyles.RoundtripKind
            };

            var namingStrategy = new CamelCaseNamingStrategy();

            DefaultContractResolver deserializerContractResolver;

            if (AppContext.TryGetSwitch(AppContextSwitches.CaseSensitiveDictionaryDeserializer, out var isEnabled) && isEnabled)
            {
                deserializerContractResolver = new JsonContractResolver(
                    ListJsonConverter,
                    InterfaceProxyConverter,
                    IsoDateTimeConverter,
                    MessageDataJsonConverter)
                {
                    NamingStrategy = namingStrategy
                };
            }
            else
            {
                deserializerContractResolver = new JsonContractResolver(
                    ListJsonConverter,
                    CaseInsensitiveDictionaryJsonConverter,
                    InterfaceProxyConverter,
                    IsoDateTimeConverter,
                    MessageDataJsonConverter)
                {
                    NamingStrategy = namingStrategy
                };
            }

            IContractResolver serializerContractResolver =
                new JsonContractResolver(IsoDateTimeConverter, MessageDataJsonConverter)
            {
                NamingStrategy = namingStrategy
            };

            DeserializerSettings = new JsonSerializerSettings
            {
                NullValueHandling      = NullValueHandling.Ignore,
                DefaultValueHandling   = DefaultValueHandling.Ignore,
                MissingMemberHandling  = MissingMemberHandling.Ignore,
                ObjectCreationHandling = ObjectCreationHandling.Auto,
                ConstructorHandling    = ConstructorHandling.AllowNonPublicDefaultConstructor,
                ContractResolver       = deserializerContractResolver,
                TypeNameHandling       = TypeNameHandling.None,
                DateParseHandling      = DateParseHandling.None,
                DateTimeZoneHandling   = DateTimeZoneHandling.RoundtripKind
            };

            SerializerSettings = new JsonSerializerSettings
            {
                NullValueHandling      = NullValueHandling.Ignore,
                DefaultValueHandling   = DefaultValueHandling.Ignore,
                MissingMemberHandling  = MissingMemberHandling.Ignore,
                ObjectCreationHandling = ObjectCreationHandling.Auto,
                ConstructorHandling    = ConstructorHandling.AllowNonPublicDefaultConstructor,
                ContractResolver       = serializerContractResolver,
                TypeNameHandling       = TypeNameHandling.None,
                DateParseHandling      = DateParseHandling.None,
                DateTimeZoneHandling   = DateTimeZoneHandling.RoundtripKind
            };

            _deserializer = new Lazy <JsonSerializer>(() => JsonSerializer.Create(DeserializerSettings));
            _serializer   = new Lazy <JsonSerializer>(() => JsonSerializer.Create(SerializerSettings));
        }
コード例 #36
0
 internal App(AppContext ctx)
 {
     context = ctx;
 }
コード例 #37
0
        public OBK_BlankResponse ReplaceBlank(int blankForReplace, int newBlank, Guid zbkCopyId)
        {
            var blankNumber = AppContext.OBK_BlankNumber.FirstOrDefault(o => o.Number == blankForReplace && o.Object_Id == zbkCopyId);

            if (blankNumber == null)
            {
                return(new OBK_BlankResponse
                {
                    message = "Исходный бланк не существует!",
                    response = false
                });
            }

            if (blankNumber.Corrupted == true)
            {
                return(new OBK_BlankResponse
                {
                    message = "Бланк заменен!",
                    response = false
                });
            }

            bool blankExistence = AppContext.OBK_BlankNumber.Any(o => o.Number == newBlank && o.Object_Id == zbkCopyId);

            var negative = new OBK_BlankResponse
            {
                message  = "Бланк уже используется! Выберите другой бланк.",
                response = false
            };

            if (blankExistence == true)
            {
                return(negative);
            }

            OBK_BlankNumber blank = new OBK_BlankNumber()
            {
                Id                 = Guid.NewGuid(),
                CreateDate         = DateTime.Now,
                EmployeeId         = UserHelper.GetCurrentEmployee().Id,
                Number             = newBlank,
                Object_Id          = blankNumber.Object_Id,
                ParentId           = blankNumber.Id,
                BlankTypeId        = blankNumber.BlankTypeId,
                Corrupted          = false,
                DecommissionedDate = DateTime.Now
            };

            blankNumber.Corrupted       = true;
            blankNumber.CorruptDate     = DateTime.Now;
            blankNumber.CorruptEmployee = UserHelper.GetCurrentEmployee().Id;

            AppContext.OBK_BlankNumber.Add(blank);
            AppContext.SaveChanges();

            return(new OBK_BlankResponse
            {
                message = "Успешно заменен!",
                response = true
            });
        }
コード例 #38
0
ファイル: Startup.cs プロジェクト: fighting71/GSForward
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddControllers(options=> {

            //    #region 设置路由前缀
            //    string prefix = Configuration["Prefix"];

            //    if (!string.IsNullOrWhiteSpace(prefix))
            //        options.UseCentralRoutePrefix(new RouteAttribute(prefix));
            //    #endregion

            //});

            services.AddControllers();

            // 添加http2支持
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            #region 添加AccountService

            string accountServiceUri = Configuration["AccountServiceUri"];

            services.AddGrpcClient <AccountLib.AccountLibClient>(options =>
            {
                options.Address = new Uri(accountServiceUri);
            });

            #endregion

            #region autoMapper
            MapperConfiguration mappingConfig = new MapperConfiguration(mc =>
            {
                mc.CreateMap <RegisterDto, RegisterReq>()
                // 忽略null值
                .ForAllMembers(opt => opt.Condition((src, dest, sourceMember) => sourceMember != null));
                mc.CreateMap <LoginDto, LoginReq>();
            });
            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);
            #endregion

            #region 配置获取
            services.Configure <AuthAESConfig>(Configuration.GetSection("AuthAES"));
            #endregion

            #region swagger

            services.AddSwaggerGen(s =>
            {
                // 使用全路径,避免相同类名异常
                s.CustomSchemaIds(x => x.FullName);
                s.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title   = "Acount web Api文档",
                    Version = "v1"
                });
                //s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                //{
                //    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                //    Name = "Authorization",
                //    In = ParameterLocation.Header,
                //    Type = SecuritySchemeType.ApiKey
                //});
                //s.AddSecurityRequirement(new OpenApiSecurityRequirement()
                //{
                //    {
                //        new OpenApiSecurityScheme
                //        {
                //            Reference = new OpenApiReference
                //            {
                //                Type = ReferenceType.SecurityScheme,
                //                Id = "Bearer"
                //            },
                //            Scheme = "oauth2",
                //            Name = "Bearer",
                //            In = ParameterLocation.Header,

                //        },
                //        new List<string>()
                //    }
                //});

                s.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "Application.AccountApi.xml"));

                s.DocumentFilter <ControllerDocumentFilter>();
            });
            #endregion
        }
コード例 #39
0
    public void Initialize(Configuration config, AppState appState, Configuration.ApplicationRow application)
    {
        foreach (Configuration.ApplicationMapTabRow appMapTabRow in application.GetApplicationMapTabRows())
        {
            Configuration.MapTabRow mapTabRow = appMapTabRow.MapTabRow;
            CommonDataFrame         dataFrame = AppContext.GetDataFrame(mapTabRow);

            bool      isInteractive = !mapTabRow.IsInteractiveLegendNull() && mapTabRow.InteractiveLegend == 1;
            CheckMode checkMode     = CheckMode.None;

            List <CommonLayer>     configuredLayers = new List <CommonLayer>();
            List <LayerProperties> layerProperties  = new List <LayerProperties>();
            List <String>          mapTabLayerIds   = new List <String>();

            string name        = null;
            string metaDataUrl = null;

            StringCollection visibleLayers = isInteractive ? appState.VisibleLayers[mapTabRow.MapTabID] : null;

            // find layers attached via MapTabLayer

            foreach (Configuration.MapTabLayerRow mapTabLayerRow in mapTabRow.GetMapTabLayerRows())
            {
                if (!mapTabLayerRow.IsShowInLegendNull() && mapTabLayerRow.ShowInLegend == 1)
                {
                    CommonLayer layer = dataFrame.Layers.FirstOrDefault(lyr => String.Compare(lyr.Name, mapTabLayerRow.LayerRow.LayerName, true) == 0);

                    name        = mapTabLayerRow.LayerRow.IsDisplayNameNull() ? mapTabLayerRow.LayerRow.LayerName : mapTabLayerRow.LayerRow.DisplayName;
                    metaDataUrl = mapTabLayerRow.LayerRow.IsMetaDataURLNull() ? null : mapTabLayerRow.LayerRow.MetaDataURL;
                    bool isExclusive = mapTabLayerRow.IsIsExclusiveNull() ? false : mapTabLayerRow.IsExclusive == 1;

                    string tag = mapTabLayerRow.LayerID;
                    mapTabLayerIds.Add(tag);

                    if (isInteractive)
                    {
                        bool layerVisible = visibleLayers != null && visibleLayers.Contains(mapTabLayerRow.LayerID);
                        checkMode = mapTabLayerRow.IsCheckInLegendNull() || mapTabLayerRow.CheckInLegend < 0 ? CheckMode.Empty :
                                    layerVisible ? CheckMode.Checked : CheckMode.Unchecked;
                    }

                    configuredLayers.Add(layer);
                    layerProperties.Add(new LayerProperties(name, tag, checkMode, isExclusive, metaDataUrl));
                }
            }

            // find layers attached via BaseMapID

            if (!mapTabRow.IsBaseMapIDNull() && !mapTabRow.IsShowBaseMapInLegendNull() && mapTabRow.ShowBaseMapInLegend == 1)
            {
                if (checkMode != CheckMode.None)
                {
                    checkMode = CheckMode.Empty;
                }

                foreach (DataRow row in config.Layer.Select("BaseMapID = '" + mapTabRow.BaseMapID + "'"))
                {
                    Configuration.LayerRow layerRow = (Configuration.LayerRow)row;

                    if (!mapTabLayerIds.Contains(layerRow.LayerID))
                    {
                        CommonLayer layer = dataFrame.Layers.FirstOrDefault(lyr => String.Compare(lyr.Name, layerRow.LayerName, true) == 0);
                        metaDataUrl = layerRow.IsMetaDataURLNull() ? null : layerRow.MetaDataURL;

                        configuredLayers.Add(layer);
                        layerProperties.Add(new LayerProperties(layerRow.Name, null, checkMode, false, metaDataUrl));
                    }
                }
            }

            // add group layers as necessary

            for (int i = 0; i < configuredLayers.Count; ++i)
            {
                checkMode = !isInteractive ? CheckMode.None : layerProperties[i].CheckMode == CheckMode.Checked ? CheckMode.Checked : CheckMode.Unchecked;
                CommonLayer parent = configuredLayers[i].Parent;

                while (parent != null)
                {
                    int index = configuredLayers.IndexOf(parent);

                    if (index < 0)
                    {
                        configuredLayers.Add(parent);
                        layerProperties.Add(new LayerProperties(parent.Name, null, checkMode, false, null));
                    }
                    else
                    {
                        if (checkMode == CheckMode.Checked && layerProperties[index].CheckMode == CheckMode.Unchecked)
                        {
                            layerProperties[index].CheckMode = CheckMode.Checked;
                        }
                    }

                    parent = parent.Parent;
                }
            }

            // create the top level legend control for this map tab

            HtmlGenericControl parentLegend = new HtmlGenericControl("div");
            pnlLegendScroll.Controls.Add(parentLegend);
            parentLegend.Attributes["data-maptab"] = appMapTabRow.MapTabID;
            parentLegend.Attributes["class"]       = "LegendTop";
            parentLegend.Style["display"]          = appMapTabRow.MapTabID == appState.MapTab ? "block" : "none";

            // add the Legend controls for the configured layers

            foreach (CommonLayer layer in dataFrame.TopLevelLayers)
            {
                AddLayerToLegend(mapTabRow.MapTabID, configuredLayers, layerProperties, parentLegend, layer);
            }
        }
    }
コード例 #40
0
 public CategoryRepository(AppContext context) : base(context)
 {
 }
コード例 #41
0
 public FoodCategoriesController(AppContext context)
 {
     _context = context;
 }
コード例 #42
0
 public JoinDateChangeCommand(
     AppContext appContext)
 {
     this.appContext = appContext;
 }
コード例 #43
0
 public static void Main(string[] args)
 {
     AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
     BuildWebHost(args).Run();
 }
コード例 #44
0
 public CarRepository(AppContext appDBContent)
 {
     this.appDBContent = appDBContent;
 }
コード例 #45
0
 public BookRepository(AppContext context) : base(context)
 {
 }
コード例 #46
0
 public BusinessRepository(AppContext context)
 {
     _context = context;
 }
コード例 #47
0
 public UserRepository(AppContext context) : base(context)
 {
 }
コード例 #48
0
 public HomeController(ILogger <HomeController> logger, AppContext context)
 {
     _logger  = logger;
     _context = context;
 }
コード例 #49
0
ファイル: Main.cs プロジェクト: migorichter/aasx-connect
        public static void Main(string[] args)
        {
            Console.WriteLine(
                "Copyright(c) 2020 PHOENIX CONTACT GmbH & Co.KG <*****@*****.**>, author: Andreas Orzelski\n" +
                "This software is licensed under the Eclipse Public License 2.0 (EPL - 2.0)\n" +
                "The Newtonsoft.JSON serialization is licensed under the MIT License (MIT)\n" +
                "The Grapevine REST server framework is licensed under Apache License 2.0 (Apache - 2.0)\n" +
                "Jose-JWT is licensed under the MIT license (MIT)\n" +
                "This application is a sample application for demonstration of the features of the Administration Shell.\n" +
                "It is not allowed for productive use. The implementation uses the concepts of the document Details of the Asset\n" +
                "Administration Shell published on www.plattform-i40.de which is licensed under Creative Commons CC BY-ND 3.0 DE."
                );
            Console.WriteLine("--help for available switches.");
            Console.WriteLine("");

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
            }

            // default command line options
            bool    debugwait  = false;
            string  sourceFile = "";
            string  proxyFile  = "";
            Boolean help       = false;

            int i = 0;

            while (i < args.Length)
            {
                var x = args[i].Trim().ToLower();

                if (x == "-node")
                {
                    sourceFile = args[i + 1];
                    Console.WriteLine(args[i] + " " + args[i + 1]);
                    i += 2;
                    continue;
                }

                if (x == "-debugwait")
                {
                    debugwait = true;
                    Console.WriteLine(args[i]);
                    i++;
                    continue;
                }

                if (x == "-proxy")
                {
                    proxyFile = args[i + 1];
                    Console.WriteLine(args[i] + " " + args[i + 1]);
                    i += 2;
                    continue;
                }

                if (x == "--help")
                {
                    help = true;
                    break;
                }
            }

            if (help)
            {
                Console.WriteLine("-node Name of node file:\n" +
                                  "   Line1 = SourceName,\n" +
                                  "   L2 = Domainname,\n" +
                                  "   L3 = ParentDomain or GLOBALROOT or LOCALROOT,\n" +
                                  "   L4* = ChildDomains to be called from above"
                                  );
                Console.WriteLine("-debugwait = wait for Debugger to attach");
                Console.WriteLine("Press ENTER");
                Console.ReadLine();
                return;
            }
            Console.WriteLine("");

            // auf Debugger warten
            if (debugwait)
            {
                Console.WriteLine("Please attach debugger now!");
                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    System.Threading.Thread.Sleep(100);
                }
                Console.WriteLine("Debugger attached");
            }

            // Proxy
            string proxyAddress = "";
            string username     = "";
            string password     = "";

            if (proxyFile != "")
            {
                if (!File.Exists(proxyFile))
                {
                    Console.WriteLine(proxyFile + " not found!");
                    Console.ReadLine();
                    return;
                }

                try
                {
                    using (StreamReader sr = new StreamReader(proxyFile))
                    {
                        proxyAddress = sr.ReadLine();
                        username     = sr.ReadLine();
                        password     = sr.ReadLine();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine(proxyFile + " not found!");
                }

                if (proxyAddress != "")
                {
                    proxy = new WebProxy();
                    Uri newUri = new Uri(proxyAddress);
                    proxy.Address     = newUri;
                    proxy.Credentials = new NetworkCredential(username, password);
                    // proxy.BypassProxyOnLocal = true;
                    Console.WriteLine("Using proxy: " + proxyAddress);

                    clientHandler = new HttpClientHandler
                    {
                        Proxy    = proxy,
                        UseProxy = true
                    };
                }
            }
            ;

            if (!File.Exists(sourceFile))
            {
                Console.WriteLine(sourceFile + " not found!");
                Console.ReadLine();
                return;
            }

            try
            {
                using (StreamReader sr = new StreamReader(sourceFile))
                {
                    // sourceNumber = Convert.ToInt32(sr.ReadLine());
                    sourceName   = sr.ReadLine();
                    domainName   = sr.ReadLine();
                    parentDomain = sr.ReadLine();

                    string localChild = "";
                    do
                    {
                        localChild = sr.ReadLine();
                        if (localChild != "")
                        {
                            childDomains[childDomainsCount++] = localChild;
                        }
                    }while (localChild != "");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(sourceFile + " not found!");
                Console.ReadLine();
                return;
            }

            bool https = false;

            string[] split1 = domainName.Split(new Char[] { '/' });
            if (split1[0].ToLower() == "https:")
            {
                https = true;
            }
            string[] split2         = split1[2].Split(new Char[] { ':' });
            var      serverSettings = new ServerSettings
            {
                Host     = split2[0],
                Port     = split2[1],
                UseHttps = https
            };

            Console.WriteLine("Waiting for client on " + domainName);

            RestServer rs = new RestServer(serverSettings);

            rs.Start();

            HttpClient httpClient;
            string     payload     = "{ \"source\" : \"" + sourceName + "\" }";
            var        contentJson = new StringContent(payload, System.Text.Encoding.UTF8, "application/json");

            if (parentDomain != "GLOBALROOT" && parentDomain != "LOCALROOT")
            {
                if (clientHandler != null)
                {
                    httpClient = new HttpClient(clientHandler);
                }
                else
                {
                    httpClient = new HttpClient();
                }

                try
                {
                    var    result  = httpClient.PostAsync(parentDomain + "/connect", contentJson).Result;
                    string content = ContentToString(result.Content);
                }
                catch
                {
                    Console.WriteLine("Can not /connect");
                }
            }

            for (i = 0; i < childDomainsCount; i++)
            {
                httpClient = new HttpClient();

                payload     = "{ \"source\" : \"" + sourceName + "\" }";
                contentJson = new StringContent(payload, System.Text.Encoding.UTF8, "application/json");

                string content = "";
                try
                {
                    var result = httpClient.PostAsync(childDomains[i] + "/connectDown", contentJson).Result;
                    content = ContentToString(result.Content);
                }
                catch
                {
                }

                if (content != "")
                {
                    Console.WriteLine("ConnectDown " + childDomains[i] + " : " + content);
                    childDomainsNames[i] = content;
                    childs.Add(content);
                }
            }

            Thread t = new Thread(new ThreadStart(ThreadLoop));

            t.Start();

            Thread t2 = new Thread(new ThreadStart(checkChildsTimeStamps));

            t2.Start();

            Console.WriteLine("Press CTRL-C to STOPP");
            // Console.ReadLine();
            ManualResetEvent quitEvent = new ManualResetEvent(false);

            try
            {
                Console.CancelKeyPress += (sender, eArgs) =>
                {
                    quitEvent.Set();
                    eArgs.Cancel = true;
                };
            }
            catch
            {
            }
            // wait for timeout or Ctrl-C
            quitEvent.WaitOne(Timeout.Infinite);

            loop = false;

            if (parentDomain != "GLOBALROOT" && parentDomain != "LOCALROOT")
            {
                if (clientHandler != null)
                {
                    httpClient = new HttpClient(clientHandler);
                }
                else
                {
                    httpClient = new HttpClient();
                }

                try
                {
                    contentJson = new StringContent(payload, System.Text.Encoding.UTF8, "application/json");
                    httpClient.PostAsync(parentDomain + "/disconnect", contentJson).Wait();
                }
                catch
                {
                    Console.WriteLine("Can not /disconnect. Press ENTER");
                    Console.ReadLine();
                }
            }

            rs.Stop();
        }
コード例 #50
0
 public SessionScheduleController()
 {
     _db = new AppContext();
 }
コード例 #51
0
        public void DublcateDoage(string modelId, long dosageId, string userId)
        {
            var model = AppContext.EXP_DrugDeclaration.FirstOrDefault(e => e.Id == new Guid(modelId)) ??
                        new EXP_DrugDeclaration
            {
                OwnerId     = new Guid(userId),
                TypeId      = CodeConstManager.DRUG_REGISTER_ID,
                Id          = new Guid(modelId),
                StatusId    = CodeConstManager.STATUS_DRAFT_ID,
                CreatedDate = DateTime.Now,
            };

            if (dosageId == 0)
            {
                var addDosage = new EXP_DrugDosage
                {
                    EXP_DrugDeclaration = model
                };
                AppContext.EXP_DrugDosage.Add(addDosage);
                AppContext.SaveChanges();
                return;
            }

            var dosage = AppContext.EXP_DrugDosage.FirstOrDefault(e => e.Id == dosageId);

            if (dosage == null)
            {
                return;
            }
            var newDosage = new EXP_DrugDosage
            {
                AppPeriodMix              = dosage.AppPeriodMix,
                AppPeriodMixMeasureDicId  = dosage.AppPeriodMixMeasureDicId,
                AppPeriodOpen             = dosage.AppPeriodOpen,
                AppPeriodOpenMeasureDicId = dosage.AppPeriodOpenMeasureDicId,
                BestBefore = dosage.BestBefore,
                BestBeforeMeasureTypeDicId = dosage.BestBeforeMeasureTypeDicId,
                ConcentrationKz            = dosage.ConcentrationKz,
                ConcentrationRu            = dosage.ConcentrationRu,
                Dosage = dosage.Dosage,
                DosageMeasureTypeId = dosage.DosageMeasureTypeId,
                DosageNoteKz        = dosage.DosageNoteKz,
                DosageNoteRu        = dosage.DosageNoteRu,
                DrugDeclarationId   = dosage.DrugDeclarationId,
                SaleTypeId          = dosage.SaleTypeId,
            };

            foreach (var expDrugPrice in dosage.EXP_DrugPrice)
            {
                var price = new EXP_DrugPrice()
                {
                    Barcode           = expDrugPrice.Barcode,
                    CountUnit         = expDrugPrice.CountUnit,
                    EXP_DrugDosage    = newDosage,
                    IntermediateText  = expDrugPrice.IntermediateText,
                    IntermediateValue = expDrugPrice.IntermediateValue,
                    ManufacturePrice  = expDrugPrice.ManufacturePrice,
                    PrimaryText       = expDrugPrice.PrimaryText,
                    PrimaryValue      = expDrugPrice.PrimaryValue,
                    RefPrice          = expDrugPrice.RefPrice,
                    RegPrice          = expDrugPrice.RegPrice,
                    SecondaryText     = expDrugPrice.SecondaryText,
                    SecondaryValue    = expDrugPrice.SecondaryValue
                };
                newDosage.EXP_DrugPrice.Add(price);
            }
            foreach (var entity in dosage.EXP_DrugSubstance)
            {
                var substance = new EXP_DrugSubstance()
                {
                    EXP_DrugDosage    = newDosage,
                    CategoryName      = entity.CategoryName,
                    CategoryPos       = entity.CategoryPos,
                    CountryId         = entity.CountryId,
                    IsControl         = entity.IsControl,
                    IsNotFound        = entity.IsNotFound,
                    IsPoison          = entity.IsPoison,
                    Locus             = entity.Locus,
                    MeasureId         = entity.MeasureId,
                    NewName           = entity.NewName,
                    NormDocFarmId     = entity.NormDocFarmId,
                    NormativeDocument = entity.NormativeDocument,
                    OriginId          = entity.OriginId,
                    PlantKindId       = entity.PlantKindId,
                    ProducerAddress   = entity.ProducerAddress,
                    ProducerName      = entity.ProducerName,
                    SubstanceCount    = entity.SubstanceCount,
                    SubstanceId       = entity.SubstanceId,
                    SubstanceName     = entity.SubstanceName,
                    SubstanceTypeId   = entity.SubstanceTypeId,
                };
                newDosage.EXP_DrugSubstance.Add(substance);
            }
            foreach (var entity in dosage.EXP_DrugWrapping)
            {
                var wrapping = new EXP_DrugWrapping()
                {
                    EXP_DrugDosage    = newDosage,
                    CountUnit         = entity.CountUnit,
                    Note              = entity.Note,
                    SizeMeasureId     = entity.SizeMeasureId,
                    VolumeMeasureId   = entity.VolumeMeasureId,
                    WrappingKindId    = entity.WrappingKindId,
                    WrappingSize      = entity.WrappingSize,
                    WrappingTypeId    = entity.WrappingTypeId,
                    WrappingVolume    = entity.WrappingVolume,
                    WrappingSizeStr   = entity.WrappingSizeStr,
                    WrappingVolumeStr = entity.WrappingVolumeStr
                };
                newDosage.EXP_DrugWrapping.Add(wrapping);
            }
            AppContext.EXP_DrugDosage.Add(newDosage);
            AppContext.SaveChanges();
        }
コード例 #52
0
 public EmployeeDetailsService(AppContext context, DateTime date)
 {
     _basicDetailsService = new BasicDetailsService(context, date);
 }
コード例 #53
0
 /// <summary>
 /// Clears all context collections.
 /// </summary>
 internal static void Clear()
 {
     SetClientContext(null);
     SetGlobalContext(null);
     AppContext.Clear();
 }
コード例 #54
0
 public UnitOfWork()
 {
     context    = new AppContext();
     Projects   = new ProjectRepository(context);
     Activities = new Repository <Activity>(context);
 }
コード例 #55
0
ファイル: PosteRepository.cs プロジェクト: csjfnc/gio
 public PosteRepository(AppContext appContext) : base(appContext)
 {
 }
コード例 #56
0
        public void SetDrugReestr(Guid modelId, long dosageId, int?reestrId)
        {
            var drugTypes = new Dictionary <int, int>();

            drugTypes.Add(1, 1);   //Лекарственный препарат
            drugTypes.Add(2, 2);   //Иммунобиологический препарат
            drugTypes.Add(3, 3);   //Лекарственное растительное сырье (сборы)
            drugTypes.Add(4, 4);   //Гомеопатический препарат
            drugTypes.Add(6, 5);   //Лекарственная субстанция
            drugTypes.Add(7, 6);   //Лекарственный балк-продукт
            drugTypes.Add(8, 7);   //Иммунобиологический балк-продукт
            drugTypes.Add(9, 8);   //Радиопрепарат
            drugTypes.Add(10, 9);  //Не фармакопейное лекарственное растительное сырье
            drugTypes.Add(11, 10); //Лекарственный препарат биологического происхождения

            var monufactureType = new Dictionary <int, string>();

            monufactureType.Add(1, "1");  //Производитель
            monufactureType.Add(2, "2");  //Держатель лицензии
                                          //            monufactureType.Add(3, "1"); //Дистрибьютор
            monufactureType.Add(4, "4");  //Предприятие-упаковщик
            monufactureType.Add(5, "5");  //Заявитель
                                          //            monufactureType.Add(6, "1"); //Производитель субстанции
                                          //            monufactureType.Add(7, "1"); //Разработчик
                                          //            monufactureType.Add(8, "3"); //Владелец регистрационного удостоверения
            monufactureType.Add(9, "7");  //Выпускающий контроль
            monufactureType.Add(10, "3"); //Держатель регистрационного удостоверения

            var model = AppContext.EXP_DrugDeclaration.FirstOrDefault(e => e.Id == modelId);

            if (model == null)
            {
                return;
            }
            var drug   = new ExternalRepository().GEtRegisterDrugById(reestrId);
            var reestr = new ExternalRepository().GetReestrById(reestrId.Value);

            if (!string.IsNullOrEmpty(model.NameRu))
            {
                model.NameRu = reestr.name;
            }
            if (!string.IsNullOrEmpty(model.NameKz))
            {
                model.NameKz = reestr.name_kz;
            }
            if (!string.IsNullOrEmpty(model.ConcentrationRu))
            {
                model.ConcentrationRu = drug.concentration;
            }
            if (!string.IsNullOrEmpty(model.ConcentrationKz))
            {
                model.ConcentrationKz = drug.concentration_kz;
            }
            if (model.AtxId == null)
            {
                model.AtxId = drug.atc_id;
            }
            if (model.MnnId == null)
            {
                model.MnnId = drug.int_name_id;
            }
            if (model.DrugFormId == null)
            {
                model.DrugFormId = drug.dosage_form_id;
            }

            if (drugTypes.ContainsKey(drug.drug_type_id))
            {
                if (model.EXP_DrugType.Count == 0)
                {
                    var type = new EXP_DrugType();
                    type.DrugTypeId = drugTypes[drug.drug_type_id];
                    model.EXP_DrugType.Add(type);
                }
                else
                {
                    model.EXP_DrugType.First().DrugTypeId = drugTypes[drug.drug_type_id];
                }
            }
            if (drug.sr_register_use_methods.Count > 0)
            {
                var usemethod = model.EXP_DrugUseMethod.Select(e => e.UseMethodsId) ?? new List <int>();
//                AppContext.EXP_DrugUseMethod.RemoveRange(model.EXP_DrugUseMethod);
                foreach (var drugSrRegisterUseMethod in drug.sr_register_use_methods)
                {
                    if (!usemethod.Contains(drugSrRegisterUseMethod.use_method_id))
                    {
                        var useMethod = new EXP_DrugUseMethod {
                            UseMethodsId = drugSrRegisterUseMethod.use_method_id
                        };
                        model.EXP_DrugUseMethod.Add(useMethod);
                    }
                }
            }
            var repository          = new ReadOnlyDictionaryRepository();
            var orgManufactureTypes = repository.GetDictionaries(CodeConstManager.DIC_ORG_MANUFACTURE_TYPE);
            var countyDics          = repository.GetDictionaries(CodeConstManager.DIC_COUNTRY_TYPE);

            if (reestr.sr_register_producers.Count > 0)
            {
                AppContext.EXP_DrugOrganizations.RemoveRange(model.EXP_DrugOrganizations);
                foreach (var registerProducer in reestr.sr_register_producers)
                {
                    var producer = new EXP_DrugOrganizations();
                    if (registerProducer.sr_producers != null)
                    {
                        producer.NameRu = registerProducer.sr_producers.name;
                        producer.NameEn = registerProducer.sr_producers.name_eng;
                        producer.NameKz = registerProducer.sr_producers.name_kz;
                        producer.Bin    = registerProducer.sr_producers.bin;

                        if (monufactureType.ContainsKey(registerProducer.sr_producers.type_id))
                        {
                            var orgManufactureType =
                                orgManufactureTypes.FirstOrDefault(
                                    e => e.Code == monufactureType[registerProducer.sr_producers.type_id]);
                            if (orgManufactureType != null)
                            {
                                producer.OrgManufactureTypeDicId = orgManufactureType.Id;
                            }
                        }
                    }
                    if (registerProducer.sr_countries != null)
                    {
                        var country =
                            countyDics.FirstOrDefault(
                                e => e.Name.ToLower() == registerProducer.sr_countries.name.ToLower());
                        if (country != null)
                        {
                            producer.CountryDicId = country.Id;
                        }
                    }
                    model.EXP_DrugOrganizations.Add(producer);
                }
            }
            if (reestr.sr_register_substances.Count > 0)
            {
                EXP_DrugDosage dosage;
                if (dosageId == 0)
                {
                    dosage = new EXP_DrugDosage
                    {
                        ConcentrationRu = drug.concentration,
                        ConcentrationKz = drug.concentration_kz,
                    };
                }
                else
                {
                    dosage = AppContext.EXP_DrugDosage.FirstOrDefault(e => e.Id == dosageId);
                    AppContext.EXP_DrugSubstance.RemoveRange(dosage.EXP_DrugSubstance);
                    AppContext.EXP_DrugPrice.RemoveRange(dosage.EXP_DrugPrice);
                    AppContext.EXP_DrugWrapping.RemoveRange(dosage.EXP_DrugWrapping);
                }

                /*  foreach (var expDrugDosage in model.EXP_DrugDosage)
                 * {
                 *    AppContext.EXP_DrugSubstance.RemoveRange(expDrugDosage.EXP_DrugSubstance);
                 *    AppContext.EXP_DrugPrice.RemoveRange(expDrugDosage.EXP_DrugPrice);
                 *    AppContext.EXP_DrugWrapping.RemoveRange(expDrugDosage.EXP_DrugWrapping);
                 * }
                 * AppContext.EXP_DrugDosage.RemoveRange(model.EXP_DrugDosage);
                 */

                if (drug.dosage_value != null)
                {
                    dosage.Dosage = drug.dosage_value.Value;
                }
                dosage.DosageMeasureTypeId = drug.dosage_measure_id;
                dosage.RegisterId          = reestrId;

                foreach (var reestrSrRegisterSubstance in reestr.sr_register_substances)
                {
                    var substance = new EXP_DrugSubstance
                    {
                        SubstanceId     = reestrSrRegisterSubstance.substance_id,
                        SubstanceTypeId = reestrSrRegisterSubstance.substance_type_id,
                        CountryId       = reestrSrRegisterSubstance.country_id,
                        MeasureId       = reestrSrRegisterSubstance.measure_id
                    };
                    if (reestrSrRegisterSubstance.substance_count != null)
                    {
                        substance.SubstanceCount = reestrSrRegisterSubstance.substance_count.ToString();
                    }
                    dosage.EXP_DrugSubstance.Add(substance);
                }

                foreach (var registerBoxes in reestr.sr_register_boxes)
                {
                    var wrapping = new EXP_DrugWrapping()
                    {
                        WrappingKindId  = registerBoxes.box_id,
                        VolumeMeasureId = registerBoxes.volume_measure_id,
                        CountUnit       = registerBoxes.unit_count,
                        Note            = registerBoxes.description,
                    };

                    if (registerBoxes.volume != null)
                    {
                        wrapping.WrappingVolume = double.Parse(registerBoxes.volume.ToString());
                    }
                    if (!string.IsNullOrEmpty(registerBoxes.box_size))
                    {
                        double size;
                        if (double.TryParse(registerBoxes.box_size, out size))
                        {
                            wrapping.WrappingSize = size;
                        }
                    }
                    dosage.EXP_DrugWrapping.Add(wrapping);
                }
                if (dosage.Id == 0)
                {
                    model.EXP_DrugDosage.Add(dosage);
                }
            }
            try
            {
                AppContext.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                      eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                          ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
        }
コード例 #57
0
 private void MenuDeleteSqlServer_Click(object sender, RoutedEventArgs e)
 {
     AppContext.DeleteDb(0);
 }
コード例 #58
0
ファイル: PosteRepository.cs プロジェクト: csjfnc/gio
 public void SetDataExclusao(Poste poste)
 {
     poste.DataExclusao            = DateTime.Now;
     AppContext.Entry(poste).State = EntityState.Modified;
 }
コード例 #59
0
 public AuthenticationTests()
 {
     // Fixes it on .Net Core 3.1
     AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
 }
コード例 #60
0
 public FeatureToggleFacts()
 {
     AppContext.SetSwitch("experimental", false);
     AppContext.SetSwitch("edge", false);
     AppContext.SetSwitch("legacy", false);
 }