Exemplo n.º 1
0
        static async Task Main(string[] args)
        {
            Server server = null;

            try
            {
                server = new Server()
                {
                    Services = { GreetingService.BindService(new GreetingServiceImpl()),
                                 CalculatorService.BindService(new CalculatorServiceImpl()),
                                 CounterService.BindService(new CounterServiceImpl()),
                                 UploadService.BindService(new UploadServiceImpl()),
                                 ConversationService.BindService(new ConversationServiceImpl()) },
                    Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
                };

                server.Start();
                Console.WriteLine($"The server is listening on the port : {Port}");
                Console.ReadKey();
            }
            catch (IOException ex)
            {
                Console.WriteLine($"The server failed to start : {ex.Message}");
                throw;
            }
            finally
            {
                if (server != null)
                {
                    await server.ShutdownAsync();
                }
            }
        }
Exemplo n.º 2
0
        public void IncreaseCount_NotSurpassTen()
        {
            var context = new TestCountContext();
            var service = new CounterService(context);
            var count   = service.IncreaseCount();

            Assert.AreEqual(count, 1);
            count = service.IncreaseCount();
            Assert.AreEqual(count, 2);
            count = service.IncreaseCount();
            Assert.AreEqual(count, 3);
            count = service.IncreaseCount();
            Assert.AreEqual(count, 4);
            count = service.IncreaseCount();
            Assert.AreEqual(count, 5);
            count = service.IncreaseCount();
            Assert.AreEqual(count, 6);
            count = service.IncreaseCount();
            Assert.AreEqual(count, 7);
            count = service.IncreaseCount();
            Assert.AreEqual(count, 8);
            count = service.IncreaseCount();
            Assert.AreEqual(count, 9);
            count = service.IncreaseCount();
            Assert.AreEqual(count, 10);
            count = service.IncreaseCount();
            Assert.AreEqual(count, 10);
        }
Exemplo n.º 3
0
        public void Count_WrittenMethod_Test()
        {
            var words = new List <IRecord>
            {
                new Record {
                    Id = 1, Word = "Bob", UserReport = 1
                },
                new Record {
                    Id = 2, Word = "made", UserReport = 1
                },
                new Record {
                    Id = 3, Word = "abracadabra", UserReport = 5
                },
                new Record {
                    Id = 4, Word = "meany", UserReport = 2
                },
                new Record {
                    Id = 5, Word = "margeaux", UserReport = 2
                },
                new Record {
                    Id = 5, Word = "really", UserReport = 2
                },
            };
            var counterService = new CounterService();
            var target         = counterService.Count(words, ModelSelection.Written);


            Assert.True(target[0].WrittenMethodGuess == 1);
            Assert.True(target[1].WrittenMethodGuess == 1);
            Assert.True(target[2].WrittenMethodGuess == 5);
            Assert.True(target[3].WrittenMethodGuess == 2);
            Assert.True(target[4].WrittenMethodGuess == 2);
            Assert.True(target[5].WrittenMethodGuess == 2);
        }
Exemplo n.º 4
0
        static void InvocateCounterService(object counter)
        {
            CounterService counterService = counter as CounterService;

            while (true)
            {
                try
                {
                    Console.WriteLine($"{Thread.CurrentThread.Name.PadRight(10)}: The count is {counterService.GetCount()}");
                    Thread.Sleep(_invocationFrequency * 1000);
                }
                catch (Exception ex)
                {
                    if (Thread.CurrentThread.Name == "singleton")
                    {
                        Console.WriteLine($"Fail to invocate Singleton counter because {ex.Message}");
                        break;
                    }
                    if (Thread.CurrentThread.Name == "cao")
                    {
                        Console.WriteLine($"Fail to invocate cao counter because {ex.Message}");
                        break;
                    }
                }
            }
        }
Exemplo n.º 5
0
 public async Task Invoke(HttpContext httpContext,
                          ICounter counter,
                          CounterService counterService)
 {
     i++;
     httpContext.Response.ContentType = "text/html;charset=utf-8";
     await httpContext.Response.WriteAsync($"Запрос {i}; Counter: { counter.Value}; Service: { counterService.Counter.Value}");
 }
Exemplo n.º 6
0
        public void IncreaseCount_TestReset()
        {
            var context = new TestCountContext();
            var service = new CounterService(context);
            var reset   = service.ResetCount();

            Assert.AreEqual(reset, 0);
        }
Exemplo n.º 7
0
        public static void InitApp(String applicationId, String apiKey)
        {
            if (String.IsNullOrEmpty(applicationId))
            {
                throw new ArgumentNullException(ExceptionMessage.NULL_APPLICATION_ID);
            }

            if (String.IsNullOrEmpty(apiKey))
            {
                throw new ArgumentNullException(ExceptionMessage.NULL_SECRET_KEY);
            }

            Log.addLogger(Log.DEFAULTLOGGER, new ConsoleLogger());
            Log.startLogging(BACKENDLESSLOG);
#if WITHRT
            Quobject.EngineIoClientDotNet.Modules.LogManager.Enabled = !DeviceCheck.IsMobile;
#endif
            AppId  = applicationId;
            APIKey = apiKey;

            Persistence   = new PersistenceService();
            Data          = Persistence;
            Geo           = new GeoService();
            Messaging     = new MessagingService();
            Files         = new FileService();
            UserService   = new UserService();
            Events        = Events.GetInstance();
            Cache         = Cache.GetInstance();
            Counters      = CounterService.GetInstance();
            Logging       = new LoggingService();
            CustomService = new CustomService();

      #if WITHRT
            RT = new RTServiceImpl();
      #endif

            MessageWriter.DefaultWriter = new UnderflowWriter();
            MessageWriter.AddAdditionalTypeWriter(typeof(BackendlessUser), new BackendlessUserWriter());
            MessageWriter.AddAdditionalTypeWriter(typeof(Geometry), new BackendlessGeometryWriter());
            MessageWriter.AddAdditionalTypeWriter(typeof(Point), new BackendlessGeometryWriter());
            MessageWriter.AddAdditionalTypeWriter(typeof(LineString), new BackendlessGeometryWriter());
            MessageWriter.AddAdditionalTypeWriter(typeof(Polygon), new BackendlessGeometryWriter());
            ORBConfig.GetInstance().getObjectFactories().AddArgumentObjectFactory(typeof(BackendlessUser).FullName, new BackendlessUserFactory());
            ORBConfig.GetInstance().getObjectFactories().AddArgumentObjectFactory(typeof(GeometryDTO).FullName, new BackendlessGeometryFactory());
            ORBConfig.GetInstance().getObjectFactories().AddArgumentObjectFactory(typeof(Geometry).FullName, new BackendlessGeometryFactory());
            ORBConfig.GetInstance().getObjectFactories().AddArgumentObjectFactory(typeof(Point).FullName, new BackendlessGeometryFactory());
            ORBConfig.GetInstance().getObjectFactories().AddArgumentObjectFactory(typeof(LineString).FullName, new BackendlessGeometryFactory());
            ORBConfig.GetInstance().getObjectFactories().AddArgumentObjectFactory(typeof(Polygon).FullName, new BackendlessGeometryFactory());

            HeadersManager.CleanHeaders();
            LoginStorage loginStorage = new LoginStorage();

            if (loginStorage.HasData)
            {
                HeadersManager.GetInstance().AddHeader(HeadersEnum.USER_TOKEN_KEY, loginStorage.UserToken);
            }
        }
        public void SetUp()
        {
            var url    = new MongoUrl(ConfigurationManager.ConnectionStrings["system"].ConnectionString);
            var client = new MongoClient(url);

            _db = client.GetServer().GetDatabase(url.DatabaseName);
            _db.Drop();
            _service = new CounterService(_db);
        }
Exemplo n.º 9
0
        public MainWindow()
        {
            InitializeComponent();
            _counterService          = new CounterService();
            _counterText.DataContext = _counterService;
            var counterServiceCookie = CookieManager.Instance.CookieObject(_counterService);

            _browser.Address = "http://localhost:5000/counter/" + counterServiceCookie.ToString();
        }
Exemplo n.º 10
0
            public async Task <CounterState> UpdateAsync(
                ILiveState <CounterState> liveState, CancellationToken cancellationToken)
            {
                var counter = await CounterService.GetCounterAsync(cancellationToken);

                return(new CounterState()
                {
                    Counter = counter
                });
            }
Exemplo n.º 11
0
        public void SetUp()
        {
            var url    = new MongoUrl(ConfigurationManager.ConnectionStrings["system"].ConnectionString);
            var client = new MongoClient(url);

            _db         = client.GetDatabase(url.DatabaseName);
            _collection = _db.GetCollection <BsonDocument>("sysCounters");
            _service    = new CounterService(_db);
            _db.Drop();
        }
Exemplo n.º 12
0
        public void IncreaseCount_ByOne()
        {
            var context = new TestCountContext();
            var service = new CounterService(context);
            var count   = service.IncreaseCount();

            Assert.AreEqual(count, 1);
            count = service.IncreaseCount();
            Assert.AreEqual(count, 2);
        }
Exemplo n.º 13
0
        public async Task Consumption_Post_Once()
        {
            _consumptionRepository = new MockConsumptionRepository();
            _counterRepository     = new MockCounterRepository();
            _counterService        = new CounterService(_counterRepository, _consumptionRepository);
            _controller            = new CounterController(_counterService);

            var result = await _controller.CounterCallback(1, 244);

            var okResult = result.Should().BeOfType <OkResult>().Subject;
        }
        public async Task RetrieveAsyncGetsValue()
        {
            //arrange
            _repository.GetAsync().Returns(10);

            //act
            ICounterService service  = new CounterService(_repository);
            int             expected = await service.RetrieveAsync();

            //assert
            Assert.Equal(10, expected);
        }
        public async Task IncrementAsyncIncreasesValue()
        {
            //arrange
            _repository.GetAsync().Returns(10);

            //act
            ICounterService service = new CounterService(_repository);
            await service.IncrementAsync();

            //assert
            await _repository.Received(1).SetAsync(11);
        }
 public HomeController(
     IGreetingProvider configuration,
     IUsersService usersService,
     IHostingEnvironment env,
     CounterService counterService,
     ILogger <HomeController> logger)
 {
     this.configuration  = configuration;
     this.usersService   = usersService;
     this.env            = env;
     this.counterService = counterService;
     this.logger         = logger;
 }
Exemplo n.º 17
0
        /// <summary>
        /// 通过ClientSponsor来延长远程对象生命周期
        /// </summary>
        /// <param name="counter"></param>
        /// <returns></returns>
        static ISponsor ExtendLifetimeViaSponsor(object counter)
        {
            CounterService counterService = counter as CounterService;

            ILease lease = RemotingServices.GetLifetimeService(counterService) as ILease;

            //为Lease注册一个Sposnor,并把Renew时间设为4s
            ClientSponsor clientSponsor = new ClientSponsor(TimeSpan.FromSeconds(4));

            clientSponsor.Register(counterService);

            return(clientSponsor);
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            IDictionary dictionary = new Hashtable();

            dictionary["port"] = 0;

            BinaryClientFormatterSinkProvider clientFormatterSinkProvider;

            clientFormatterSinkProvider = new BinaryClientFormatterSinkProvider();

            BinaryServerFormatterSinkProvider serverFormatterSinkProvider;

            serverFormatterSinkProvider = new BinaryServerFormatterSinkProvider();
            serverFormatterSinkProvider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;

            IChannel channel = new TcpChannel(dictionary, clientFormatterSinkProvider, serverFormatterSinkProvider);

            ChannelServices.RegisterChannel(channel, false);

            Type   t   = typeof(CounterService);
            string url = "tcp://127.0.0.1:8501/RemoteLifeTimeMangement";

            RemotingConfiguration.RegisterActivatedClientType(t, url);
            CounterService caoCounter = new CounterService();

            CounterService singletonCounter = Activator.GetObject(t, "tcp://127.0.0.1:8501/RemoteLifeTimeMangement/Counter.rem") as CounterService;


            Thread caothread = new Thread(InvocateCounterService);

            caothread.Name = "cao";

            Thread singletonThread = new Thread(InvocateCounterService);

            singletonThread.Name = "singleton";

            caothread.Start(caoCounter);
            singletonThread.Start(singletonCounter);

            //Thread caoExtend = new Thread(ExtendLifetimeViaLease);
            //Thread singletonExtend = new Thread(ExtendLifetimeViaLease);

            //caoExtend.Start(caoCounter);
            //singletonExtend.Start(singletonCounter);

            //把该Sposnor负值给一个静态变量,这样不会被垃圾回收
            _singletonSponsor = ExtendLifetimeViaSponsor(singletonCounter);
            _caoSponsor       = ExtendLifetimeViaSponsor(caoCounter);

            Console.ReadLine();
        }
        public async Task GetCounters_Should_Succeed()
        {
            var mockResponse     = mockCountersResponse();
            var mockServiceAgent = Mock.Of <IServiceAgent>();

            Mock.Get(mockServiceAgent)
            .Setup(agent => agent.FetchCounters())
            .Returns(Task.FromResult(mockResponse));
            service = new CounterService(TestDoubles.Configuration, mockServiceAgent);

            var result = await service.GetCounters();

            Assert.IsTrue(result.DidSucceed);
        }
Exemplo n.º 20
0
        public void TryDecrementTest()
        {
            // Arrange
            CounterService counterService = new CounterService();
            int            expected       = 0;

            // Act
            bool isDecrement = counterService.TryDecrement();

            // Assert
            int actual = counterService.Counter;

            Assert.Equal(expected, actual);
            Assert.False(isDecrement);
        }
Exemplo n.º 21
0
        public async Task Counter_Get_One()
        {
            _consumptionRepository = new MockConsumptionRepository();
            _counterRepository     = new MockCounterRepository();
            _counterService        = new CounterService(_counterRepository, _consumptionRepository);
            _controller            = new CounterController(_counterService);

            var result = await _controller.Counter(1);

            // Assert
            var okResult = result.Should().BeOfType <OkObjectResult>().Subject;
            var subject  = okResult.Value.Should().BeAssignableTo <SlimCounterViewModel>().Subject;

            subject.Id.Should().Be("1");
            subject.VillageName.Should().Be("TestVillage1");
        }
Exemplo n.º 22
0
        public void TryIncrementTest()
        {
            // Arrange
            var counterService = new CounterService();
            var requestLimit   = 5;
            var expected       = counterService.Counter;

            expected += 1;

            // Act
            var isIncrement = counterService.TryIncrement(requestLimit);

            // Assert
            var actualResult = counterService.Counter;

            Assert.Equal(expected, actualResult);
            Assert.True(isIncrement);
        }
Exemplo n.º 23
0
        /// <summary>
        /// 采用延迟租约(Lease)的方式来延长远程对象生命周期
        /// </summary>
        /// <param name="counter"></param>
        static void ExtendLifetimeViaLease(object counter)
        {
            CounterService counterService = counter as CounterService;

            ILease lease = RemotingServices.GetLifetimeService(counterService) as ILease;

            while (true)
            {
                if (lease == null)
                {
                    Console.WriteLine("Can not retrieve the lease!");
                    break;
                }

                lease.Renew(TimeSpan.FromSeconds(_leaseRenewalFrequency));
                Thread.Sleep(_leaseRenewalFrequency * 950);
            }
        }
Exemplo n.º 24
0
        public static void InitApp(string applicationId, string apiKey)
        {
            if (string.IsNullOrEmpty(applicationId))
            {
                throw new ArgumentNullException(ExceptionMessage.NULL_APPLICATION_ID);
            }

            if (string.IsNullOrEmpty(apiKey))
            {
                throw new ArgumentNullException(ExceptionMessage.NULL_SECRET_KEY);
            }

            AppId  = applicationId;
            APIKey = apiKey;

            Persistence   = new PersistenceService();
            Data          = Persistence;
            Geo           = new GeoService();
            Messaging     = new MessagingService();
            Files         = new FileService();
            UserService   = new UserService();
            Events        = Events.GetInstance();
            Cache         = Cache.GetInstance();
            Counters      = CounterService.GetInstance();
            Logging       = new LoggingService();
            CustomService = new CustomService();

            MessageWriter.DefaultWriter = new UnderflowWriter();
            MessageWriter.AddAdditionalTypeWriter(typeof(BackendlessUser), new BackendlessUserWriter());
            ORBConfig.GetInstance().getObjectFactories().AddArgumentObjectFactory(typeof(BackendlessUser).FullName, new BackendlessUserFactory());

            HeadersManager.CleanHeaders();
            LoginStorage loginStorage = new LoginStorage();

            if (loginStorage.HasData)
            {
                HeadersManager.GetInstance().AddHeader(HeadersEnum.USER_TOKEN_KEY, loginStorage.UserToken);
            }
        }
Exemplo n.º 25
0
    public static void InitApp( string applicationId, string secretKey, string version )
    {
      if( string.IsNullOrEmpty( applicationId ) )
        throw new ArgumentNullException( ExceptionMessage.NULL_APPLICATION_ID );

      if( string.IsNullOrEmpty( secretKey ) )
        throw new ArgumentNullException(ExceptionMessage.NULL_SECRET_KEY);

      if( string.IsNullOrEmpty( version ) )
        throw new ArgumentNullException(ExceptionMessage.NULL_VERSION);

      AppId = applicationId;
      SecretKey = secretKey;
      VersionNum = version;

      Persistence = new PersistenceService();
      Data = Persistence;
      Geo = new GeoService();
      Messaging = new MessagingService();
      Files = new FileService();
      UserService = new UserService();
      Events = Events.GetInstance();
      Cache = Cache.GetInstance();
      Counters = CounterService.GetInstance();
      Logging = new LoggingService();
      CustomService = new CustomService();
      
      MessageWriter.DefaultWriter = new UnderflowWriter();
      MessageWriter.AddAdditionalTypeWriter( typeof( BackendlessUser ), new BackendlessUserWriter() );
      ORBConfig.GetInstance().getObjectFactories().AddArgumentObjectFactory( typeof( BackendlessUser ).FullName, new BackendlessUserFactory() );

      HeadersManager.CleanHeaders();
      LoginStorage loginStorage = new LoginStorage();

      if( loginStorage.HasData )
        HeadersManager.GetInstance().AddHeader( HeadersEnum.USER_TOKEN_KEY, loginStorage.UserToken );
    }
Exemplo n.º 26
0
        public async Task Counter_Report_All()
        {
            _consumptionRepository = new MockConsumptionRepository();
            _counterRepository     = new MockCounterRepository();
            _counterService        = new CounterService(_counterRepository, _consumptionRepository);
            _controller            = new CounterController(_counterService);

            await _controller.CounterCallback(1, 250);

            await _controller.CounterCallback(1, 240);

            await _controller.CounterCallback(2, 2444);

            var result = await _controller.ConsumptionReport("24");

            var okResult = result.Should().BeOfType <OkObjectResult>().Subject;

            var subject = okResult.Value.Should().BeAssignableTo <TotalVillageReportWrapperViewModel>().Subject;

            subject.Villages.Count().Should().Be(2);

            subject.Villages[0].Consumption.Should().Be(490);
            subject.Villages[1].Consumption.Should().Be(2444);
        }
Exemplo n.º 27
0
 public CounterSumService(CounterService counters) => Counters = counters;
Exemplo n.º 28
0
        public ActionResult Create(AgentViewModel AgentVm)
        {
            if (AgentVm.LedgerAccountGroupId == 0)
            {
                PrepareViewBag();
                return(View(AgentVm).Danger("Account Group field is required"));
            }

            if (_PersonService.CheckDuplicate(AgentVm.Name, AgentVm.Suffix, AgentVm.PersonId) == true)
            {
                PrepareViewBag();
                return(View(AgentVm).Danger("Combination of name and sufix is duplicate"));
            }


            if (ModelState.IsValid)
            {
                if (AgentVm.PersonId == 0)
                {
                    Person         person         = Mapper.Map <AgentViewModel, Person>(AgentVm);
                    BusinessEntity businessentity = Mapper.Map <AgentViewModel, BusinessEntity>(AgentVm);
                    Agent          Agent          = Mapper.Map <AgentViewModel, Agent>(AgentVm);
                    PersonAddress  personaddress  = Mapper.Map <AgentViewModel, PersonAddress>(AgentVm);
                    LedgerAccount  account        = Mapper.Map <AgentViewModel, LedgerAccount>(AgentVm);

                    person.CreatedDate  = DateTime.Now;
                    person.ModifiedDate = DateTime.Now;
                    person.CreatedBy    = User.Identity.Name;
                    person.ModifiedBy   = User.Identity.Name;
                    person.ObjectState  = Model.ObjectState.Added;
                    new PersonService(_unitOfWork).Create(person);

                    _BusinessEntityService.Create(businessentity);
                    _AgentService.Create(Agent);

                    personaddress.AddressType  = AddressTypeConstants.Work;
                    personaddress.CreatedDate  = DateTime.Now;
                    personaddress.ModifiedDate = DateTime.Now;
                    personaddress.CreatedBy    = User.Identity.Name;
                    personaddress.ModifiedBy   = User.Identity.Name;
                    personaddress.ObjectState  = Model.ObjectState.Added;
                    _PersonAddressService.Create(personaddress);


                    account.LedgerAccountName   = person.Name;
                    account.LedgerAccountSuffix = person.Suffix;
                    account.CreatedDate         = DateTime.Now;
                    account.ModifiedDate        = DateTime.Now;
                    account.CreatedBy           = User.Identity.Name;
                    account.ModifiedBy          = User.Identity.Name;
                    account.ObjectState         = Model.ObjectState.Added;
                    _AccountService.Create(account);


                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        return(View(AgentVm));
                    }


                    #region

                    //Saving Images if any uploaded after UnitOfWorkSave

                    if (Request.Files[0] != null && Request.Files[0].ContentLength > 0)
                    {
                        //For checking the first time if the folder exists or not-----------------------------
                        string uploadfolder;
                        int    MaxLimit;
                        int.TryParse(ConfigurationManager.AppSettings["MaxFileUploadLimit"], out MaxLimit);
                        var x = (from iid in db.Counter
                                 select iid).FirstOrDefault();
                        if (x == null)
                        {
                            uploadfolder = System.Guid.NewGuid().ToString();
                            Counter img = new Counter();
                            img.ImageFolderName = uploadfolder;
                            img.ModifiedBy      = User.Identity.Name;
                            img.CreatedBy       = User.Identity.Name;
                            img.ModifiedDate    = DateTime.Now;
                            img.CreatedDate     = DateTime.Now;
                            new CounterService(_unitOfWork).Create(img);
                            _unitOfWork.Save();
                        }

                        else
                        {
                            uploadfolder = x.ImageFolderName;
                        }


                        //For checking if the image contents length is greater than 100 then create a new folder------------------------------------

                        if (!Directory.Exists(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder)))
                        {
                            Directory.CreateDirectory(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder));
                        }

                        int count = Directory.GetFiles(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder)).Length;

                        if (count >= MaxLimit)
                        {
                            uploadfolder = System.Guid.NewGuid().ToString();
                            var u = new CounterService(_unitOfWork).Find(x.CounterId);
                            u.ImageFolderName = uploadfolder;
                            new CounterService(_unitOfWork).Update(u);
                            _unitOfWork.Save();
                        }


                        //Saving Thumbnails images:
                        Dictionary <string, string> versions = new Dictionary <string, string>();

                        //Define the versions to generate
                        versions.Add("_thumb", "maxwidth=100&maxheight=100");  //Crop to square thumbnail
                        versions.Add("_medium", "maxwidth=200&maxheight=200"); //Fit inside 400x400 area, jpeg

                        string temp2    = "";
                        string filename = System.Guid.NewGuid().ToString();
                        foreach (string filekey in System.Web.HttpContext.Current.Request.Files.Keys)
                        {
                            HttpPostedFile pfile = System.Web.HttpContext.Current.Request.Files[filekey];
                            if (pfile.ContentLength <= 0)
                            {
                                continue;                           //Skip unused file controls.
                            }
                            temp2 = Path.GetExtension(pfile.FileName);

                            string uploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder);
                            if (!Directory.Exists(uploadFolder))
                            {
                                Directory.CreateDirectory(uploadFolder);
                            }

                            string filecontent = Path.Combine(uploadFolder, AgentVm.Name + "_" + filename);

                            //pfile.SaveAs(filecontent);
                            ImageBuilder.Current.Build(new ImageJob(pfile, filecontent, new Instructions(), false, true));


                            //Generate each version
                            foreach (string suffix in versions.Keys)
                            {
                                if (suffix == "_thumb")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Thumbs");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, AgentVm.Name + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                                else if (suffix == "_medium")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Medium");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, AgentVm.Name + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                            }

                            //var tempsave = _FinishedProductService.Find(pt.ProductId);

                            person.ImageFileName   = AgentVm.Name + "_" + filename + temp2;
                            person.ImageFolderName = uploadfolder;
                            person.ObjectState     = Model.ObjectState.Modified;
                            _PersonService.Update(person);
                            _unitOfWork.Save();
                        }
                    }

                    #endregion



                    //return RedirectToAction("Create").Success("Data saved successfully");
                    return(RedirectToAction("Edit", new { id = person.PersonID }).Success("Data saved Successfully"));
                }
                else
                {
                    //string tempredirect = (Request["Redirect"].ToString());
                    Person         person         = Mapper.Map <AgentViewModel, Person>(AgentVm);
                    BusinessEntity businessentity = Mapper.Map <AgentViewModel, BusinessEntity>(AgentVm);
                    Agent          Agent          = Mapper.Map <AgentViewModel, Agent>(AgentVm);
                    PersonAddress  personaddress  = _PersonAddressService.Find(AgentVm.PersonAddressID);
                    LedgerAccount  account        = _AccountService.Find(AgentVm.AccountId);

                    StringBuilder logstring = new StringBuilder();

                    person.ModifiedDate = DateTime.Now;
                    person.ModifiedBy   = User.Identity.Name;
                    new PersonService(_unitOfWork).Update(person);


                    _BusinessEntityService.Update(businessentity);
                    _AgentService.Update(Agent);

                    personaddress.Address      = AgentVm.Address;
                    personaddress.CityId       = AgentVm.CityId;
                    personaddress.Zipcode      = AgentVm.Zipcode;
                    personaddress.ModifiedDate = DateTime.Now;
                    personaddress.ModifiedBy   = User.Identity.Name;
                    personaddress.ObjectState  = Model.ObjectState.Modified;
                    _PersonAddressService.Update(personaddress);

                    account.LedgerAccountName   = person.Name;
                    account.LedgerAccountSuffix = person.Suffix;
                    account.ModifiedDate        = DateTime.Now;
                    account.ModifiedBy          = User.Identity.Name;
                    _AccountService.Update(account);

                    ////Saving Activity Log::
                    ActivityLog al = new ActivityLog()
                    {
                        ActivityType = (int)ActivityTypeContants.Modified,
                        DocId        = AgentVm.PersonId,
                        Narration    = logstring.ToString(),
                        CreatedDate  = DateTime.Now,
                        CreatedBy    = User.Identity.Name,
                        //DocTypeId = new DocumentTypeService(_unitOfWork).FindByName(TransactionDocCategoryConstants.ProcessSequence).DocumentTypeId,
                    };
                    new ActivityLogService(_unitOfWork).Create(al);
                    //End of Saving ActivityLog

                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        return(View("Create", AgentVm));
                    }



                    #region

                    //Saving Image if file is uploaded
                    if (Request.Files[0] != null && Request.Files[0].ContentLength > 0)
                    {
                        string uploadfolder = AgentVm.ImageFolderName;
                        string tempfilename = AgentVm.ImageFileName;
                        if (uploadfolder == null)
                        {
                            var x = (from iid in db.Counter
                                     select iid).FirstOrDefault();
                            if (x == null)
                            {
                                uploadfolder = System.Guid.NewGuid().ToString();
                                Counter img = new Counter();
                                img.ImageFolderName = uploadfolder;
                                img.ModifiedBy      = User.Identity.Name;
                                img.CreatedBy       = User.Identity.Name;
                                img.ModifiedDate    = DateTime.Now;
                                img.CreatedDate     = DateTime.Now;
                                new CounterService(_unitOfWork).Create(img);
                                _unitOfWork.Save();
                            }
                            else
                            {
                                uploadfolder = x.ImageFolderName;
                            }
                        }
                        //Deleting Existing Images
                        //ConfigurationManager.AppSettings["PhysicalRDLCPath"] + uploadfolder + "/" + tempfilename;
                        var xtemp = System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename);
                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename));
                        }

                        //Deleting Thumbnail Image:

                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Thumbs/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Thumbs/" + tempfilename));
                        }

                        //Deleting Medium Image:
                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Medium/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Medium/" + tempfilename));
                        }

                        //Saving Thumbnails images:
                        Dictionary <string, string> versions = new Dictionary <string, string>();

                        //Define the versions to generate
                        versions.Add("_thumb", "maxwidth=100&maxheight=100");  //Crop to square thumbnail
                        versions.Add("_medium", "maxwidth=200&maxheight=200"); //Fit inside 400x400 area, jpeg

                        string temp2    = "";
                        string filename = System.Guid.NewGuid().ToString();
                        foreach (string filekey in System.Web.HttpContext.Current.Request.Files.Keys)
                        {
                            HttpPostedFile pfile = System.Web.HttpContext.Current.Request.Files[filekey];
                            if (pfile.ContentLength <= 0)
                            {
                                continue;                           //Skip unused file controls.
                            }
                            temp2 = Path.GetExtension(pfile.FileName);

                            string uploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder);
                            if (!Directory.Exists(uploadFolder))
                            {
                                Directory.CreateDirectory(uploadFolder);
                            }

                            string filecontent = Path.Combine(uploadFolder, AgentVm.Name + "_" + filename);

                            //pfile.SaveAs(filecontent);

                            ImageBuilder.Current.Build(new ImageJob(pfile, filecontent, new Instructions(), false, true));

                            //Generate each version
                            foreach (string suffix in versions.Keys)
                            {
                                if (suffix == "_thumb")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Thumbs");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, AgentVm.Name + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                                else if (suffix == "_medium")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Medium");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, AgentVm.Name + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                            }
                        }

                        person.ImageFileName   = person.Name + "_" + filename + temp2;
                        person.ImageFolderName = uploadfolder;
                        _PersonService.Update(person);
                        _unitOfWork.Save();
                    }

                    #endregion



                    return(RedirectToAction("Index").Success("Data saved successfully"));
                }
            }
            PrepareViewBag();
            return(View(AgentVm));
        }
Exemplo n.º 29
0
 public DashboardHub(CounterService counterService)
 {
     CounterService = counterService;
 }
Exemplo n.º 30
0
 public ViewController(IntPtr handle) : base(handle)
 {
     _service = new CounterService();
 }
Exemplo n.º 31
0
        public ActionResult Post(ProductType ptt)
        {
            if (ModelState.IsValid)
            {
                if (ptt.ProductTypeId <= 0)
                {
                    ProductType pt1 = new ProductType();
                    pt1.ProductNatureId = ptt.ProductNatureId;
                    pt1.ProductTypeName = ptt.ProductTypeName;
                    pt1.IsPostedInStock = ptt.IsPostedInStock;
                    pt1.CreatedDate     = DateTime.Now;
                    pt1.ModifiedDate    = DateTime.Now;
                    pt1.IsActive        = ptt.IsActive;
                    pt1.CreatedBy       = User.Identity.Name;
                    pt1.ModifiedBy      = User.Identity.Name;
                    pt1.ObjectState     = Model.ObjectState.Added;
                    var createdProductType = _ProductTypeService.Create(pt1);

                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        return(View("Create", ptt));
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId    = new DocumentTypeService(_unitOfWork).FindByName(MasterDocTypeConstants.ProductType).DocumentTypeId,
                        DocId        = pt1.ProductTypeId,
                        ActivityType = (int)ActivityTypeContants.Added,
                    }));

                    #region

                    //Saving Images if any uploaded after UnitOfWorkSave

                    if (Request.Files[0] != null && Request.Files[0].ContentLength > 0)
                    {
                        //For checking the first time if the folder exists or not-----------------------------
                        string uploadfolder;
                        int    MaxLimit;
                        int.TryParse(ConfigurationManager.AppSettings["MaxFileUploadLimit"], out MaxLimit);
                        var x = (from iid in db.Counter
                                 select iid).FirstOrDefault();
                        if (x == null)
                        {
                            uploadfolder = System.Guid.NewGuid().ToString();
                            Counter img = new Counter();
                            img.ImageFolderName = uploadfolder;
                            img.ModifiedBy      = User.Identity.Name;
                            img.CreatedBy       = User.Identity.Name;
                            img.ModifiedDate    = DateTime.Now;
                            img.CreatedDate     = DateTime.Now;
                            new CounterService(_unitOfWork).Create(img);
                            _unitOfWork.Save();
                        }

                        else
                        {
                            uploadfolder = x.ImageFolderName;
                        }


                        //For checking if the image contents length is greater than 100 then create a new folder------------------------------------

                        if (!Directory.Exists(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder)))
                        {
                            Directory.CreateDirectory(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder));
                        }

                        int count = Directory.GetFiles(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder)).Length;

                        if (count >= MaxLimit)
                        {
                            uploadfolder = System.Guid.NewGuid().ToString();
                            var u = new CounterService(_unitOfWork).Find(x.CounterId);
                            u.ImageFolderName = uploadfolder;
                            new CounterService(_unitOfWork).Update(u);
                            _unitOfWork.Save();
                        }


                        //Saving Thumbnails images:
                        Dictionary <string, string> versions = new Dictionary <string, string>();

                        //Define the versions to generate
                        versions.Add("_thumb", "maxwidth=100&maxheight=100");  //Crop to square thumbnail
                        versions.Add("_medium", "maxwidth=200&maxheight=200"); //Fit inside 400x400 area, jpeg

                        string temp2    = "";
                        string filename = System.Guid.NewGuid().ToString();
                        foreach (string filekey in System.Web.HttpContext.Current.Request.Files.Keys)
                        {
                            HttpPostedFile pfile = System.Web.HttpContext.Current.Request.Files[filekey];
                            if (pfile.ContentLength <= 0)
                            {
                                continue;                           //Skip unused file controls.
                            }
                            temp2 = Path.GetExtension(pfile.FileName);

                            string uploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder);
                            if (!Directory.Exists(uploadFolder))
                            {
                                Directory.CreateDirectory(uploadFolder);
                            }

                            string filecontent = Path.Combine(uploadFolder, pt1.ProductTypeName + "_" + filename);

                            //pfile.SaveAs(filecontent);
                            ImageBuilder.Current.Build(new ImageJob(pfile, filecontent, new Instructions(), false, true));


                            //Generate each version
                            foreach (string suffix in versions.Keys)
                            {
                                if (suffix == "_thumb")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Thumbs");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, pt1.ProductTypeName + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                                else if (suffix == "_medium")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Medium");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, pt1.ProductTypeName + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                            }

                            //var tempsave = _FinishedProductService.Find(pt.ProductId);

                            pt1.ImageFileName   = ptt.ProductTypeName + "_" + filename + temp2;
                            pt1.ImageFolderName = uploadfolder;
                            pt1.ObjectState     = Model.ObjectState.Modified;
                            _ProductTypeService.Update(pt1);
                            _unitOfWork.Save();
                        }
                    }

                    #endregion


                    return(RedirectToAction("Create").Success("Data saved successfully"));
                }

                else
                {
                    List <LogTypeViewModel> LogList = new List <LogTypeViewModel>();

                    ProductType temp = _ProductTypeService.Find(ptt.ProductTypeId);

                    ProductType ExRec = Mapper.Map <ProductType>(temp);

                    temp.ProductNatureId = ptt.ProductNatureId;
                    temp.ProductTypeName = ptt.ProductTypeName;
                    temp.IsPostedInStock = ptt.IsPostedInStock;
                    temp.IsActive        = ptt.IsActive;
                    temp.ModifiedDate    = DateTime.Now;
                    temp.ModifiedBy      = User.Identity.Name;
                    temp.ObjectState     = Model.ObjectState.Modified;
                    _ProductTypeService.Update(temp);

                    LogList.Add(new LogTypeViewModel
                    {
                        ExObj = ExRec,
                        Obj   = temp,
                    });
                    XElement Modifications = new ModificationsCheckService().CheckChanges(LogList);

                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        return(View("Create", ptt));
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId       = new DocumentTypeService(_unitOfWork).FindByName(MasterDocTypeConstants.ProductType).DocumentTypeId,
                        DocId           = temp.ProductTypeId,
                        ActivityType    = (int)ActivityTypeContants.Modified,
                        xEModifications = Modifications,
                    }));

                    #region

                    //Saving Image if file is uploaded
                    if (Request.Files[0] != null && Request.Files[0].ContentLength > 0)
                    {
                        string uploadfolder = temp.ImageFolderName;
                        string tempfilename = temp.ImageFileName;
                        if (uploadfolder == null)
                        {
                            var x = (from iid in db.Counter
                                     select iid).FirstOrDefault();
                            if (x == null)
                            {
                                uploadfolder = System.Guid.NewGuid().ToString();
                                Counter img = new Counter();
                                img.ImageFolderName = uploadfolder;
                                img.ModifiedBy      = User.Identity.Name;
                                img.CreatedBy       = User.Identity.Name;
                                img.ModifiedDate    = DateTime.Now;
                                img.CreatedDate     = DateTime.Now;
                                new CounterService(_unitOfWork).Create(img);
                                _unitOfWork.Save();
                            }
                            else
                            {
                                uploadfolder = x.ImageFolderName;
                            }
                        }
                        //Deleting Existing Images

                        var xtemp = System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename);
                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename));
                        }

                        //Deleting Thumbnail Image:

                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Thumbs/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Thumbs/" + tempfilename));
                        }

                        //Deleting Medium Image:
                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Medium/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Medium/" + tempfilename));
                        }

                        //Saving Thumbnails images:
                        Dictionary <string, string> versions = new Dictionary <string, string>();

                        //Define the versions to generate
                        versions.Add("_thumb", "maxwidth=100&maxheight=100");  //Crop to square thumbnail
                        versions.Add("_medium", "maxwidth=200&maxheight=200"); //Fit inside 400x400 area, jpeg

                        string temp2    = "";
                        string filename = System.Guid.NewGuid().ToString();
                        foreach (string filekey in System.Web.HttpContext.Current.Request.Files.Keys)
                        {
                            HttpPostedFile pfile = System.Web.HttpContext.Current.Request.Files[filekey];
                            if (pfile.ContentLength <= 0)
                            {
                                continue;                           //Skip unused file controls.
                            }
                            temp2 = Path.GetExtension(pfile.FileName);

                            string uploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder);
                            if (!Directory.Exists(uploadFolder))
                            {
                                Directory.CreateDirectory(uploadFolder);
                            }

                            string filecontent = Path.Combine(uploadFolder, temp.ProductTypeName + "_" + filename);

                            //pfile.SaveAs(filecontent);

                            ImageBuilder.Current.Build(new ImageJob(pfile, filecontent, new Instructions(), false, true));

                            //Generate each version
                            foreach (string suffix in versions.Keys)
                            {
                                if (suffix == "_thumb")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Thumbs");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, temp.ProductTypeName + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                                else if (suffix == "_medium")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Medium");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, temp.ProductTypeName + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                            }
                        }
                        var temsave = _ProductTypeService.Find(temp.ProductTypeId);
                        temsave.ImageFileName   = temsave.ProductTypeName + "_" + filename + temp2;
                        temsave.ImageFolderName = uploadfolder;
                        _ProductTypeService.Update(temsave);
                        _unitOfWork.Save();
                    }

                    #endregion


                    return(RedirectToAction("Index").Success("Data saved successfully"));
                }
            }
            PrepareViewBag();
            return(View("Create", ptt));
        }