public IHttpActionResult Get()
 {
     using (var context = new ConnectContext())
     {
         return(Ok(context.GetReports <QCReport>(ConnectUser).Select(c => new QCCheckViewModel(c))));
     }
 }
        private static async Task <MobileApplicationUser> IsUserAuthorized <T>(MobileAppRequestViewModel <T> message)
        {
            if (string.IsNullOrEmpty(message?.Username) || string.IsNullOrEmpty(message.Thumbprint))
            {
                return(null);
            }

            using (var context = new ConnectContext())
            {
                var user = await context.MobileApplicationUsers.FirstOrDefaultAsync(u => u.Username == message.Username && u.Thumbprint == message.Thumbprint);

                if (user != null)
                {
                    user.EmailAddress = message.EmailAddress;
                    return(user.IsAuthorized ? user : null);
                }

                user = context.MobileApplicationUsers.Add(new MobileApplicationUser
                {
                    Username     = message.Username,
                    Thumbprint   = message.Thumbprint,
                    EmailAddress = message.EmailAddress,
                    IsAuthorized = true
                });
                await context.SaveChangesAsync();

                return(user);
            }
        }
Exemple #3
0
        public async Task <IHttpActionResult> Get()
        {
            using (var context = new ConnectContext())
            {
                var model = new GenerateEmailReportViewModel
                {
                    From = DateTime.Now.StartOfLastMonth(),
                    To   = DateTime.Now.EndOfNextMonth()
                };

                var clients = await context.Users.Where(c => c.CompanyKey == ConnectUser.CompanyKey || ConnectUser.CompanyKey == ConnectConstants.ConnectAdministratonCompany)
                              .OrderBy(c => c.CompanyKey)
                              .ToListAsync();

                model.Clients = clients.Select(c => new ClientNameViewModel(c)).ToList();
                model.Clients.RemoveAll(c => c.Name == ConnectConstants.ConnectAdministratonCompany);

                if (User.IsInRole(ConnectRoles.Admin))
                {
                    model.Clients.Insert(0, new ClientNameViewModel(-1, Constants.All));
                }

                return(Ok(model));
            }
        }
Exemple #4
0
        public async Task <IHttpActionResult> AddClient([FromBody] ClientViewModel data)
        {
            if (data == null || string.IsNullOrEmpty(data.Name))
            {
                throw new ArgumentNullException(nameof(data));
            }

            using (var context = new ConnectContext())
            {
                if (context.Clients.Any(c => c.Name == data.Name))
                {
                    return(BadRequest("A client already exists with that name."));
                }

                var client = new Client
                {
                    Name     = data.Name,
                    Created  = DateTime.Now,
                    AccessId = Guid.NewGuid(),
                    Licenses = new List <License>()
                };

                context.Clients.Add(client);
                await context.SaveChangesAsync();

                return(Ok(client));
            }
        }
Exemple #5
0
        public IHttpActionResult Post([FromBody] EmailReportViewModel data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
            if (data.UserId == -1 && !User.IsInRole(ConnectRoles.Admin))
            {
                return(Unauthorized());
            }

            using (var context = new ConnectContext())
            {
                switch (data.ReportType)
                {
                case ApiReportType.RecentCalibrations:
                    var recentCalibrations = context.RecentCalibrations(ConnectUser, data.UserId, data.From);
                    SendEmail(data.Recipient, "Your Recent Calibrations Report", EmailHelper.GetCalibrationDataTable(recentCalibrations));
                    break;

                case ApiReportType.CalibrationsDue:
                    var calibrationsDue = context.CalibrationsDue(ConnectUser, data.UserId, data.From, data.To.GetValueOrDefault());
                    SendEmail(data.Recipient, "Your Calibrations Due Report", EmailHelper.GetCalibrationDataTable(calibrationsDue));
                    break;
                }
            }

            return(Ok());
        }
Exemple #6
0
        private const ConnectionType UserIdConnectionType = ConnectionType.RemoteTrusted;             //use RemoteTrusted if specifying a windows user on the server, or SQL if using a DB local user

        /// <summary>
        /// The Main method - the standard entry function for a .Net console application. This method will execute other
        /// methods in order to fulfill the final goal - in this case, printing the name of the Root node in the Archive instance.
        /// </summary>
        static void Main()
        {
            //create a client instance (in this case, the addition of a service reference auto-generated this 'proxy' class) to operate with.
            CinegyDataAccessServiceClient cinegyClient = new CinegyDataAccessServiceClient();

            //CAS requires a connection context to be provided with most calls, in order to assign the correct session to any individual call.
            //This context is linked to a user login, and will determine the security context in which results are returned.
            //Identical calls to the same method varying by context may yield different results, depending on the user permissions!
            ConnectContext clientConnectContext = ConnectToCas(cinegyClient);

            //The CAS proxy object implements a number of concrete types - but any type that exists in the explorer tree structure
            //inherit from Node. The Root Node is a special object which represents the very start of the explorer tree.
            //If you wanted to draw the tree out, you would start by getting the details of the root node.
            Node rootNode = GetRootNode(cinegyClient, clientConnectContext);

            //Little bit of error checking, in case the connection has failed and the root node is null
            if (rootNode != null)
            {
                Console.WriteLine("Connected to CAS OK, Root Node Name: " + rootNode.name);
            }

            //CAS will keep a connection alive for a time (the default is 5 minutes, unless altered in configuration).
            //A heartbeat can be transmitted to let the service know the connection is still alive, and absence of this
            //light-weight heartbeat (or other calls) will make the service terminate the connection (and invalidate the context).
            //However, if you know you are disconnecting, call the explict disconnection and then the service will
            //return the license for that connection and invalidate the context immediately. This is very useful when configured
            //to block secondary logins from one user if another is active (just like the Desktop client).
            DisconnectFromCas(cinegyClient, clientConnectContext);

            Console.WriteLine("\n\nPress Enter to Quit.");

            Console.ReadLine();
        }
Exemple #7
0
 public SearchGoods(ref DataGridView gridBasket)
 {
     InitializeComponent();
     db = new ConnectContext((new ConfigJson()).StringConnecting());
     db.Goods_category.Local.CollectionChanged += Local_CollectionChanged;
     this.gridBasket = gridBasket;
 }
Exemple #8
0
        public async Task <IHttpActionResult> AddLicense([FromBody] LicenseViewModel data)
        {
            using (var context = new ConnectContext())
            {
                var client = await context.Clients.Include(x => x.Licenses).FirstOrDefaultAsync(c => c.AccessId == data.AccessId);

                if (client != null)
                {
                    var license = new License
                    {
                        Created    = DateTime.Now,
                        Expiration = data.Expiration,
                        Key        = data.Expiration.Ticks.ToString(CultureInfo.InvariantCulture).TrimEnd(char.Parse("0")),
                        AccessId   = Guid.NewGuid()
                    };

                    client.Licenses.Add(license);

                    await context.SaveChangesAsync();

                    return(Ok(new LicenseViewModel(license)));
                }

                return(BadRequest("Could not find client"));
            }
        }
Exemple #9
0
 public Education(int id_employees, ref ListBox education)
 {
     InitializeComponent();
     db = new ConnectContext((new ConfigJson()).StringConnecting());
     this.id_employees = id_employees;
     this.education    = education;
 }
        public IHttpActionResult Get(string vehicleRegistration)
        {
            if (string.IsNullOrEmpty(vehicleRegistration))
            {
                return(BadRequest());
            }

            using (var context = new ConnectContext())
            {
                vehicleRegistration = vehicleRegistration.ToUpper().Trim().Replace(" ", "");

                var allDocuments = context.GetAllDocuments(ConnectUser)
                                   .OfType <TachographDocument>()
                                   .OrderByDescending(c => c.CalibrationTime.GetValueOrDefault())
                                   .Where(c => c.RegistrationNumber == vehicleRegistration)
                                   .ToList();

                var result = new InspectionDataViewModel();
                result.Parse(allDocuments.FirstOrDefault());

                if (allDocuments.Count > 0)
                {
                    var documents = allDocuments.Where(c => !string.IsNullOrEmpty(c.InspectionInfo)).Skip(1)
                                    .Select(c => new HistoryViewModel(c.CalibrationTime.GetValueOrDefault(), c.InspectionInfo));

                    foreach (var item in documents)
                    {
                        result.History.Add(item);
                    }
                }

                return(Ok(result));
            }
        }
Exemple #11
0
        private static void AddLicenseForUser(ConnectContext context, ConnectUser user, RegisterUserViewModel data)
        {
            var licenseUser = context.Clients.Include(x => x.Licenses).FirstOrDefault(c => c.Name == user.CompanyKey);

            if (licenseUser == null)
            {
                licenseUser = new Client
                {
                    Name     = user.CompanyKey,
                    Created  = DateTime.Now,
                    AccessId = Guid.NewGuid(),
                    Licenses = new List <License>()
                };
                context.Clients.Add(licenseUser);
            }

            licenseUser.Licenses.Add(new License
            {
                Created    = DateTime.Now,
                Expiration = data.Expiration,
                Key        = data.Expiration.Ticks.ToString(CultureInfo.InvariantCulture).TrimEnd(char.Parse("0")),
                AccessId   = Guid.NewGuid()
            });

            context.SaveChanges();
        }
Exemple #12
0
        public IActionResult GetNewUser()
        {
            User newUser;

            using (var ctx = new ConnectContext())
            {
                var address = ctx.Set <Address>().Find(1);

                var id = new Random().Next(10, 4000);

                newUser = new User()
                {
                    Id        = id,
                    Name      = $"user{id}",
                    AddressId = address.Id
                };

                ctx.Set <User>().Add(newUser);
                ctx.SaveChanges();

                Console.WriteLine(newUser.Address == null);
            }

            //this will be false as newUser's Address property got automatically populated
            return(Ok(newUser.Address == null));
        }
Exemple #13
0
        public async Task <IHttpActionResult> EmailCertificate([FromBody] CalibrationCertificateEmailViewModel calibrationData)
        {
            Document document;

            using (var context = new ConnectContext())
            {
                document = (Document)await context.GetDocumentAsync(calibrationData.DocumentType, calibrationData.DocumentId);

                var fullDocumentType       = calibrationData.DocumentType.GetAttributeOfType <FullDocumentTypeAttribute>().Type;
                var documentSerializedData = await context.SerializedData.FirstOrDefaultAsync(s => s.DocumentId == document.Id && s.DocumentType == fullDocumentType);

                if (documentSerializedData != null)
                {
                    document.SerializedData = documentSerializedData.Data;
                }
            }

            if (document != null && document.SerializedData != null)
            {
                try
                {
                    SendCertificate(calibrationData.Recipient, "Your Certificate From WebcalConnect.com", document);
                    return(Ok());
                }
                catch (Exception)
                {
                    return(InternalServerError());
                }
            }

            return(NotFound());
        }
Exemple #14
0
        private void button_payment_card_Click(object sender, EventArgs e)
        {
            using (ConnectContext db = new ConnectContext((new ConfigJson()).StringConnecting()))
            {
                var countGoods = from g in db.Goods
                                 join cat in db.Goods_category on g.id_goods_category equals cat.id
                                 select new
                { category = g.Goods_category.title,
                  title        = g.title,
                  manufacturer = g.manufacturer,
                  date_create  = g.date_create,
                  date_end     = g.date_end,
                  shelf_life   = g.shelf_life,
                  count        = g.count, };

                gridStorage.DataSource = countGoods.ToList();

                gridStorage.Columns["category"].HeaderText     = "Категория";
                gridStorage.Columns["title"].HeaderText        = "Название товара";
                gridStorage.Columns["manufacturer"].HeaderText = "Производитель";
                gridStorage.Columns["count"].HeaderText        = "Количество ";
                gridStorage.Columns["date_end"].HeaderText     = "Дата просрочки";
                gridStorage.Columns["shelf_life"].HeaderText   = "Срок годности";
                gridStorage.Columns["date_create"].HeaderText  = "Дата производства";
            }
            ColorRowsDate();
        }
Exemple #15
0
        private void button_add_Click(object sender, EventArgs e)
        {
            using (ConnectContext db = new ConnectContext((new ConfigJson()).StringConnecting()))
            {
                var countGoods = from g in db.Goods
                                 join cat in db.Goods_category on g.id_goods_category equals cat.id

                                 group g by new
                {
                    g.Goods_category,
                    g.title,
                    g.manufacturer
                } into s


                    select new
                {
                    title        = s.Key.title,
                    manufacturer = s.Key.manufacturer,
                    count        = s.Count(),
                    sum          = s.Sum(x => x.count)
                };

                gridStorage.DataSource = countGoods.ToList();
                gridStorage.Columns["title"].HeaderText        = "Название товара";
                gridStorage.Columns["manufacturer"].HeaderText = "Производитель";
                gridStorage.Columns["count"].HeaderText        = "Количество партий";
                gridStorage.Columns["sum"].HeaderText          = "Общее количество товара";
            }
            ColorRows("sum");
        }
        public async Task <HttpResponseMessage> DirectUpload(int itemId)
        {
            DirectUploadDocument document;

            using (var context = new ConnectContext())
            {
                document = await context.GetDirectUploadDocumentAsync(ConnectUser, itemId);
            }

            var userId = -1;

            byte[] serializedData = null;

            if (document != null)
            {
                userId         = document.UserId;
                serializedData = document.SerializedData;
            }

            if (userId != -1 && serializedData != null && (User.IsInRole(ConnectRoles.Admin) || User.Identity.GetUserId <int>() == userId))
            {
                return(Pdf(serializedData, $"{document.FileName}"));
            }

            return(new HttpResponseMessage(HttpStatusCode.NotFound));
        }
        public async Task <IHttpActionResult> Post(AddressBookEntryViewModel addressBookEntry)
        {
            if (addressBookEntry == null)
            {
                return(BadRequest());
            }

            using (var context = new ConnectContext())
            {
                var userId          = User.Identity.GetUserId <int>();
                var isAdministrator = User.IsInRole(ConnectRoles.Admin);

                var entry = await context.CustomerContacts.FirstOrDefaultAsync(c => c.Id == addressBookEntry.Id && (userId == c.UserId || isAdministrator));

                if (entry != null)
                {
                    entry.Email          = addressBookEntry.Email;
                    entry.SecondaryEmail = addressBookEntry.SecondaryEmail;

                    await context.SaveChangesAsync();

                    return(Ok());
                }
            }

            return(NotFound());
        }
Exemple #18
0
 public AdminSaleOrder(ref DataGridView grid, ref Label labRes, ref Chart Chart)
 {
     InitializeComponent();
     db          = new ConnectContext((new ConfigJson()).StringConnecting());
     this.grid   = grid;
     this.labRes = labRes;
     this.Chart  = Chart;
 }
Exemple #19
0
 public SeeSale(User_access user)
 {
     InitializeComponent();
     db = new ConnectContext((new ConfigJson()).StringConnecting());
     db.Sale.Local.CollectionChanged += Local_CollectionChanged;
     this.user      = user;
     this.employees = db.Employees.Where(em => em.id_user_access == user.id).ToList();
 }
Exemple #20
0
 protected override void ProcessSend(SocketAsyncEventArgs e)
 {
     if (ValidateAsyncResult(e))
     {
         ConnectContext connectContext = (ConnectContext)e.UserToken;
         byte[]         array          = new byte[m_ReceiveBufferSize];
         e.SetBuffer(array, 0, array.Length);
         StartReceive(connectContext.Socket, e);
     }
 }
        public IHttpActionResult Get()
        {
            var from = DateTime.Now.StartOfMonth();
            var to   = DateTime.Now.EndOfNextMonth();

            using (var context = new ConnectContext())
            {
                return(Ok(context.GetAllDocuments(ConnectUser, from, to).Select(c => new CalibrationsDueViewModel(c))));
            }
        }
Exemple #22
0
        static void Main(string[] args)
        {
            ConnectContext context = new ConnectContext();
            StoreDTO       store   = new StoreDTO();

            store.productName   = "Table";
            store.quantity      = 2;
            store.lastPurchased = Convert.ToDateTime("10-10-2020");
            context.StoreDTO.Add(store);
            context.SaveChanges();
        }
Exemple #23
0
        TryConnectAsync(ConnectContext context)
        {
            var newState = await(_onTryConnect?.Invoke(context.CancellationToken) ?? Task.FromResult(ConnectivityState.Ready));

            CurrentAddress = Subchannel._addresses[0];
            Subchannel.UpdateConnectivityState(newState, Status.DefaultSuccess);

            _connectTcs.TrySetResult(null);

            return(newState == ConnectivityState.Ready);
        }
Exemple #24
0
 private void Autorization_Load(object sender, EventArgs e)
 {
     try
     {
         db = new ConnectContext((new ConfigJson()).StringConnecting());
     }
     catch
     {
         MessageBox.Show("Проверьте настройки подключения к серверу БД");
         (new Configuration()).Show();
     }
 }
Exemple #25
0
        public IHttpActionResult Get(DateTime dateFrom, DateTime to, string filter = null)
        {
            using (var context = new ConnectContext())
            {
                var documents = from document in context.GetAllDocuments(ConnectUser)
                                where document.Created.Date >= dateFrom.Date && document.Created.Date <= to.Date
                                where string.IsNullOrEmpty(filter) || (!string.IsNullOrEmpty(document.DepotName) && document.DepotName.ToUpper().Contains(filter.ToUpper()))
                                orderby document.Created descending
                                select new RecentCalibrationsViewModel(document, null);

                return(Ok(documents.ToList()));
            }
        }
        public async Task <IHttpActionResult> Post([FromBody] ChangePasswordViewModel data)
        {
            using (var context = new ConnectContext())
            {
                var result = await UserManager.ChangePasswordAsync(ConnectUser.Id, data.CurrentPassword, data.NewPassword);

                if (result.Succeeded)
                {
                    return(Ok());
                }
                return(BadRequest(string.Join(",", result.Errors)));
            }
        }
        public async Task <IHttpActionResult> GetUsers()
        {
            using (var context = new ConnectContext())
            {
                var users = context.Users.Where(u => u.Deleted == null)
                            .OrderBy(c => c.CompanyKey)
                            .Select(c => new ManageAccessUserViewModel {
                    Name = c.CompanyKey, Id = c.Id
                });

                return(Ok(await users.ToListAsync()));
            }
        }
        public IHttpActionResult Get(int userId, DateTime from, DateTime to)
        {
            if (userId == -1 && !User.IsInRole(ConnectRoles.Admin))
            {
                return(Unauthorized());
            }

            using (var context = new ConnectContext())
            {
                var data = context.CalibrationsDue(ConnectUser, userId, from, to);
                return(Ok(data));
            }
        }
Exemple #29
0
        public async Task <IHttpActionResult> Post(int userId)
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            using (var context = new ConnectContext())
            {
                var statusReportMap = await context.StatusReportMaps.FirstOrDefaultAsync(c => c.UserId == userId);

                if (statusReportMap == null)
                {
                    statusReportMap = new StatusReportMap
                    {
                        UserId = userId,
                        MapId  = Guid.NewGuid()
                    };
                    context.StatusReportMaps.Add(statusReportMap);
                    await context.SaveChangesAsync();
                }

                var root     = HttpContext.Current.Server.MapPath("~/StatusReportData");
                var provider = new MultipartFormDataStreamProvider(root);

                try
                {
                    await Request.Content.ReadAsMultipartAsync(provider);

                    foreach (var file in provider.FileData)
                    {
                        var finalDestination = HttpContext.Current.Server.MapPath("~/StatusReportData/" + statusReportMap.MapId.ToString().Replace("-", "") + "/" + DateTime.Now.Date.ToString("ddMMMyyyy"));
                        if (!Directory.Exists(finalDestination))
                        {
                            Directory.CreateDirectory(finalDestination);
                        }

                        var fileName = file.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
                        var data     = File.ReadAllBytes(file.LocalFileName);

                        File.WriteAllBytes(Path.Combine(finalDestination, fileName), data);
                    }
                    return(Ok());
                }
                catch (Exception ex)
                {
                    return(InternalServerError(ex));
                }
            }
        }
Exemple #30
0
 private void button_test_connection_Click(object sender, EventArgs e)
 {
     try
     {
         ConnectContext connect = new ConnectContext((new ConfigJson()).StringConnecting());
         connect.Database.Connection.Open();
         MessageBox.Show("Подключение установлено");
         connect.Database.Connection.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show("Ошибка: " + ex.Message);
     }
 }
Exemple #31
0
 public virtual void Connecting()
 {
     var context = new ConnectContext(this);
     GetScheduler().QueueWorkItem(((IReceiveSwitch)GetConfig("switch")).ReceiveSwitching(context), () =>
     {
         try
         {
             ((IChannelHandler)GetConfig("handler")).Connected(context);
         }
         catch (Exception e)
         {
             Log.Error("Connected Error", e);
         }
         BeginReceive();
     });
 }
Exemple #32
0
 public static extern ReturnValue Connect(ref ConnectContext ctx);