public RouteService(IAppServiceRepository svcRepo, RequestContext context, RouteCollection routes, ILogService logger)
 {
   AppService = svcRepo.GetService();
   Routes = routes;
   Context = context;
   LogService = logger;
 }
 private void RefreshGrid()
 {
     var svc = new AppService();
     var contacts = svc.GetContacts();
     ContactsGridView.DataSource = contacts;
     ContactsGridView.DataBind();
 }
 public virtual AppService UpdateService(AppService appService)
 {
   LogService.Info("AtomPubService.UpdateService");
   AuthorizeService.Auth(Scope.EntireSite, AuthAction.UpdateServiceDoc);
   //TODO: combine with existing service doc based on authorization rules
   //OnUpdateService(appService);
   return AppServiceRepository.UpdateService(appService);
 }
 protected void Page_Init(object sender, EventArgs e)
 {
     var svc = new AppService();
     var message = svc.GetSiteSettings();
     if (!String.IsNullOrEmpty(message.SiteHeaderMessage))
     {
         AlertLabel.Visible = true;
         AlertLabel.Text = message.SiteHeaderMessage;
     }
 }
 public IEnumerable<DiaryFixture> Get(string ageGroup)
 {
     AgeGroup ag = (AgeGroup)Enum.Parse(typeof(AgeGroup), ageGroup.ToUpper());
     var svc = new AppService();
     if (ag == AgeGroup.SENIOR)
     {
         return svc.GetAgeGroupDiaryNew(ag);
     }
     return svc.GetAgeGroupDiary(ag);
 }
        public AppService UpdateService(AppService service)
        {

            if (service == null)
            {
                throw new ArgumentException("service");
            }

            this.appService = service;
            return this.appService;
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         AppService svc = new AppService();
         var settings = svc.GetSiteSettings();
         if (settings != null && !String.IsNullOrEmpty(settings.SiteHeaderMessage))
         {
             MessageTextBox.Text = settings.SiteHeaderMessage;
         }
     }
 }
        public void CreateWithAdminsAppServiceTest()
        {
            AppService appService = new AppService()
                {
                  Admins = Enumerable.Repeat<string>("admin", 4)
                };

            Assert.IsNotNull(appService);
            Assert.IsNotNull(appService.Admins);
            Assert.AreEqual(4, appService.Admins.Count());

        }
    /// <summary>
    /// Determines dynamically the collection, workspace, entry, and theme
    /// for the current request.
    /// </summary>
    /// <param name="ctx"></param>
    protected override void Execute(RequestContext ctx)
    {
      IContainer container = (IContainer)ctx.HttpContext.Application["Container"];
      appService = container.GetInstance<IAppServiceRepository>().GetService();
      LogService = container.GetInstance<ILogService>();
      AuthorizeService = container.GetInstance<IAuthorizeService>();
      //determine resource context based on routing data
      IRouteService r = RouteService.GetCurrent(ctx);
      if (EntryId == null) EntryId = r.GetEntryId();
      Scope = r.GetScope();
      base.Execute(ctx);

    }
    public AnnotateService(IContainer container, IAtomPubService atompub, IAppServiceRepository svcRepo, IAuthorizeService auth,
      IAtomEntryRepository entryRepo, IMediaRepository mediaRepo, ILogService logger)
    {
      AppService = svcRepo.GetService();
      AtomPubService = atompub;
      AuthorizeService = auth;
      AtomEntryRepository = entryRepo;
      MediaRepository = mediaRepo;
      Container = container;
      LogService = logger;

      atompub.SettingEntryLinks += (e) => SetLinks(e);
      atompub.SettingFeedLinks += (f) => SetLinks(f);
    }
    protected void SaveButton_Click(object sender, EventArgs e)
    {
        var svc = new AppService();
        int contactId = Int32.Parse(Request["id"]);

        var agegroup = AgeGroupTextBox.Text ;
        var title = TitleTextBox.Text    ;
        var photo = PhotoTextBox.Text    ;
        var name = NameTextBox.Text     ;
        var phone = PhoneTextBox.Text;
        var email = EmailTextBox.Text;

        svc.UpdateContact(contactId, agegroup, title, photo, name, phone, email);

        Response.Redirect("Contacts.aspx");
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var svc = new AppService();
            int contactId = Int32.Parse(Request["id"]);
            var contact = svc.GetContact(contactId);

            ContactLabel.Text = contact.ContactId.ToString();
            AgeGroupTextBox.Text = contact.AgeGroup;
            TitleTextBox.Text = contact.Title;
            PhotoTextBox.Text = contact.Photo;
            NameTextBox.Text = contact.Name;
            PhoneTextBox.Text = contact.Phone;
            EmailTextBox.Text = contact.Email;

        }
    }
 public BlogService(IAtomPubService atompub, IAnnotateService annotate,
   IAppServiceRepository svcRepo, IContainer container,
     IAtomEntryRepository entryRepo, IAuthorizeService auth, ILogService logger,
   ICleanContentService cleaner)
 {
   this.AppService = svcRepo.GetService();
   this.AppServiceRepository = svcRepo;
   this.AtomEntryRepository = entryRepo;
   this.Container = container;
   this.AnnotateService = annotate;
   this.AuthorizeService = auth;
   this.LogService = logger;
   this.CleanContentService = cleaner;
   atompub.CreatingEntry += OnModifyEntry;
   atompub.UpdatingEntry += OnModifyEntry;
   annotate.AnnotatingEntry += OnAnnotateEntry;
   atompub.SettingEntryLinks += (e) => SetLinks(e);
   atompub.SettingFeedLinks += (f) => SetLinks(f);
 }
        public void FullCreateAppServiceTest()
        {
            AppService appService = new AppService()
                {
                  //TODO: Admins = new List<AtomPerson>(),
                    DefaultSubdomain = "foo",
                    //Domain = "aDomain",
                    Lang = "EN",
                    Secure = false,
                    ServiceType = ServiceType.Single,
                    Workspaces = new List<AppWorkspace>()
                };


            Assert.IsNotNull(appService);
            Assert.IsNotNull(appService.Admins);
            Assert.AreEqual(0, appService.Admins.Count());

            Assert.IsNotNull(appService.Workspaces);
            Assert.AreEqual("foo", appService.DefaultSubdomain);
            Assert.AreEqual("EN", appService.Lang);
            Assert.AreEqual(false, appService.Secure);
            Assert.AreEqual(ServiceType.Single, appService.ServiceType);
        }
Exemple #15
0
        public override void OnLoad()
        {
            base.OnLoad();

            //系统模块编码

            ReportService report_fxsc = (ReportService)this.dw_fxsc.Services.Add(ServiceName.Report);

            report_fxsc.RequestorDrawTitle = false;
            ReportService report_thyc = (ReportService)this.dw_thyc.Services.Add(ServiceName.Report);

            report_thyc.RequestorDrawTitle = false;
            ReportService report_bgyc = (ReportService)this.dw_thsc.Services.Add(ServiceName.Report);

            report_bgyc.RequestorDrawTitle = false;
            ReportService report_bjyc = (ReportService)this.dw_wxqk.Services.Add(ServiceName.Report);

            report_bjyc.RequestorDrawTitle = false;
            ReportService report_tgyc = (ReportService)this.dw_tgyc.Services.Add(ServiceName.Report);

            report_tgyc.RequestorDrawTitle = false;
            ReportService report_fxyc = (ReportService)this.dw_fxyc.Services.Add(ServiceName.Report);

            report_fxyc.RequestorDrawTitle = false;
            ReportService report_bjtgyc = (ReportService)this.dw_bjtgyc.Services.Add(ServiceName.Report);

            report_bjtgyc.RequestorDrawTitle = false;
            ReportService report_gjyc = (ReportService)this.dw_gjyc.Services.Add(ServiceName.Report);

            report_gjyc.RequestorDrawTitle = false;
            ReportService report_hdyc = (ReportService)this.dw_hdyc.Services.Add(ServiceName.Report);

            report_hdyc.RequestorDrawTitle = false;
            ReportService report_bjhthcq = (ReportService)this.dw_bjhthcq.Services.Add(ServiceName.Report);

            report_bjhthcq.RequestorDrawTitle = false;
            var userid    = AppService.GetUserID();
            var username  = AppService.GetUserName();
            var ShareMode = AppService.GetShareMode();
            var Dlwtf     = AppService.GetDlwtf();
            var Tybm      = AppService.GetTybm();
            var Sfqytybm  = AppService.GetSfqytybm();

            this.SetParm("userid", userid);
            this.SetParm("username", username);
            this.SetParm("ShareMode", ShareMode);
            this.SetParm("Dlwtf", Dlwtf);
            this.SetParm("Tybm", Tybm);
            this.SetParm("Sfqytybm", Sfqytybm);

            // 数据分页检索,必须在数据检索之前设置
            //this.dw_list.PageSize = 50;   //每页检索50条记录


            this.ds_1.DataWindowObject = "d_sys_modules_all";
            this.ds_1.Retrieve();

            var      node   = "000158";
            var      li_row = this.ds_1.FindRow("id='" + node + "'", 1, this.ds_1.RowCount);
            DateTime date   = System.DateTime.Now.AddDays(-30);

            this.dp_begin.Value = date;

            //接单人
            this.ds_2.DataWindowObject = "dd_jdr_list";
            this.ds_2.Retrieve();
            ddlb_jdr.Items.Add("全部");
            for (int row = 1; row <= this.ds_2.RowCount; row++)
            {
                var ctr_area2 = this.ds_2.GetItemString(row, "jdrjc");
                ddlb_jdr.Items.Add(ctr_area2);
            }

            // 数据检索
            this.dw_fxsc.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()), "全部");
            this.dw_thyc.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()), "全部");
            this.dw_thsc.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()), "全部");
            this.dw_wxqk.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()), "全部");
            this.dw_tgyc.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()), "全部");
            this.dw_fxyc.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()), "全部");
            this.dw_bjtgyc.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()), "全部");
            this.dw_gjyc.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()), "全部");
            this.dw_hdyc.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()), "全部");
            this.dw_bjhthcq.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()), "全部");
            this.dw_mtsjthyc.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()), "全部");
            //this.dw_wdqk.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()), Dlwtf, "单证");
            //this.dw_gqdjyd.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()), Dlwtf, "单证");

            //注册相关的js文件
            this.RegisterClientScriptInclude("ExtPB_Demo", "/Beta3/ExtPB_Demo.js");
            this.RegisterClientScriptInclude("W_HddzList_Hyycgz", "/Hddz/W_HddzList_Hyycgz.win.js");
            this.RegisterClientScriptInclude("W_Wldw_htjhthsj_Select", "/Xt_Popwin/W_Wldw_htjhthsj_Select.win.js");
            this.RegisterClientScriptInclude("W_Hddz_Ycyy", "/Hddz/W_Hddz_Ycyy.win.js");
            this.RegisterClientScriptInclude("W_Filter", "/Hddz/W_Filter.win.js");

            //注册需要使用的弹出窗口的事件处理程序的JS文件
            this.RegisterClientScriptInclude("W_Index", "W_Index.win.js");
            AjaxPro.Utility.RegisterTypeForAjax(typeof(PubMethod));
        }
 public CallScriptService(AppDbContext db, AppService appService) : base(db, appService)
 {
 }
 protected void RemoveButton_Click(object sender, EventArgs e)
 {
     MessageTextBox.Text = String.Empty;
     AppService svc = new AppService();
     svc.ClearSiteMessage();
 }
        // ARM
        public async Task<ResourceGroup> ActivateWebApp(WebsiteTemplate template, TryWebsitesIdentity userIdentity, string anonymousUserName, AppService temp = AppService.Web)
        {
            // Start site specific stuff
            var deploymentType = template != null && template.GithubRepo != null
                ? DeploymentType.GitWithCsmDeploy
                : DeploymentType.ZipDeploy;
            return await ActivateResourceGroup(userIdentity, temp, deploymentType, async (resourceGroup, inProgressOperation) =>
                {
                    SimpleTrace.Analytics.Information(AnalyticsEvents.UserCreatedSiteWithLanguageAndTemplateName,
                        userIdentity, template, resourceGroup.CsmId);
                    SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}; {5}; {6}",
                            AnalyticsEvents.OldUserCreatedSiteWithLanguageAndTemplateName, userIdentity.Name,
                            template.Language, template.Name, resourceGroup.ResourceUniqueId, temp.ToString(), anonymousUserName);

                    var site = resourceGroup.Sites.First(s => s.IsSimpleWAWSOriginalSite);
                    var rbacTask = resourceGroup.AddResourceGroupRbac(userIdentity.Puid, userIdentity.Email);
                    if (template != null && template.FileName != null)
                    {
                        var credentials = new NetworkCredential(site.PublishingUserName, site.PublishingPassword);
                        var zipManager = new RemoteZipManager(site.ScmUrl + "zip/", credentials, retryCount: 3);
                        Task zipUpload = zipManager.PutZipFileAsync("site/wwwroot", template.GetFullPath());
                        var vfsManager = new RemoteVfsManager(site.ScmUrl + "vfs/", credentials, retryCount: 3);
                        Task deleteHostingStart = vfsManager.Delete("site/wwwroot/hostingstart.html");
                        await Task.WhenAll(zipUpload, deleteHostingStart);
                    }
                    else if (template != null && template.GithubRepo != null)
                    {
                        Uri githubRepo;
                        var validUri = Uri.TryCreate(template.GithubRepo, UriKind.Absolute, out githubRepo);
                        if (validUri && (githubRepo.AbsoluteUri.StartsWith("https://github.com/davidebbo-test/") || githubRepo.AbsoluteUri.StartsWith("https://github.com/ahmelsayed-test")))
                        {
                            //Do CSM template deployment
                            var csmTemplate = new CsmTemplateWrapper
                            {
                                properties = new CsmTemplateProperties
                                {
                                    mode = "Incremental",
                                    parameters = new
                                    {
                                        siteName = new CsmTemplateParameter(site.SiteName),
                                        hostingPlanName = new CsmTemplateParameter(resourceGroup.ServerFarms.Select(sf => sf.ServerFarmName).FirstOrDefault()),
                                        repoUrl = new CsmTemplateParameter(githubRepo.AbsoluteUri)
                                    },
                                    templateLink = new CsmTemplateLink
                                    {
                                        contentVersion = "1.0.0.0",
                                        uri = new Uri("https://raw.githubusercontent.com/" + githubRepo.AbsolutePath.Trim('/') + "/master/azuredeploy.json")
                                    }
                                }
                            };
                            await inProgressOperation.CreateDeployment(csmTemplate, block: true);
                            await site.GetKuduDeploymentStatus(block: true);
                            await resourceGroup.Load();
                        }
                        else if (validUri && githubRepo.AbsoluteUri.StartsWith("https://github.com/"))
                        {
                            //Do Kudu deployment
                            throw new InvalidGithubRepoException();
                        }
                        else
                        {
                            throw new InvalidGithubRepoException();
                        }
                    }
                    site.AppSettings["LAST_MODIFIED_TIME_UTC"] = DateTime.UtcNow.ToString("u");
                    site.AppSettings["SITE_LIFE_TIME_IN_MINUTES"] = SimpleSettings.SiteExpiryMinutes;
                    site.AppSettings["MONACO_EXTENSION_VERSION"] = "beta";
                    site.AppSettings["WEBSITE_TRY_MODE"] = "1";

                    if (template.Name.Equals("ASP.NET + Azure Search Site", StringComparison.OrdinalIgnoreCase))
                    {
                        site.AppSettings["SearchServiceName"] = SimpleSettings.SearchServiceName;
                        site.AppSettings["SearchServiceApiKey"] = AzureSearchHelper.GetApiKey();
                    }
                    else if (template.Name.Equals("PHP Starter Site", StringComparison.OrdinalIgnoreCase))
                    {
                        //Enable ZRay
                        await site.EnableZRay(resourceGroup.GeoRegion);
                    }

                    await site.UpdateAppSettings();

                    if (template.GithubRepo == null)
                    {
                        await site.UpdateConfig(new { properties = new { scmType = "LocalGit", httpLoggingEnabled = true } });
                    }

                    resourceGroup.IsRbacEnabled = await rbacTask;
                    site.FireAndForget();
                    return resourceGroup;
                });
        }
        // ARM
        public async Task <ResourceGroup> ActivateWebApp(BaseTemplate template, TryWebsitesIdentity userIdentity, string anonymousUserName, AppService temp = AppService.Web)
        {
            // Start site specific stuff
            var deploymentType = template != null && template.GithubRepo != null
                ? DeploymentType.GitWithCsmDeploy
                : DeploymentType.ZipDeploy;

            return(await ActivateResourceGroup(userIdentity, temp, deploymentType, async (resourceGroup, inProgressOperation) => {
                SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}; ",
                                             AnalyticsEvents.OldUserCreatedSiteWithLanguageAndTemplateName, "NA", template.Name, resourceGroup.ResourceUniqueId, temp.ToString());

                var site = resourceGroup.Sites.First(s => s.IsSimpleWAWSOriginalSite);
                var rbacTask = resourceGroup.AddResourceGroupRbac(userIdentity.Puid, userIdentity.Email);
                if (template != null && template.FileName != null)
                {
                    var credentials = new NetworkCredential(site.PublishingUserName, site.PublishingPassword);
                    var zipManager = new RemoteZipManager(site.ScmUrl + "zip/", credentials, retryCount: 3);
                    Task zipUpload = zipManager.PutZipFileAsync("site/wwwroot", template.GetFullPath());

                    var vfsSCMManager = new RemoteVfsManager(site.ScmUrl + "vfs/", credentials, retryCount: 3);
                    Task scmRedirectUpload = vfsSCMManager.Put("site/applicationHost.xdt", Path.Combine(HostingEnvironment.MapPath(@"~/App_Data"), "applicationHost.xdt"));

                    var vfsManager = new RemoteVfsManager(site.ScmUrl + "vfs/", credentials, retryCount: 3);
                    Task deleteHostingStart = vfsManager.Delete("site/wwwroot/hostingstart.html");

                    await Task.WhenAll(zipUpload, scmRedirectUpload, deleteHostingStart);
                }
                else if (template != null && template.GithubRepo != null)
                {
                    Uri githubRepo;
                    var validUri = Uri.TryCreate(template.GithubRepo, UriKind.Absolute, out githubRepo);
                    if (validUri && (githubRepo.AbsoluteUri.StartsWith("https://github.com/davidebbo-test/") || githubRepo.AbsoluteUri.StartsWith("https://github.com/ahmelsayed-test")))
                    {
                        //Do CSM template deployment
                        var csmTemplate = new CsmTemplateWrapper
                        {
                            properties = new CsmTemplateProperties
                            {
                                mode = "Incremental",
                                parameters = new
                                {
                                    siteName = new CsmTemplateParameter(site.SiteName),
                                    hostingPlanName = new CsmTemplateParameter(resourceGroup.ServerFarms.Select(sf => sf.ServerFarmName).FirstOrDefault()),
                                    repoUrl = new CsmTemplateParameter(githubRepo.AbsoluteUri)
                                },
                                templateLink = new CsmTemplateLink
                                {
                                    contentVersion = "1.0.0.0",
                                    uri = new Uri("https://raw.githubusercontent.com/" + githubRepo.AbsolutePath.Trim('/') + "/master/azuredeploy.json")
                                }
                            }
                        };
                        await inProgressOperation.CreateDeployment(csmTemplate, block: true, subscriptionType: resourceGroup.SubscriptionType);
                        await site.GetKuduDeploymentStatus(block: true);
                        await resourceGroup.Load();
                    }
                    else if (validUri && githubRepo.AbsoluteUri.StartsWith("https://github.com/"))
                    {
                        //Do Kudu deployment
                        throw new InvalidGithubRepoException();
                    }
                    else
                    {
                        throw new InvalidGithubRepoException();
                    }
                }
                resourceGroup.Tags[Constants.TemplateName] = template.Name;
                site.AppSettings["LAST_MODIFIED_TIME_UTC"] = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture);
                site.AppSettings["WEBSITE_TRY_MODE"] = "1";
                if (site.SubscriptionType != SubscriptionType.VSCodeLinux)
                {
                    site.AppSettings["SITE_LIFE_TIME_IN_MINUTES"] = SimpleSettings.SiteExpiryMinutes;
                }
                if (site.AppSettings.ContainsKey("FUNCTIONS_EXTENSION_VERSION"))
                {
                    site.AppSettings.Remove("FUNCTIONS_EXTENSION_VERSION");
                }

                if (template.Name.Equals("ASP.NET with Azure Search Site", StringComparison.OrdinalIgnoreCase))
                {
                    site.AppSettings["SearchServiceName"] = SimpleSettings.SearchServiceName;
                    site.AppSettings["SearchServiceApiKey"] = AzureSearchHelper.GetApiKey();
                }

                await Task.WhenAll(site.UpdateAppSettings(), resourceGroup.Update());

                if (template.GithubRepo == null)
                {
                    if (site.IsFunctionsContainer)
                    {
                        await site.UpdateConfig(new { properties = new { scmType = "None", httpLoggingEnabled = true } });
                    }
                    else if (template.Name.Equals("WordPress", StringComparison.OrdinalIgnoreCase))
                    {
                        await site.UpdateConfig(new { properties = new { scmType = "LocalGit", httpLoggingEnabled = true, localMySqlEnabled = true } });
                    }
                    else
                    {
                        await site.UpdateConfig(new { properties = new { scmType = "LocalGit", httpLoggingEnabled = true } });
                    }
                }

                resourceGroup.IsRbacEnabled = await rbacTask;
                Util.WarmUpSite(site);
                return resourceGroup;
            }));
        }
 public void SimpleCreateAppServiceTest()
 {
     AppService appService = new AppService();
     Assert.IsNotNull(appService);
 }
Exemple #21
0
 public static Ice.DispatchStatus del_blacklist_member___(AppService obj__, IceInternal.Incoming inS__, Ice.Current current__)
 {
     Ice.ObjectImpl.checkMode__(Ice.OperationMode.Normal, current__.mode);
     IceInternal.BasicStream is__ = inS__.startReadParams();
     string cellphone;
     cellphone = is__.readString();
     inS__.endReadParams();
     try
     {
         int ret__ = obj__.del_blacklist_member(cellphone, current__);
         IceInternal.BasicStream os__ = inS__.startWriteParams__(Ice.FormatType.DefaultFormat);
         os__.writeInt(ret__);
         inS__.endWriteParams__(true);
         return Ice.DispatchStatus.DispatchOK;
     }
     catch(minie.irpc.GenericError ex__)
     {
         inS__.writeUserException__(ex__, Ice.FormatType.DefaultFormat);
         return Ice.DispatchStatus.DispatchUserException;
     }
 }
        protected override async Task ProcessEvent(object evt, CancellationToken cancellationToken)
        {
            if (evt is UpdateAppInventory updateAppInventory)
            {
                //get all apps that were tagged that have manageable inventory that has an item that matches the item code in the invoice
                var apps = (await _appService.GetApps(updateAppInventory.AppId)).Select(data =>
                {
                    switch (Enum.Parse <AppType>(data.AppType))
                    {
                    case AppType.PointOfSale:
                        var possettings = data.GetSettings <PointOfSaleSettings>();
                        return(Data: data, Settings: (object)possettings,
                               Items: _appService.Parse(possettings.Template, possettings.Currency));

                    case AppType.Crowdfund:
                        var cfsettings = data.GetSettings <CrowdfundSettings>();
                        return(Data: data, Settings: (object)cfsettings,
                               Items: _appService.Parse(cfsettings.PerksTemplate, cfsettings.TargetCurrency));

                    default:
                        return(null, null, null);
                    }
                }).Where(tuple => tuple.Data != null && tuple.Items.Any(item =>
                                                                        item.Inventory.HasValue &&
                                                                        updateAppInventory.Items.ContainsKey(item.Id)));
                foreach (var valueTuple in apps)
                {
                    foreach (var item1 in valueTuple.Items.Where(item =>
                                                                 updateAppInventory.Items.ContainsKey(item.Id)))
                    {
                        if (updateAppInventory.Deduct)
                        {
                            item1.Inventory -= updateAppInventory.Items[item1.Id];
                        }
                        else
                        {
                            item1.Inventory += updateAppInventory.Items[item1.Id];
                        }
                    }

                    switch (Enum.Parse <AppType>(valueTuple.Data.AppType))
                    {
                    case AppType.PointOfSale:

                        ((PointOfSaleSettings)valueTuple.Settings).Template =
                            _appService.SerializeTemplate(valueTuple.Items);
                        break;

                    case AppType.Crowdfund:
                        ((CrowdfundSettings)valueTuple.Settings).PerksTemplate =
                            _appService.SerializeTemplate(valueTuple.Items);
                        break;

                    default:
                        throw new InvalidOperationException();
                    }

                    valueTuple.Data.SetSettings(valueTuple.Settings);
                    await _appService.UpdateOrCreateApp(valueTuple.Data);
                }
            }
            else if (evt is InvoiceEvent invoiceEvent)
            {
                Dictionary <string, int> cartItems = null;
                bool deduct;
                switch (invoiceEvent.Name)
                {
                case InvoiceEvent.Expired:

                case InvoiceEvent.MarkedInvalid:
                    deduct = false;
                    break;

                case InvoiceEvent.Created:
                    deduct = true;
                    break;

                default:
                    return;
                }

                if ((!string.IsNullOrEmpty(invoiceEvent.Invoice.Metadata.ItemCode) ||
                     AppService.TryParsePosCartItems(invoiceEvent.Invoice.Metadata.PosData, out cartItems)))
                {
                    var appIds = AppService.GetAppInternalTags(invoiceEvent.Invoice);

                    if (!appIds.Any())
                    {
                        return;
                    }

                    var items = cartItems ?? new Dictionary <string, int>();
                    if (!string.IsNullOrEmpty(invoiceEvent.Invoice.Metadata.ItemCode))
                    {
                        items.TryAdd(invoiceEvent.Invoice.Metadata.ItemCode, 1);
                    }

                    _eventAggregator.Publish(new UpdateAppInventory()
                    {
                        Deduct = deduct,
                        Items  = items,
                        AppId  = appIds
                    });
                }
            }
        }
 public AppInventoryUpdaterHostedService(EventAggregator eventAggregator, AppService appService, Logs logs) : base(eventAggregator, logs)
 {
     _eventAggregator = eventAggregator;
     _appService      = appService;
 }
Exemple #24
0
        private static void Patch20190227(EntityManager entMan, EntityRelationManager relMan, RecordManager recMan)
        {
            var appSrv = new AppService();

            #region << ***Update app*** App name: sdk >>
            {
                var id          = new Guid("56a8548a-19d0-497f-8e5b-242abfdc4082");
                var name        = "sdk";
                var label       = "Software Development Kit";
                var description = "SDK & Development Tools";
                var iconClass   = "fa fa-cogs";
                var author      = "WebVella";
                var color       = "#dc3545";
                var weight      = 1000;
                var access      = new List <Guid>();
                access.Add(new Guid("bdc56420-caf0-4030-8a0e-d264938e0cda"));

                new WebVella.Erp.Web.Services.AppService().UpdateApplication(id, name, label, description, iconClass, author, color, weight, access, WebVella.Erp.Database.DbContext.Current.Transaction);
            }
            #endregion

            #region << ***Update sitemap area*** Sitemap area name: objects >>
            {
                var id                      = new Guid("d3237d8c-c074-46d7-82c2-1385cbfff35a");
                var appId                   = new Guid("56a8548a-19d0-497f-8e5b-242abfdc4082");
                var name                    = "objects";
                var label                   = "Objects";
                var description             = @"Schema and Layout management";
                var iconClass               = "fa fa-pencil-ruler";
                var color                   = "#2196F3";
                var weight                  = 1;
                var showGroupNames          = false;
                var access                  = new List <Guid>();
                var labelTranslations       = new List <WebVella.Erp.Web.Models.TranslationResource>();
                var descriptionTranslations = new List <WebVella.Erp.Web.Models.TranslationResource>();

                new WebVella.Erp.Web.Services.AppService().UpdateArea(id, appId, name, label, labelTranslations, description, descriptionTranslations, iconClass, color, weight, showGroupNames, access, WebVella.Erp.Database.DbContext.Current.Transaction);
            }
            #endregion

            #region << ***Update sitemap area*** Sitemap area name: access >>
            {
                var id                      = new Guid("c5c4cefc-1402-4a8b-9867-7f2a059b745d");
                var appId                   = new Guid("56a8548a-19d0-497f-8e5b-242abfdc4082");
                var name                    = "access";
                var label                   = "Access";
                var description             = @"Manage users and roles";
                var iconClass               = "fa fa-key";
                var color                   = "#673AB7";
                var weight                  = 2;
                var showGroupNames          = false;
                var access                  = new List <Guid>();
                var labelTranslations       = new List <WebVella.Erp.Web.Models.TranslationResource>();
                var descriptionTranslations = new List <WebVella.Erp.Web.Models.TranslationResource>();

                new WebVella.Erp.Web.Services.AppService().UpdateArea(id, appId, name, label, labelTranslations, description, descriptionTranslations, iconClass, color, weight, showGroupNames, access, WebVella.Erp.Database.DbContext.Current.Transaction);
            }
            #endregion

            #region << ***Update sitemap area*** Sitemap area name: server >>
            {
                var id                      = new Guid("fee72214-f1c4-4ed5-8bda-35698dc11528");
                var appId                   = new Guid("56a8548a-19d0-497f-8e5b-242abfdc4082");
                var name                    = "server";
                var label                   = "Server";
                var description             = @"Background jobs and maintenance";
                var iconClass               = "fa fa-database";
                var color                   = "#F44336";
                var weight                  = 3;
                var showGroupNames          = false;
                var access                  = new List <Guid>();
                var labelTranslations       = new List <WebVella.Erp.Web.Models.TranslationResource>();
                var descriptionTranslations = new List <WebVella.Erp.Web.Models.TranslationResource>();

                new WebVella.Erp.Web.Services.AppService().UpdateArea(id, appId, name, label, labelTranslations, description, descriptionTranslations, iconClass, color, weight, showGroupNames, access, WebVella.Erp.Database.DbContext.Current.Transaction);
            }
            #endregion

            #region << ***Update sitemap node*** Sitemap node name: page >>
            {
                var  id                = new Guid("5b132ac0-703e-4342-a13d-c7ff93d07a4f");
                var  areaId            = new Guid("d3237d8c-c074-46d7-82c2-1385cbfff35a");
                Guid?entityId          = null;
                var  name              = "page";
                var  label             = "Pages";
                var  url               = "/sdk/objects/page/l";
                var  iconClass         = "fa fa-file";
                var  weight            = 1;
                var  type              = ((int)3);
                var  access            = new List <Guid>();
                var  labelTranslations = new List <WebVella.Erp.Web.Models.TranslationResource>();

                new WebVella.Erp.Web.Services.AppService().UpdateAreaNode(id, areaId, name, label, labelTranslations, iconClass, url, type, entityId, weight, access, new List <Guid>(), new List <Guid>(), new List <Guid>(), new List <Guid>(), WebVella.Erp.Database.DbContext.Current.Transaction);
            }
            #endregion

            #region << ***Update sitemap node*** Sitemap node name: data_source >>
            {
                var  id                = new Guid("9b30bf96-67d9-4d20-bf07-e6ef1c44d553");
                var  areaId            = new Guid("d3237d8c-c074-46d7-82c2-1385cbfff35a");
                Guid?entityId          = null;
                var  name              = "data_source";
                var  label             = "Data sources";
                var  url               = "/sdk/objects/data_source/l/list";
                var  iconClass         = "fa fa-cloud-download-alt";
                var  weight            = 2;
                var  type              = ((int)3);
                var  access            = new List <Guid>();
                var  labelTranslations = new List <WebVella.Erp.Web.Models.TranslationResource>();

                new WebVella.Erp.Web.Services.AppService().UpdateAreaNode(id, areaId, name, label, labelTranslations, iconClass, url, type, entityId, weight, access, new List <Guid>(), new List <Guid>(), new List <Guid>(), new List <Guid>(), WebVella.Erp.Database.DbContext.Current.Transaction);
            }
            #endregion

            #region << ***Update sitemap node*** Sitemap node name: application >>
            {
                var  id                = new Guid("02d75ea5-8fc6-4f95-9933-0eed6b36ca49");
                var  areaId            = new Guid("d3237d8c-c074-46d7-82c2-1385cbfff35a");
                Guid?entityId          = null;
                var  name              = "application";
                var  label             = "Applications";
                var  url               = "/sdk/objects/application/l/list";
                var  iconClass         = "fa fa-th";
                var  weight            = 3;
                var  type              = ((int)3);
                var  access            = new List <Guid>();
                var  labelTranslations = new List <WebVella.Erp.Web.Models.TranslationResource>();

                new WebVella.Erp.Web.Services.AppService().UpdateAreaNode(id, areaId, name, label, labelTranslations, iconClass, url, type, entityId, weight, access, new List <Guid>(), new List <Guid>(), new List <Guid>(), new List <Guid>(), WebVella.Erp.Database.DbContext.Current.Transaction);
            }
            #endregion

            #region << ***Update sitemap node*** Sitemap node name: entity >>
            {
                var  id                = new Guid("dfa7ec55-b55b-404f-b251-889f1d81df29");
                var  areaId            = new Guid("d3237d8c-c074-46d7-82c2-1385cbfff35a");
                Guid?entityId          = null;
                var  name              = "entity";
                var  label             = "Entities";
                var  url               = "/sdk/objects/entity/l";
                var  iconClass         = "fa fa-database";
                var  weight            = 4;
                var  type              = ((int)3);
                var  access            = new List <Guid>();
                var  labelTranslations = new List <WebVella.Erp.Web.Models.TranslationResource>();

                new WebVella.Erp.Web.Services.AppService().UpdateAreaNode(id, areaId, name, label, labelTranslations, iconClass, url, type, entityId, weight, access, new List <Guid>(), new List <Guid>(), new List <Guid>(), new List <Guid>(), WebVella.Erp.Database.DbContext.Current.Transaction);
            }
            #endregion

            #region << ***Update sitemap node*** Sitemap node name: user >>
            {
                var  id                = new Guid("ff578868-817e-433d-988f-bb8d4e9baa0d");
                var  areaId            = new Guid("c5c4cefc-1402-4a8b-9867-7f2a059b745d");
                Guid?entityId          = null;
                var  name              = "user";
                var  label             = "Users";
                var  url               = "/sdk/access/user/l/list";
                var  iconClass         = "fa fa-user";
                var  weight            = 1;
                var  type              = ((int)3);
                var  access            = new List <Guid>();
                var  labelTranslations = new List <WebVella.Erp.Web.Models.TranslationResource>();

                new WebVella.Erp.Web.Services.AppService().UpdateAreaNode(id, areaId, name, label, labelTranslations, iconClass, url, type, entityId, weight, access, new List <Guid>(), new List <Guid>(), new List <Guid>(), new List <Guid>(), WebVella.Erp.Database.DbContext.Current.Transaction);
            }
            #endregion

            #region << ***Update sitemap node*** Sitemap node name: job >>
            {
                var  id                = new Guid("396ec481-3b2e-461c-b514-743fb3252003");
                var  areaId            = new Guid("fee72214-f1c4-4ed5-8bda-35698dc11528");
                Guid?entityId          = null;
                var  name              = "job";
                var  label             = "Background jobs";
                var  url               = "/sdk/server/job/l/plan";
                var  iconClass         = "fa fa-cogs";
                var  weight            = 1;
                var  type              = ((int)3);
                var  access            = new List <Guid>();
                var  labelTranslations = new List <WebVella.Erp.Web.Models.TranslationResource>();

                new WebVella.Erp.Web.Services.AppService().UpdateAreaNode(id, areaId, name, label, labelTranslations, iconClass, url, type, entityId, weight, access, new List <Guid>(), new List <Guid>(), new List <Guid>(), new List <Guid>(), WebVella.Erp.Database.DbContext.Current.Transaction);
            }
            #endregion

            #region << ***Update sitemap node*** Sitemap node name: log >>
            {
                var  id                = new Guid("78a29ac8-d2aa-4379-b990-08f7f164a895");
                var  areaId            = new Guid("fee72214-f1c4-4ed5-8bda-35698dc11528");
                Guid?entityId          = null;
                var  name              = "log";
                var  label             = "Logs";
                var  url               = "/sdk/server/log/l/list";
                var  iconClass         = "fas fa-sticky-note";
                var  weight            = 2;
                var  type              = ((int)3);
                var  access            = new List <Guid>();
                var  labelTranslations = new List <WebVella.Erp.Web.Models.TranslationResource>();

                new WebVella.Erp.Web.Services.AppService().UpdateAreaNode(id, areaId, name, label, labelTranslations, iconClass, url, type, entityId, weight, access, new List <Guid>(), new List <Guid>(), new List <Guid>(), new List <Guid>(), WebVella.Erp.Database.DbContext.Current.Transaction);
            }
            #endregion
        }
        //单据保存
        protected void Save()
        {
            string userID    = AppService.GetUserID();
            string rwbh      = Request.Form["rwbh"].ToString();
            string dw_master = Request.Form["dw_master"].ToString();
            SafeDS ds_master = new SafeDS("dw_wlgz_edit");

            try
            {
                ds_master.SetChanges(dw_master);

                //TODO  在服务器端,最好是重做一次数据校验,Demo简化处理,不再重复校验了。
                if (rwbh == null || rwbh == "" || rwbh == null)
                {
                    if (ds_master.GetRowStatus(1, Sybase.DataWindow.DataBuffer.Primary) == Sybase.DataWindow.RowStatus.NewAndModified)
                    {
                        var        year  = System.DateTime.Now.ToString("yyyyMMdd");
                        SqlCommand cmd   = this.DBHelp.GetCommand("select max(right(rwbh,4)) from yw_hddz_wlgz where substring(rwbh,1,8) = '" + year.Substring(0, 8) + "' ");
                        object     value = cmd.ExecuteScalar();
                        if (Convert.IsDBNull(value) || value == null)
                        {
                            rwbh = year.Substring(0, 8) + "0001";
                        }
                        else
                        {
                            rwbh = year.Substring(0, 8) + String.Format("{0:0000}", (long.Parse((string)value) + 1));
                        }
                        ds_master.SetItemString(1, "rwbh", rwbh);
                    }
                    else
                    {
                        rwbh = ds_master.GetItemString(1, "rwbh");
                    }
                }


                ds_master.SetTransaction(this.DBHelp.TransAction);
                this.DBHelp.BeginTransAction();
                if (ds_master.UpdateData() == 1)
                {
                    this.DBHelp.Commit();
                    //把单据号码,传回到客户端
                    Response.Write(rwbh);
                }
                else
                {
                    this.DBHelp.Rollback();
                    this.SetErrorInfo("调换车架任务保存失败!\n\n详细错误信息:\n" + ds_master.DBError + "  " + ds_master.LastError);
                }
            }

            catch (Exception ex)
            {
                this.SetErrorInfo(ex.Message);
            }
            finally
            {
                ds_master.Dispose();
                ds_master = null;
            }
        }
Exemple #26
0
        public override void OnLoad()
        {
            base.OnLoad();

            //系统模块编码
            ReportService report = (ReportService)this.dw_list.Services.Add(ServiceName.Report);

            report.RequestorDrawTitle = false;
            var userid    = AppService.GetUserID();
            var username  = AppService.GetUserName();
            var ShareMode = AppService.GetShareMode();
            var Dlwtf     = AppService.GetDlwtf();


            this.SetParm("userid", userid);
            this.SetParm("username", username);
            this.SetParm("ShareMode", ShareMode);
            this.SetParm("Dlwtf", Dlwtf);


            // 数据分页检索,必须在数据检索之前设置
            //this.dw_list.PageSize = 50;   //每页检索50条记录

            //DataWindowChild dwc = dw_list.GetChild("zbr");
            //dwc.SetTransaction(this.AdoTransaction);
            //dwc.Retrieve("");

            //dwc = dw_list.GetChild("zdr");
            //dwc.SetTransaction(this.AdoTransaction);
            //dwc.Retrieve("");

            //dwc = dw_list.GetChild("dz_zdy");
            //dwc.SetTransaction(this.AdoTransaction);
            //dwc.Retrieve("");

            //dwc = dw_list.GetChild("yw_Kptzs_dzjh_zdy");
            //dwc.SetTransaction(this.AdoTransaction);
            //dwc.Retrieve("");

            this.ds_1.DataWindowObject = "d_sys_modules_all";
            this.ds_1.Retrieve();

            var      node    = "000501";
            var      li_row  = this.ds_1.FindRow("id='" + node + "'", 1, this.ds_1.RowCount);
            var      role_no = this.ds_1.GetItemString(li_row, "role_no");
            DateTime date    = System.DateTime.Now.AddDays(-90);

            this.dp_begin.Value = date;


            ds_role.Retrieve(userid, role_no);
            if (ds_role.RowCount > 0)
            {
                btn_new.Visible       = true;
                btn_duplicate.Visible = true;
                btn_delete.Visible    = true;
                this.SetParm("operation", "open");
                dw_list.Modify("DataWindow.Readonly=no");
            }
            else
            {
                btn_new.Visible       = false;
                btn_duplicate.Visible = false;
                btn_delete.Visible    = false;
                this.SetParm("operation", "show");
                dw_list.Modify("DataWindow.Readonly=yes");
            }


            // 数据检索
            this.dw_list.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()));
            //注册相关的js文件
            this.RegisterClientScriptInclude("ExtPB_Demo", "/Beta3/ExtPB_Demo.js");
            this.RegisterClientScriptInclude("W_HdfyhxdcfList", "/Yw_Zjgl/W_HdfyhxdcfList.win.js");
            this.RegisterClientScriptInclude("W_HdfyhxdcfEdit", "/Yw_Zjgl/W_HdfyhxdcfEdit.win.js");
            this.RegisterClientScriptInclude("W_Filter", "/Hddz/W_Filter.win.js");
            //注册需要使用的弹出窗口的事件处理程序的JS文件
            this.RegisterClientScriptInclude("W_Index", "W_Index.win.js");
            AjaxPro.Utility.RegisterTypeForAjax(typeof(PubMethod));
        }
Exemple #27
0
    public void LoadLabels()
    {
        List <LblLanguage> lblLanguagelst = null;

        ILblLanguage mLanguageService = null;

        lblLanguagelst              = new List <LblLanguage>();
        this.mappmanager            = Master.AppManager;
        mLanguageService            = AppService.Create <ILblLanguage>();
        mLanguageService.AppManager = mappmanager;
        // retrieve
        lblLanguagelst = mLanguageService.RetrieveLabel(Master.AppManager.LoginUser.Id, "USERMODULE");

        Utility _objUtil = new Utility();

        _objUtil.LoadLabels(lblLanguagelst);

        var ALERT_MSG = lblLanguagelst.Where(c => c.LabelId.ToUpper().Equals("ALERTINFORMATION")).FirstOrDefault();

        if (ALERT_MSG != null)
        {
            AlertInformation = Convert.ToString(ALERT_MSG.DisplayText);
            PasswordMismatch = Convert.ToString(ALERT_MSG.SupportingText1);
        }

        var ALERT_PWD = lblLanguagelst.Where(c => c.LabelId.ToUpper().Equals("ALERTPASSWORDLEN")).FirstOrDefault();

        if (ALERT_PWD != null)
        {
            PWDlengthMismatch = Convert.ToString(ALERT_PWD.DisplayText);
        }

        var DATE_LEN = lblLanguagelst.Where(c => c.LabelId.ToUpper().Equals("ALERTINVALIDDATE")).FirstOrDefault();

        if (DATE_LEN != null)
        {
            Datelength         = Convert.ToString(DATE_LEN.DisplayText);
            DatelengthMismatch = Convert.ToString(DATE_LEN.SupportingText1);
        }

        var DATE_RANGE = lblLanguagelst.Where(c => c.LabelId.ToUpper().Equals("ALERTDATERANGE")).FirstOrDefault();

        if (DATE_RANGE != null)
        {
            RELEIVEDATE_RANGE = Convert.ToString(DATE_RANGE.DisplayText);
            JOINDATE_RANGE    = Convert.ToString(DATE_RANGE.SupportingText1);
        }

        var INVALIDEMAIL = lblLanguagelst.Where(c => c.LabelId.ToUpper().Equals("INVALIDEMAIL")).FirstOrDefault();

        if (INVALIDEMAIL != null)
        {
            INVALIDE_MAIL = Convert.ToString(INVALIDEMAIL.DisplayText);
        }

        var PAGE_HEADING = lblLanguagelst.Where(c => c.LabelId.ToUpper().Equals("LBLUSERSMANAGEMENTADDEDIT")).FirstOrDefault();

        if (PAGE_HEADING != null)
        {
            PAGEHEADINGADD  = Convert.ToString(PAGE_HEADING.DisplayText);
            PAGEHEADINGEDIT = Convert.ToString(PAGE_HEADING.SupportingText1);
        }

        var btnADDMOD = lblLanguagelst.Where(c => c.LabelId.Equals("btnUpdate")).FirstOrDefault();

        if (btnADDMOD != null)
        {
            BTNMODIFY = Convert.ToString(btnADDMOD.SupportingText1);
            BTNADD    = Convert.ToString(btnADDMOD.DisplayText);
        }
    }
Exemple #28
0
 public static Ice.DispatchStatus update_user_info___(AppService obj__, IceInternal.Incoming inS__, Ice.Current current__)
 {
     Ice.ObjectImpl.checkMode__(Ice.OperationMode.Normal, current__.mode);
     IceInternal.BasicStream is__ = inS__.startReadParams();
     IceInternal.ParamPatcher<minie.irpc.cm_user_rpc> userInfo__PP = new IceInternal.ParamPatcher<minie.irpc.cm_user_rpc>(minie.irpc.cm_user_rpc.ice_staticId());
     is__.readObject(userInfo__PP);
     is__.readPendingObjects();
     inS__.endReadParams();
     try
     {
         int ret__ = obj__.update_user_info(userInfo__PP.value, current__);
         IceInternal.BasicStream os__ = inS__.startWriteParams__(Ice.FormatType.DefaultFormat);
         os__.writeInt(ret__);
         inS__.endWriteParams__(true);
         return Ice.DispatchStatus.DispatchOK;
     }
     catch(minie.irpc.InvalidDataError ex__)
     {
         inS__.writeUserException__(ex__, Ice.FormatType.DefaultFormat);
         return Ice.DispatchStatus.DispatchUserException;
     }
 }
Exemple #29
0
 public static Ice.DispatchStatus add_member___(AppService obj__, IceInternal.Incoming inS__, Ice.Current current__)
 {
     Ice.ObjectImpl.checkMode__(Ice.OperationMode.Normal, current__.mode);
     IceInternal.BasicStream is__ = inS__.startReadParams();
     string nodeID;
     string userID;
     nodeID = is__.readString();
     userID = is__.readString();
     inS__.endReadParams();
     try
     {
         minie.irpc.cm_node_user_rpc ret__ = obj__.add_member(nodeID, userID, current__);
         IceInternal.BasicStream os__ = inS__.startWriteParams__(Ice.FormatType.DefaultFormat);
         os__.writeObject(ret__);
         os__.writePendingObjects();
         inS__.endWriteParams__(true);
         return Ice.DispatchStatus.DispatchOK;
     }
     catch(minie.irpc.InvalidDataError ex__)
     {
         inS__.writeUserException__(ex__, Ice.FormatType.DefaultFormat);
         return Ice.DispatchStatus.DispatchUserException;
     }
 }
Exemple #30
0
        //#region 列表存盘
        protected void ListSave()
        {
            string userID      = AppService.GetUserID();
            string dw_list     = Request.Form["dw_list"].ToString();
            SafeDS ds_list     = new SafeDS("dw_hy_thwljh_list");
            string dw_log      = Request.Form["dw_log"].ToString();
            SafeDS ds_log      = new SafeDS("dw_s_log_list");
            string dw_htjhthsj = Request.Form["dw_htjhthsj"].ToString();
            SafeDS ds_htjhthsj = new SafeDS("dw_hddz_htjhthsj_lrsj");

            try
            {
                ds_list.SetChanges(dw_list);
                ds_log.SetChanges(dw_log);
                ds_htjhthsj.SetChanges(dw_htjhthsj);

                //for (int row = 1; row <= ds_list.RowCount; row++)
                //{
                //    var ywbh1 = ds_list.GetItemString(row, "ywbh");
                //    var ywbh2=ds_htjhthsj.GetItemString(row,"ywbh");
                //    var cxh1=ds_list.GetItemDecimal(row,"cxh");
                //    var cxh2=ds_htjhthsj.GetItemDecimal(row,"hddz_cxh");
                //    if (ywbh1==ywbh2&&cxh1==cxh2)
                //    {
                //        var htjhthsj_sjd = ds_list.GetItemString(row, "jzxxx_htjhthsj_sjd");
                //        ds_htjhthsj.SetItemString(row, "htjhthsj_sjd", htjhthsj_sjd);
                //    }

                //}

                ds_list.SetTransaction(this.DBHelp.TransAction);
                ds_log.SetTransaction(this.DBHelp.TransAction);
                ds_htjhthsj.SetTransaction(this.DBHelp.TransAction);
                this.DBHelp.BeginTransAction();


                if (ds_list.UpdateData() == 1)
                {
                    if (ds_htjhthsj.UpdateData() == 1)
                    {
                        if (ds_log.UpdateData() == 1)
                        {
                            this.DBHelp.Commit();
                            //把单据号码,传回到客户端
                            Response.Write("存盘成功");

                            //////数据上传生鲜港
                            //Thread t1 = new Thread(new ThreadStart(delegate
                            //{
                            //HddzIF serv = new HddzIF();
                            //for (int row = 1; row <= ds_list.RowCount; row++)
                            //{
                            //    string zt = ds_list.GetRowStatus(row, Sybase.DataWindow.DataBuffer.Primary).ToString();

                            //    if (zt == "NotModified")
                            //    {
                            //        string ywbh = ds_list.GetItemString(row, "ywbh");
                            //        int cxh = ds_list.GetItemInt32(row, "cxh");
                            //        DateTime htjhthsj = new DateTime(1999, 01, 01, 00, 00, 00);
                            //        htjhthsj = ds_list.GetItemDateTime(row, "jzxxx_htjhthsj");
                            //        string zdmc = "htjhthsj";
                            //        DateTime date1 = new DateTime(2000, 01, 01, 00, 00, 00);
                            //        if (htjhthsj > date1)
                            //        {
                            //        string strErr;
                            //        Interfaces.GeneralPortal.DataToFreshPort("yw_hddz_jzxxx", zdmc, ywbh, out strErr, new string[] { cxh.ToString() });
                            //        }
                            //    };
                            //};
                            //}));
                            //t1.IsBackground = true;
                            //t1.Start();
                        }
                        else
                        {
                            this.DBHelp.Rollback();;
                            this.SetErrorInfo("修改传输日志保存失败!\n\n详细错误信息:\n" + ds_log.DBError);
                        }
                    }
                    else
                    {
                        this.DBHelp.Rollback();;
                        this.SetErrorInfo("提货物流计划信息保存失败!\n\n详细错误信息:\n" + ds_htjhthsj.DBError);
                    }
                }
                else
                {
                    this.DBHelp.Rollback();;
                    this.SetErrorInfo("提货物流计划信息保存失败!\n\n详细错误信息:\n" + ds_list.DBError);
                }
            }
            catch (Exception ex)
            {
                this.SetErrorInfo(ex.Message);
            }
            finally
            {
                ds_list.Dispose();
                ds_list = null;
                ds_log.Dispose();
                ds_log = null;
                ds_htjhthsj.Dispose();
                ds_htjhthsj = null;
            }
        }
Exemple #31
0
 public static Ice.DispatchStatus revoke_privilige___(AppService obj__, IceInternal.Incoming inS__, Ice.Current current__)
 {
     Ice.ObjectImpl.checkMode__(Ice.OperationMode.Normal, current__.mode);
     IceInternal.BasicStream is__ = inS__.startReadParams();
     IceInternal.ParamPatcher<minie.irpc.cm_friend_privilege_rpc> privilege__PP = new IceInternal.ParamPatcher<minie.irpc.cm_friend_privilege_rpc>(minie.irpc.cm_friend_privilege_rpc.ice_staticId());
     is__.readObject(privilege__PP);
     is__.readPendingObjects();
     inS__.endReadParams();
     int ret__ = obj__.revoke_privilige(privilege__PP.value, current__);
     IceInternal.BasicStream os__ = inS__.startWriteParams__(Ice.FormatType.DefaultFormat);
     os__.writeInt(ret__);
     inS__.endWriteParams__(true);
     return Ice.DispatchStatus.DispatchOK;
 }
Exemple #32
0
        //#region 码头业务处理列表存盘
        protected void MtywclListSave()
        {
            string userID  = AppService.GetUserID();
            string dw_list = Request.Form["dw_list"].ToString();
            SafeDS ds_list = new SafeDS("dw_hy_mtywcl_list");

            //string dw_log = Request.Form["dw_log"].ToString();
            //SafeDS ds_log = new SafeDS("dw_s_log_list");
            try
            {
                ds_list.SetChanges(dw_list);
                //ds_log.SetChanges(dw_log);

                ds_list.SetTransaction(this.DBHelp.TransAction);
                //ds_log.SetTransaction(this.DBHelp.TransAction);
                this.DBHelp.BeginTransAction();


                if (ds_list.UpdateData() == 1)
                // if (ds_list.e)
                {
                    //if (ds_log.UpdateData()==1)
                    //{


                    this.DBHelp.Commit();

                    //////数据上传生鲜港
                    //Thread t1 = new Thread(new ThreadStart(delegate
                    //{
                    //HddzIF serv = new HddzIF();
                    for (int row = 1; row <= ds_list.RowCount; row++)
                    {
                        string zt = ds_list.GetRowStatus(row, Sybase.DataWindow.DataBuffer.Primary).ToString();

                        if (zt == "NotModified")
                        {
                            string ywbh = ds_list.GetItemString(row, "ywbh");
                            int    cxh  = ds_list.GetItemInt32(row, "cxh");
                            string zdmc = "fxgsjc,fxsj";
                            string strErr;
                            Interfaces.GeneralPortal.DataToFreshPort("yw_hddz_jzxxx", zdmc, ywbh, out strErr, new string[] { cxh.ToString() });

                            DBHelp.Commit();

                            DBHelp.BeginTransAction();
                            SqlCommand cmd = DBHelp.GetCommand("select count(*),rwbh= isnull(max(Yw_hddz_wlgz_cmd.rwbh),''),dzwlbh= isnull(max(Yw_hddz_wlgz.dzwlbh),'') from Yw_hddz_wlgz,Yw_hddz_wlgz_cmd,yw_hddz_jzxxx Where Yw_hddz_wlgz.rwbh = Yw_hddz_wlgz_cmd.rwbh and Yw_hddz_wlgz_cmd.ywbh = yw_hddz_jzxxx.ywbh  and  Yw_hddz_wlgz_cmd.hddz_cxh = yw_hddz_jzxxx.cxh  and Yw_hddz_wlgz_cmd.ywbh=@ywbh and Yw_hddz_wlgz_cmd.hddz_cxh = @cxh and len(yw_hddz_jzxxx.fxdcjc) > 0 and Yw_hddz_wlgz_cmd.rwmc = '堆场' and (jd is null and points is null)");

                            cmd.Parameters.Add(new SqlParameter("@ywbh", ywbh));
                            cmd.Parameters.Add(new SqlParameter("@cxh", cxh));
                            SqlDataReader rs = cmd.ExecuteReader();
                            if (rs.Read())
                            {
                                int    num    = rs.GetInt32(0);
                                string rwbh   = rs.GetString(1);
                                string dzwlbh = rs.GetString(2);
                                rs.Close();
                                if (num > 0)
                                {
                                    SqlCommand cmd_update = DBHelp.GetCommand(" update  Yw_hddz_wlgz_cmd set Yw_hddz_wlgz_cmd.jd = yw_wldw_gnkh_shdz.jd, Yw_hddz_wlgz_cmd.wd = yw_wldw_gnkh_shdz.wd, Yw_hddz_wlgz_cmd.fw = yw_wldw_gnkh_shdz.fw, Yw_hddz_wlgz_cmd.wllx = yw_wldw_gnkh_shdz.type,Yw_hddz_wlgz_cmd.points = yw_wldw_gnkh_shdz.points from Yw_hddz_wlgz_cmd,yw_hddz_jzxxx ,yw_wldw_gnkh_shdz,yw_wldw Where Yw_hddz_wlgz_cmd.ywbh = yw_hddz_jzxxx.ywbh  and  Yw_hddz_wlgz_cmd.hddz_cxh = yw_hddz_jzxxx.cxh  and   yw_wldw_gnkh_shdz.yw_khbm = yw_wldw.yw_khbm  and yw_wldw.khjc = yw_hddz_jzxxx.fxdcjc and Yw_hddz_wlgz_cmd.ywbh=@ywbh and Yw_hddz_wlgz_cmd.hddz_cxh = @cxh and len(yw_hddz_jzxxx.fxdcjc) > 0 and Yw_hddz_wlgz_cmd.rwmc = '堆场' and (Yw_hddz_wlgz_cmd.jd is null and Yw_hddz_wlgz_cmd.points is null) ");
                                    cmd_update.Parameters.Add(new SqlParameter("@ywbh", ywbh));
                                    cmd_update.Parameters.Add(new SqlParameter("@cxh", cxh));
                                    if (cmd_update.ExecuteNonQuery() > 0)
                                    {
                                        DBHelp.Commit();



                                        IFView.FenceHandler fenceHandler = new IFView.FenceHandler();
                                        string strerr = string.Empty;
                                        bool   flag   = fenceHandler.AddLogisticsMonitoring(dzwlbh, out strerr);


                                        if (strerr == null)
                                        {
                                            strerr = "";
                                        }
                                        DBHelp.BeginTransAction();
                                        SqlCommand cmd_wlgz = DBHelp.GetCommand("insert into yw_hddz_wlgz_bd (rwbh,dqsj,strerr) values(@rwbh,getdate(),@strerr)");
                                        cmd_wlgz.Parameters.Add(new SqlParameter("@rwbh", rwbh));
                                        cmd_wlgz.Parameters.Add(new SqlParameter("@strerr", strerr));
                                        if (cmd_wlgz.ExecuteNonQuery() > 0)
                                        {
                                            DBHelp.Commit();
                                        }
                                        else
                                        {
                                            DBHelp.Rollback();
                                        }
                                    }
                                    else
                                    {
                                        DBHelp.Rollback();
                                    }
                                }
                            }
                            else
                            {
                                DBHelp.Rollback();
                            }
                        }
                        ;
                    }
                    ;
                    //}));
                    //t1.IsBackground = true;
                    //t1.Start();

                    //把单据号码,传回到客户端
                    Response.Write("存盘成功");
                    //}
                    //else {
                    //    this.DBHelp.Rollback();
                    //    this.SetErrorInfo("传输错误日志保存失败!\n\n详细错误信息:\n"+ds_log.DBError);
                    //}
                }
                else
                {
                    this.DBHelp.Rollback();;
                    this.SetErrorInfo("码头业务处理保存失败!\n\n详细错误信息:\n" + ds_list.DBError);
                }
            }
            catch (Exception ex)
            {
                this.SetErrorInfo(ex.Message);
            }
            finally
            {
                ds_list.Dispose();
                ds_list = null;
                //ds_log.Dispose();
                //ds_log = null;
            }
        }
        async Task AddOrderHandle(string requestContent, string requestType)
        {
            var logtext = $"请求类型:{requestType}添加订单AddOrder原始请求报文:{requestContent}";

            LogInfo(logtext);

            var sw = new Stopwatch();

            sw.Start();

            //1、解析报文
            var dic = requestContent.UrlFormat();
            var logisticsInterface = dic.ContainsKey("logistics_interface") ? dic["logistics_interface"] : "";
            var dataDigest         = dic.ContainsKey("data_digest") ? dic["data_digest"] : "";
            var msgType            = dic.ContainsKey("msg_type") ? dic["msg_type"] : "";

            //2、检查参数,为空则返回
            if (string.IsNullOrWhiteSpace(logisticsInterface) || string.IsNullOrWhiteSpace(dataDigest))
            {
                LogError($"请求消息报文内容为空导致添加订单操作终止,{logtext}");
                await WriteAsync(new { errorCode = "S05", errorMsg = "消息内容为空", success = false });

                LogInfo($"本次AddOrder提交订单操作耗时:{sw.ElapsedMilliseconds}毫秒");
                sw.Stop();
                return;
            }

            //3、消息类型检查
            if (!string.Equals(msgType, AppSettings.MsgType))
            {
                LogError($"请求消息类型验证失败导致添加订单操作终止,{logtext}");
                await WriteAsync(new { errorCode = "S04", errorMsg = "消息类型msg_type错误", success = false });

                LogInfo($"本次AddOrder提交订单操作耗时:{sw.ElapsedMilliseconds}毫秒");
                sw.Stop();
                return;
            }

            //4、签名检查
            try
            {
                var dataDigestContent = HttpUtility.UrlEncode(logisticsInterface);
                if (!SignHelper.CheckDataDigest(dataDigestContent, dataDigest, AppSettings.SecretKey))
                {
                    LogError($"签名验证失败导致添加订单操作终止,{logtext}");
                    await WriteAsync(new { errorCode = "S02", errorMsg = "消息签名不符,请检查签名", success = false });

                    LogInfo($"本次AddOrder提交订单操作耗时:{sw.ElapsedMilliseconds}毫秒");
                    sw.Stop();
                    return;
                }
            }
            catch (Exception ex)
            {
                LogError($"签名验证过程中出现异常导致添加订单操作终止,{logtext}", ex.Message, ex.StackTrace);
                await WriteAsync(new { errorCode = "S02", errorMsg = "报文消息签名检查失败", success = false });

                LogInfo($"本次AddOrder提交订单操作耗时:{sw.ElapsedMilliseconds}毫秒");
                sw.Stop();
                return;
            }

            //5、报文转换为实体对象
            TmsOrderModel model;

            try
            {
                //URL解码
                model = JsonConvert.DeserializeObject <TmsOrderModel>(logisticsInterface);
            }
            catch (Exception ex)
            {
                var errTitle = "报文内容格式不符合规范,Json格式转换失败";
                LogError($"{errTitle}导致添加订单操作终止,{logtext}", ex.Message, ex.StackTrace);
                await WriteAsync(new { errorCode = "S01", errorMsg = errTitle, success = false });

                LogInfo($"本次AddOrder提交订单操作耗时:{sw.ElapsedMilliseconds}毫秒");
                sw.Stop();
                return;
            }

            //6、创建订单映射
            LogInfo($"运单号:{model.mailNo}外部订单号{model.logisticsId}提交订单原始数据:{JsonConvert.SerializeObject(model)}");
            var mySqlOrder = CainiaoHandler.CreateMap(model, logisticsInterface);

            if (mySqlOrder == null)
            {
                LogInfo($"本次AddOrder提交订单操作耗时:{sw.ElapsedMilliseconds}毫秒");
                sw.Stop();
                return;
            }

            LogInfo($"数据校验与处理用时:{sw.ElapsedMilliseconds}毫秒");

            var hasSuccess = await AppService.AddOrder(mySqlOrder);

            if (!hasSuccess)
            {
                await WriteAsync(new { errorCode = "S07", errorMsg = "订单写入数据库失败", success = false });

                LogInfo($"本次AddOrder提交订单操作耗时:{sw.ElapsedMilliseconds}毫秒");
                sw.Stop();
                return;
            }
            LogInfo($"运单号是{mySqlOrder.OUTSYS_BILL_CODE}外部订单号是{mySqlOrder.OUTSYS_ORDER_NO}的菜鸟仓配订单已成功落盘");
            await WriteAsync(new { errorCode = "", errorMsg = "", success = true });

            LogInfo($"总计用时:{sw.ElapsedMilliseconds}毫秒");
            sw.Stop();
        }
Exemple #34
0
        //单据保存
        protected void Save()
        {
            string userID    = AppService.GetUserID();
            var    operation = Request.Form["operation"].ToString();
            string ywbh      = Request.Form["ywbh"].ToString();
            Int32  cxh       = int.Parse(Request.Form["cxh"].ToString());
            string dw_master = Request.Form["dw_master"].ToString();
            SafeDS ds_master = new SafeDS("dw_hy_thwljh_edit");
            string dw_cmd    = Request.Form["dw_cmd"].ToString();
            SafeDS ds_cmd    = new SafeDS("dw_wlgz_edit_wldz");
            string dw_log    = Request.Form["dw_log"].ToString();
            SafeDS ds_log    = new SafeDS("dw_s_log_list");

            try
            {
                ds_master.SetChanges(dw_master);
                ds_cmd.SetChanges(dw_cmd);
                ds_log.SetChanges(dw_log);

                for (int row = 1; row <= ds_cmd.RowCount; row++)
                {
                    ds_cmd.SetItemString(row, "ywbh", ywbh);
                    ds_cmd.SetItemDouble(row, "hddz_cxh", cxh);
                    ds_cmd.SetItemDouble(row, "cxh", row);
                }

                ds_master.SetTransaction(this.DBHelp.TransAction);
                ds_cmd.SetTransaction(this.DBHelp.TransAction);
                ds_log.SetTransaction(this.DBHelp.TransAction);
                this.DBHelp.BeginTransAction();
                if (ds_master.UpdateData() == 1)
                {
                    if (ds_cmd.UpdateData() == 1)
                    {
                        if (ds_log.UpdateData() == 1)
                        {
                            this.DBHelp.Commit();
                            //把单据号码,传回到客户端
                        }
                        else
                        {
                            this.DBHelp.Rollback();
                            this.SetErrorInfo("传输错误日志保存失败!\n\n详细错误信息:\n" + ds_log.DBError + "  " + ds_log.LastError);
                        }
                    }
                    else
                    {
                        this.DBHelp.Rollback();
                        this.SetErrorInfo("提货物流计划保存失败!\n\n详细错误信息:\n" + ds_cmd.DBError + "  " + ds_cmd.LastError);
                    }
                }
                else
                {
                    this.DBHelp.Rollback();
                    this.SetErrorInfo("提货物流计划保存失败!\n\n详细错误信息:\n" + ds_master.DBError + "  " + ds_master.LastError);
                }
            }

            catch (Exception ex)
            {
                this.SetErrorInfo(ex.Message);
            }
            finally
            {
                ds_master.Dispose();
                ds_master = null;

                ds_cmd.Dispose();
                ds_cmd = null;

                ds_log.Dispose();
                ds_log = null;
            }
        }
Exemple #35
0
        /// <summary>
        /// 接收到数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (BaseConfig.FXType == "Q02U")
            {
                System.Threading.Thread.Sleep(50);
            }
            try
            {
                byte[] data = new byte[sp.BytesToRead];
                sp.Read(data, 0, data.Length);


//               LogUtil.Logger.Info("[Data]" + ToHexString(data));

                if (BaseConfig.FXType == "Q02U" && data.Length > 0)
                {
                    string check = ToHexString(data);


                    if (check.StartsWith("EE 1A") && check.EndsWith("0D 0A") && data.Length == 124)
                    {
                        // 完整的数据
                        //for (int i = 0; i < data.Length; i++) {
                        //    g_data[i] = data[i];
                        //    g_index = i;
                        //}
                    }
                    else if (check.StartsWith("EE 1A"))
                    {
                        for (int i = 0; i < data.Length; i++)
                        {
                            g_data[i] = data[i];
                        }
                        g_index = data.Length;
                    }
                    else if (check.EndsWith("0D 0A"))
                    {
                        for (int i = 0; i < data.Length; i++)
                        {
                            g_data[i + g_index] = data[i];
                        }
                        data    = g_data;
                        g_index = 0;
                    }
                    else
                    {
                        for (int i = 0; i < data.Length; i++)
                        {
                            g_data[i + g_index] = data[i];
                        }
                        g_index += data.Length;
                    }
                }

                if (data.Length == RETURN_DATA_LENGTH)
                {
                    //     LogUtil.Logger.Info("[NICE Read Data]" + ToHexString(data));

                    //   LogUtil.Logger.Info("[LAST Read Data]" + ToHexString(lastRecord));
                    // LogUtil.Logger.Info(getOnOffState(data));

                    if (ToHexString(lastRecord).Equals(ToHexString(data)))
                    {
                        // LogUtil.Logger.Info("SAME................................");
                        // 找到开着的 计时
                        byte[] ons = getOnOffState(data);
                        for (int i = 0; i < ons.Length; i++)
                        {
                            if (ons[i] == 1)
                            {
                                timeRecords[i] = timeRecords[i] + BaseConfig.COMTimerInterval;
                            }
                        }
                    }
                    else
                    {
                        List <string> codes  = new List <string>();
                        List <string> values = new List <string>();


                        // 如果不匹配,发送数据并重置计时器
                        byte[] old_ons  = getOnOffState(lastRecord);
                        byte[] new_offs = getOnOffState(data);

                        // LogUtil.Logger.Info(new_offs);

                        for (int i = 0; i < old_ons.Length; i++)
                        {
                            if (old_ons[i] == 1 && new_offs[i] == 0)
                            {
                                timeRecords[i] = timeRecords[i] + BaseConfig.COMTimerInterval;
                                // #TODO 发送数据,多个发送
                                // 过滤时间
                                if (timeRecords[i] >= BaseConfig.FilterMillSecond)
                                {
                                    //LogUtil.Logger.Info("*************************Merix:");
                                    //LogUtil.Logger.Info(merix[i]);

                                    if (merix[i] != "X")
                                    {
                                        codes.Add(merix[i].ToString());
                                        values.Add(timeRecords[i].ToString());
                                    }
                                }
                                // 重置计时
                                timeRecords[i] = 0;
                            }
                            else if (old_ons[i] == 1 && new_offs[i] == 1)
                            {
                                timeRecords[i] = timeRecords[i] + BaseConfig.COMTimerInterval;
                            }
                        }


                        if (codes.Count > 0)
                        {
                            //     LogUtil.Logger.Info("*************************CODES:");
                            LogUtil.Logger.Info(codes);

                            AppService app  = new AppService();
                            string     time = DateTime.Now.ToString();
                            ResponseMessage <object> msg = app.PostPlcData(codes, values, time);
                            if (msg.http_error)
                            {
                                // save the data in local
                                string dir = System.IO.Path.Combine("Data\\UnHandle");
                                if (!Directory.Exists(dir))
                                {
                                    Directory.CreateDirectory(dir);
                                }

                                using (FileStream fs = new FileStream(System.IO.Path.Combine(dir, DateTime.Now.ToString("yyyy-MM-dd HH-mm-sss") + Guid.NewGuid().ToString() + ".txt"),
                                                                      FileMode.Create, FileAccess.Write))
                                {
                                    using (StreamWriter sw = new StreamWriter(fs))
                                    {
                                        sw.WriteLine(string.Join(",", codes.ToArray()) + ";" + string.Join(",", values.ToArray()) + ";" + time);
                                    }
                                }
                            }
                        }
                    }
                    for (int j = 0; j < data.Length; j++)
                    {
                        lastRecord[j] = data[j];
                    }
                    //lastRecord = data;
                }
                else
                {
                    // LogUtil.Logger.Info("[BAD Read Data]" + ToHexString(data));
                }
            }
            catch (Exception ex)
            {
                LogUtil.Logger.Error("Read Com Error");
                LogUtil.Logger.Error(ex.Message);
            }
        }
Exemple #36
0
        public async Task <IActionResult> ContributeToCrowdfund(string appId, ContributeToCrowdfund request, CancellationToken cancellationToken)
        {
            var app = await _AppService.GetApp(appId, AppType.Crowdfund, true);

            if (app == null)
            {
                return(NotFound());
            }
            var settings = app.GetSettings <CrowdfundSettings>();


            var isAdmin = await _AppService.GetAppDataIfOwner(GetUserId(), appId, AppType.Crowdfund) != null;

            if (!settings.Enabled && !isAdmin)
            {
                return(NotFound("Crowdfund is not currently active"));
            }

            var info = (ViewCrowdfundViewModel)await _AppService.GetAppInfo(appId);

            info.HubPath = AppHub.GetHubPath(this.Request);
            if (!isAdmin &&
                ((settings.StartDate.HasValue && DateTime.Now < settings.StartDate) ||
                 (settings.EndDate.HasValue && DateTime.Now > settings.EndDate) ||
                 (settings.EnforceTargetAmount &&
                  (info.Info.PendingProgressPercentage.GetValueOrDefault(0) +
                   info.Info.ProgressPercentage.GetValueOrDefault(0)) >= 100)))
            {
                return(NotFound("Crowdfund is not currently active"));
            }

            var store = await _AppService.GetStore(app);

            var title = settings.Title;
            var price = request.Amount;

            ViewPointOfSaleViewModel.Item choice = null;
            if (!string.IsNullOrEmpty(request.ChoiceKey))
            {
                var choices = _AppService.Parse(settings.PerksTemplate, settings.TargetCurrency);
                choice = choices.FirstOrDefault(c => c.Id == request.ChoiceKey);
                if (choice == null)
                {
                    return(NotFound("Incorrect option provided"));
                }
                title = choice.Title;
                price = choice.Price.Value;
                if (request.Amount > price)
                {
                    price = request.Amount;
                }


                if (choice.Inventory.HasValue)
                {
                    if (choice.Inventory <= 0)
                    {
                        return(NotFound("Option was out of stock"));
                    }
                }
            }

            if (!isAdmin && (settings.EnforceTargetAmount && info.TargetAmount.HasValue && price >
                             (info.TargetAmount - (info.Info.CurrentAmount + info.Info.CurrentPendingAmount))))
            {
                return(NotFound("Contribution Amount is more than is currently allowed."));
            }

            store.AdditionalClaims.Add(new Claim(Policies.CanCreateInvoice.Key, store.Id));
            try
            {
                var invoice = await _InvoiceController.CreateInvoiceCore(new CreateInvoiceRequest()
                {
                    OrderId               = AppService.GetCrowdfundOrderId(appId),
                    Currency              = settings.TargetCurrency,
                    ItemCode              = request.ChoiceKey ?? string.Empty,
                    ItemDesc              = title,
                    BuyerEmail            = request.Email,
                    Price                 = price,
                    NotificationURL       = settings.NotificationUrl,
                    NotificationEmail     = settings.NotificationEmail,
                    FullNotifications     = true,
                    ExtendedNotifications = true,
                    RedirectURL           = request.RedirectUrl ??
                                            new Uri(new Uri(new Uri(HttpContext.Request.GetAbsoluteRoot()), _BtcPayServerOptions.RootPath), $"apps/{appId}/crowdfund").ToString()
                }, store, HttpContext.Request.GetAbsoluteRoot(),
                                                                         new List <string> {
                    AppService.GetAppInternalTag(appId)
                },
                                                                         cancellationToken : cancellationToken);

                if (request.RedirectToCheckout)
                {
                    return(RedirectToAction(nameof(InvoiceController.Checkout), "Invoice",
                                            new { invoiceId = invoice.Data.Id }));
                }
                else
                {
                    return(Ok(invoice.Data.Id));
                }
            }
            catch (BitpayHttpException e)
            {
                return(BadRequest(e.Message));
            }
        }
Exemple #37
0
    public AppStack()
    {
        var resourceGroup = new ResourceGroup("keyvault-rg");

        // Create a storage account for Blobs
        var storageAccount = new Account("storage", new AccountArgs
        {
            ResourceGroupName      = resourceGroup.Name,
            AccountReplicationType = "LRS",
            AccountTier            = "Standard",
        });

        // The container to put our files into
        var storageContainer = new Container("files", new ContainerArgs
        {
            StorageAccountName  = storageAccount.Name,
            ContainerAccessType = "private",
        });

        // Azure SQL Server that we want to access from the application
        var administratorLoginPassword = new RandomPassword("password",
                                                            new RandomPasswordArgs {
            Length = 16, Special = true
        }).Result;
        var sqlServer = new SqlServer("sqlserver", new SqlServerArgs
        {
            ResourceGroupName = resourceGroup.Name,
            // The login and password are required but won't be used in our application
            AdministratorLogin         = "******",
            AdministratorLoginPassword = administratorLoginPassword,
            Version = "12.0",
        });

        // Azure SQL Database that we want to access from the application
        var database = new Database("db", new DatabaseArgs
        {
            ResourceGroupName             = resourceGroup.Name,
            ServerName                    = sqlServer.Name,
            RequestedServiceObjectiveName = "S0",
        });

        // The connection string that has no credentials in it: authertication will come through MSI
        var connectionString =
            Output.Format($"Server=tcp:{sqlServer.Name}.database.windows.net;Database={database.Name};");

        // A file in Blob Storage that we want to access from the application
        var textBlob = new Blob("text", new BlobArgs
        {
            StorageAccountName   = storageAccount.Name,
            StorageContainerName = storageContainer.Name,
            Type   = "Block",
            Source = new FileAsset("./README.md"),
        });

        // A plan to host the App Service
        var appServicePlan = new Plan("asp", new PlanArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Kind = "App",
            Sku  = new PlanSkuArgs
            {
                Tier = "Basic",
                Size = "B1",
            },
        });

        // ASP.NET deployment package
        var blob = new Blob("zip", new BlobArgs
        {
            StorageAccountName   = storageAccount.Name,
            StorageContainerName = storageContainer.Name,
            Type   = "Block",
            Source = new FileArchive("./webapp/bin/Debug/netcoreapp2.2/publish"),
        });

        var clientConfig     = Output.Create(GetClientConfig.InvokeAsync());
        var tenantId         = clientConfig.Apply(c => c.TenantId);
        var currentPrincipal = clientConfig.Apply(c => c.ObjectId);

        // Key Vault to store secrets (e.g. Blob URL with SAS)
        var vault = new KeyVault("vault", new KeyVaultArgs
        {
            ResourceGroupName = resourceGroup.Name,
            SkuName           = "standard",
            TenantId          = tenantId,
            AccessPolicies    =
            {
                new KeyVaultAccessPolicyArgs
                {
                    TenantId = tenantId,
                    // The current principal has to be granted permissions to Key Vault so that it can actually add and then remove
                    // secrets to/from the Key Vault. Otherwise, 'pulumi up' and 'pulumi destroy' operations will fail.
                    ObjectId          = currentPrincipal,
                    SecretPermissions ={ "delete",                         "get", "list", "set" },
                }
            },
        });

        // Put the URL of the zip Blob to KV
        var secret = new Secret("deployment-zip", new SecretArgs
        {
            KeyVaultId = vault.Id,
            Value      = SharedAccessSignature.SignedBlobReadUrl(blob, storageAccount),
        });
        var secretUri = Output.Format($"{vault.VaultUri}secrets/{secret.Name}/{secret.Version}");


        // The application hosted in App Service
        var app = new AppService("app", new AppServiceArgs
        {
            ResourceGroupName = resourceGroup.Name,
            AppServicePlanId  = appServicePlan.Id,
            // A system-assigned managed service identity to be used for authentication and authorization to the SQL Database and the Blob Storage
            Identity = new AppServiceIdentityArgs {
                Type = "SystemAssigned"
            },

            AppSettings =
            {
                // Website is deployed from a URL read from the Key Vault
                { "WEBSITE_RUN_FROM_ZIP", Output.Format($"@Microsoft.KeyVault(SecretUri={secretUri})") },

                // Note that we simply provide the URL without SAS or keys
                { "StorageBlobUrl",       textBlob.Url                                                 },
            },
            ConnectionStrings =
            {
                new AppServiceConnectionStringArgs
                {
                    Name  = "db",
                    Type  = "SQLAzure",
                    Value = connectionString,
                },
            },
        });

        // Work around a preview issue https://github.com/pulumi/pulumi-azure/issues/192
        var principalId = app.Identity.Apply(id => id.PrincipalId ?? "11111111-1111-1111-1111-111111111111");

        // Grant App Service access to KV secrets
        var policy = new AccessPolicy("app-policy", new AccessPolicyArgs
        {
            KeyVaultId        = vault.Id,
            TenantId          = tenantId,
            ObjectId          = principalId,
            SecretPermissions = { "get" },
        });

        // Make the App Service the admin of the SQL Server (double check if you want a more fine-grained security model in your real app)
        var sqlAdmin = new ActiveDirectoryAdministrator("adadmin", new ActiveDirectoryAdministratorArgs
        {
            ResourceGroupName = resourceGroup.Name,
            TenantId          = tenantId,
            ObjectId          = principalId,
            Login             = "******",
            ServerName        = sqlServer.Name,
        });

        // Grant access from App Service to the container in the storage
        var blobPermission = new Assignment("readblob", new AssignmentArgs
        {
            PrincipalId        = principalId,
            Scope              = Output.Format($"{storageAccount.Id}/blobServices/default/containers/{storageContainer.Name}"),
            RoleDefinitionName = "Storage Blob Data Reader",
        });

        // Add SQL firewall exceptions
        var firewallRules = app.OutboundIpAddresses.Apply(
            ips => ips.Split(",").Select(
                ip => new FirewallRule($"FR{ip}", new FirewallRuleArgs
        {
            ResourceGroupName = resourceGroup.Name,
            StartIpAddress    = ip,
            EndIpAddress      = ip,
            ServerName        = sqlServer.Name,
        })
                ).ToList());

        this.Endpoint = Output.Format($"https://{app.DefaultSiteHostname}");
    }
Exemple #38
0
        public async Task <IActionResult> ViewPointOfSale(string appId,
                                                          [ModelBinder(typeof(InvariantDecimalModelBinder))] decimal amount,
                                                          string email,
                                                          string orderId,
                                                          string notificationUrl,
                                                          string redirectUrl,
                                                          string choiceKey,
                                                          string posData = null, CancellationToken cancellationToken = default)
        {
            var app = await _AppService.GetApp(appId, AppType.PointOfSale);

            if (string.IsNullOrEmpty(choiceKey) && amount <= 0)
            {
                return(RedirectToAction(nameof(ViewPointOfSale), new { appId = appId }));
            }
            if (app == null)
            {
                return(NotFound());
            }
            var settings = app.GetSettings <PointOfSaleSettings>();

            if (string.IsNullOrEmpty(choiceKey) && !settings.ShowCustomAmount && !settings.EnableShoppingCart)
            {
                return(RedirectToAction(nameof(ViewPointOfSale), new { appId = appId }));
            }
            string title = null;
            var    price = 0.0m;

            ViewPointOfSaleViewModel.Item choice = null;
            if (!string.IsNullOrEmpty(choiceKey))
            {
                var choices = _AppService.Parse(settings.Template, settings.Currency);
                choice = choices.FirstOrDefault(c => c.Id == choiceKey);
                if (choice == null)
                {
                    return(NotFound());
                }
                title = choice.Title;
                price = choice.Price.Value;
                if (amount > price)
                {
                    price = amount;
                }

                if (choice.Inventory.HasValue)
                {
                    if (choice.Inventory <= 0)
                    {
                        return(RedirectToAction(nameof(ViewPointOfSale), new { appId = appId }));
                    }
                }
            }
            else
            {
                if (!settings.ShowCustomAmount && !settings.EnableShoppingCart)
                {
                    return(NotFound());
                }
                price = amount;
                title = settings.Title;

                //if cart IS enabled and we detect posdata that matches the cart system's, check inventory for the items
                if (!string.IsNullOrEmpty(posData) &&
                    settings.EnableShoppingCart &&
                    AppService.TryParsePosCartItems(posData, out var cartItems))
                {
                    var choices      = _AppService.Parse(settings.Template, settings.Currency);
                    var updateNeeded = false;
                    foreach (var cartItem in cartItems)
                    {
                        var itemChoice = choices.FirstOrDefault(c => c.Id == cartItem.Key);
                        if (itemChoice == null)
                        {
                            return(NotFound());
                        }

                        if (itemChoice.Inventory.HasValue)
                        {
                            switch (itemChoice.Inventory)
                            {
                            case int i when i <= 0:
                                return(RedirectToAction(nameof(ViewPointOfSale), new { appId }));

                            case int inventory when inventory < cartItem.Value:
                                return(RedirectToAction(nameof(ViewPointOfSale), new { appId }));
                            }
                        }
                    }
                }
            }
            var store = await _AppService.GetStore(app);

            store.AdditionalClaims.Add(new Claim(Policies.CanCreateInvoice.Key, store.Id));
            var invoice = await _InvoiceController.CreateInvoiceCore(new CreateInvoiceRequest()
            {
                ItemCode        = choice?.Id,
                ItemDesc        = title,
                Currency        = settings.Currency,
                Price           = price,
                BuyerEmail      = email,
                OrderId         = orderId,
                NotificationURL =
                    string.IsNullOrEmpty(notificationUrl) ? settings.NotificationUrl : notificationUrl,
                NotificationEmail     = settings.NotificationEmail,
                RedirectURL           = redirectUrl ?? Request.GetDisplayUrl(),
                FullNotifications     = true,
                ExtendedNotifications = true,
                PosData = string.IsNullOrEmpty(posData) ? null : posData,
                RedirectAutomatically = settings.RedirectAutomatically,
            }, store, HttpContext.Request.GetAbsoluteRoot(),
                                                                     new List <string>() { AppService.GetAppInternalTag(appId) },
                                                                     cancellationToken);

            return(RedirectToAction(nameof(InvoiceController.Checkout), "Invoice", new { invoiceId = invoice.Data.Id }));
        }
 protected void SaveButton_Click(object sender, EventArgs e)
 {
     AppService svc = new AppService();
     svc.SaveSiteMessage(MessageTextBox.Text);
 }
Exemple #40
0
        private static void Patch20181215(EntityManager entMan, EntityRelationManager relMan, RecordManager recMan)
        {
            var appSrv = new AppService();

            #region << Create SDK App >>
            var sdkApp = new App()
            {
                Id          = WEBVELLA_SDK_APP_ID,
                Name        = WEBVELLA_SDK_APP_NAME,
                Label       = "Software Development Kit",
                Description = "SDK & Development Tools",
                IconClass   = "ti-settings",
                Author      = "WebVella",
                Weight      = 1000,
                Color       = "#dc3545",
                Access      = new List <Guid>()
                {
                    SystemIds.AdministratorRoleId
                }
            };
            appSrv.CreateApplication(sdkApp.Id, sdkApp.Name, sdkApp.Label, sdkApp.Description, sdkApp.IconClass, sdkApp.Author, sdkApp.Color,
                                     sdkApp.Weight, sdkApp.Access, DbContext.Current.Transaction);

            #endregion

            #region << Create App Sitemap Areas>>
            {
                var appArea = new SitemapArea()
                {
                    Id          = WEBVELLA_SDK_APP_AREA_DESIGN_ID,
                    Name        = "objects",
                    Label       = "Objects",
                    Description = "System objects management",
                    IconClass   = "ti-ruler-pencil",
                    Weight      = 1,
                    Color       = "#2196F3"
                };
                appSrv.CreateArea(appArea.Id, WEBVELLA_SDK_APP_ID, appArea.Name, appArea.Label, appArea.LabelTranslations, appArea.Description, appArea.DescriptionTranslations,
                                  appArea.IconClass, appArea.Color, appArea.Weight, appArea.ShowGroupNames, appArea.Access, DbContext.Current.Transaction);
            }
            {
                var appArea = new SitemapArea()
                {
                    Id          = WEBVELLA_SDK_APP_AREA_ACCESS_ID,
                    Name        = "access",
                    Label       = "Access",
                    Description = "Manage users and roles",
                    IconClass   = "ti-key",
                    Weight      = 2,
                    Color       = "#673AB7"
                };
                appSrv.CreateArea(appArea.Id, WEBVELLA_SDK_APP_ID, appArea.Name, appArea.Label, appArea.LabelTranslations, appArea.Description, appArea.DescriptionTranslations,
                                  appArea.IconClass, appArea.Color, appArea.Weight, appArea.ShowGroupNames, appArea.Access, DbContext.Current.Transaction);
            }
            {
                var appArea = new SitemapArea()
                {
                    Id          = WEBVELLA_SDK_APP_AREA_SERVER_ID,
                    Name        = "server",
                    Label       = "Server",
                    Description = "Background jobs and maintenance",
                    IconClass   = "ti-server",
                    Weight      = 3,
                    Color       = "#F44336"
                };
                appSrv.CreateArea(appArea.Id, WEBVELLA_SDK_APP_ID, appArea.Name, appArea.Label, appArea.LabelTranslations, appArea.Description, appArea.DescriptionTranslations,
                                  appArea.IconClass, appArea.Color, appArea.Weight, appArea.ShowGroupNames, appArea.Access, DbContext.Current.Transaction);
            }
            #endregion

            #region Create Sitemap Nodes >>
            //Design
            {
                var appNode = new SitemapNode()
                {
                    Id        = new Guid("5b132ac0-703e-4342-a13d-c7ff93d07a4f"),
                    Name      = "page",
                    Label     = "Pages",
                    IconClass = "ti-file",
                    Url       = "/sdk/objects/page/l",
                    Weight    = 1,
                    Type      = SitemapNodeType.Url
                };
                appSrv.CreateAreaNode(appNode.Id, WEBVELLA_SDK_APP_AREA_DESIGN_ID, appNode.Name, appNode.Label, appNode.LabelTranslations, appNode.IconClass, appNode.Url,
                                      (int)appNode.Type, appNode.EntityId, appNode.Weight, appNode.Access, DbContext.Current.Transaction);
            }
            {
                var appNode = new SitemapNode()
                {
                    Id        = new Guid("9b30bf96-67d9-4d20-bf07-e6ef1c44d553"),
                    Name      = "data_source",
                    Label     = "Data sources",
                    IconClass = "ti-cloud-down",
                    Url       = "/sdk/objects/data_source/l/list",
                    Weight    = 2,
                    Type      = SitemapNodeType.Url
                };
                appSrv.CreateAreaNode(appNode.Id, WEBVELLA_SDK_APP_AREA_DESIGN_ID, appNode.Name, appNode.Label, appNode.LabelTranslations, appNode.IconClass, appNode.Url,
                                      (int)appNode.Type, appNode.EntityId, appNode.Weight, appNode.Access, DbContext.Current.Transaction);
            }
            {
                var appNode = new SitemapNode()
                {
                    Id        = new Guid("02d75ea5-8fc6-4f95-9933-0eed6b36ca49"),
                    Name      = "application",
                    Label     = "Applications",
                    IconClass = "ti-layout-grid2",
                    Url       = "/sdk/objects/application/l/list",
                    Weight    = 3,
                    Type      = SitemapNodeType.Url
                };
                appSrv.CreateAreaNode(appNode.Id, WEBVELLA_SDK_APP_AREA_DESIGN_ID, appNode.Name, appNode.Label, appNode.LabelTranslations, appNode.IconClass, appNode.Url,
                                      (int)appNode.Type, appNode.EntityId, appNode.Weight, appNode.Access, DbContext.Current.Transaction);
            }
            {
                var appNode = new SitemapNode()
                {
                    Id        = new Guid("dfa7ec55-b55b-404f-b251-889f1d81df29"),
                    Name      = "entity",
                    Label     = "Entities",
                    IconClass = "ti-server",
                    Url       = "/sdk/objects/entity/l",
                    Weight    = 4,
                    Type      = SitemapNodeType.Url
                };
                appSrv.CreateAreaNode(appNode.Id, WEBVELLA_SDK_APP_AREA_DESIGN_ID, appNode.Name, appNode.Label, appNode.LabelTranslations, appNode.IconClass, appNode.Url,
                                      (int)appNode.Type, appNode.EntityId, appNode.Weight, appNode.Access, DbContext.Current.Transaction);
            }
            {
                var appNode = new SitemapNode()
                {
                    Id        = new Guid("4571de62-a817-4a94-8b49-4b230cc0d2ad"),
                    Name      = "codegen",
                    Label     = "Code generation",
                    IconClass = "fa fa-code",
                    Url       = "/sdk/objects/codegen/a/codegen",
                    Weight    = 10,
                    Type      = SitemapNodeType.Url
                };
                appSrv.CreateAreaNode(appNode.Id, WEBVELLA_SDK_APP_AREA_DESIGN_ID, appNode.Name, appNode.Label, appNode.LabelTranslations, appNode.IconClass, appNode.Url,
                                      (int)appNode.Type, appNode.EntityId, appNode.Weight, appNode.Access, DbContext.Current.Transaction);
            }

            //Access
            {
                var appNode = new SitemapNode()
                {
                    Id        = new Guid("ff578868-817e-433d-988f-bb8d4e9baa0d"),
                    Name      = "user",
                    Label     = "Users",
                    IconClass = "ti-user",
                    Url       = "/sdk/access/user/l/list",
                    Weight    = 1,
                    Type      = SitemapNodeType.Url
                };
                appSrv.CreateAreaNode(appNode.Id, WEBVELLA_SDK_APP_AREA_ACCESS_ID, appNode.Name, appNode.Label, appNode.LabelTranslations, appNode.IconClass, appNode.Url,
                                      (int)appNode.Type, appNode.EntityId, appNode.Weight, appNode.Access, DbContext.Current.Transaction);
            }
            {
                var appNode = new SitemapNode()
                {
                    Id        = new Guid("75567fc4-70e1-41a9-9e32-2e5b62636598"),
                    Name      = "role",
                    Label     = "Roles",
                    IconClass = "fa fa-key",
                    Url       = "/sdk/access/role/l/list",
                    Weight    = 2,
                    Type      = SitemapNodeType.Url
                };
                appSrv.CreateAreaNode(appNode.Id, WEBVELLA_SDK_APP_AREA_ACCESS_ID, appNode.Name, appNode.Label, appNode.LabelTranslations, appNode.IconClass, appNode.Url,
                                      (int)appNode.Type, appNode.EntityId, appNode.Weight, appNode.Access, DbContext.Current.Transaction);
            }

            //Server
            {
                var appNode = new SitemapNode()
                {
                    Id        = new Guid("396ec481-3b2e-461c-b514-743fb3252003"),
                    Name      = "job",
                    Label     = "Background jobs",
                    IconClass = "ti-settings",
                    Url       = "/sdk/server/job/l/plan",
                    Weight    = 1,
                    Type      = SitemapNodeType.Url
                };
                appSrv.CreateAreaNode(appNode.Id, WEBVELLA_SDK_APP_AREA_SERVER_ID, appNode.Name, appNode.Label, appNode.LabelTranslations, appNode.IconClass, appNode.Url,
                                      (int)appNode.Type, appNode.EntityId, appNode.Weight, appNode.Access, DbContext.Current.Transaction);
            }
            {
                var appNode = new SitemapNode()
                {
                    Id        = new Guid("78a29ac8-d2aa-4379-b990-08f7f164a895"),
                    Name      = "log",
                    Label     = "Logs",
                    IconClass = "ti-notepad",
                    Url       = "/sdk/server/log/l/list",
                    Weight    = 2,
                    Type      = SitemapNodeType.Url
                };
                appSrv.CreateAreaNode(appNode.Id, WEBVELLA_SDK_APP_AREA_SERVER_ID, appNode.Name, appNode.Label, appNode.LabelTranslations, appNode.IconClass, appNode.Url,
                                      (int)appNode.Type, appNode.EntityId, appNode.Weight, appNode.Access, DbContext.Current.Transaction);
            }
            #endregion
        }
 public AppService UpdateService(AppService service)
 {
   services.Put(pathResolver.ServiceDocPath, service);
   return service;
 }
        public override void OnLoad()
        {
            base.OnLoad();
            //系统模块编码

            ReportService report = (ReportService)dw_jzxxx.Services.Add(ServiceName.Report);

            report.RequestorDrawTitle = false;

            //DataWindowChild dwc = dw_master.GetChild("cllx");
            //dwc.SetTransaction(this.AdoTransaction);
            //dwc.Retrieve("%");

            //DataWindowChild dwc_jgfs = dw_master.GetChild("jgfs");
            //dwc_jgfs.SetTransaction(this.AdoTransaction);
            //dwc_jgfs.Retrieve("%");

            //DataWindowChild dwc_xx = dw_jzxxx.GetChild("xx");
            //dwc_xx.SetTransaction(this.AdoTransaction);
            //dwc_xx.Retrieve("%");

            //DataWindowChild dwc_xl = dw_jzxxx.GetChild("xl");
            //dwc_xl.SetTransaction(this.AdoTransaction);
            //dwc_xl.Retrieve("%");

            //DataWindowChild dwc_fybm = dw_jzxxx.GetChild("fybm");
            //dwc_fybm.SetTransaction(this.AdoTransaction);
            //dwc_fybm.Retrieve("0109");

            var operation = this.Request["operation"].ToString();

            this.SetParm("operation", operation);

            var userid    = AppService.GetUserID();
            var username  = AppService.GetUserName();
            var ShareMode = AppService.GetShareMode();
            var Dlwtf     = AppService.GetDlwtf();
            var userip    = AppService.GetIp();

            this.SetParm("userid", userid);
            this.SetParm("username", username);
            this.SetParm("ShareMode", ShareMode);
            this.SetParm("Dlwtf", Dlwtf);
            this.SetParm("userip", userip);


            var ywbh = this.Request["ywbh"].ToString();
            var cxh  = this.Request["cxh"].ToString();

            dw_master.Retrieve(ywbh, int.Parse(cxh));
            dw_jzxxx.Retrieve(ywbh, int.Parse(cxh));


            this.RegisterClientScriptInclude("W_Wldw_Select", "/Xt_Popwin/W_Wldw_Select.win.js");
            this.RegisterClientScriptInclude("W_Wldw_Yh_Select", "/Xt_Popwin/W_Wldw_Yh_Select.win.js");
            this.RegisterClientScriptInclude("W_Wldw_Zfdx_Select", "/Xt_Popwin/W_Wldw_Zfdx_Select.win.js");
            //注册相关的js文件
            //注册需要使用的弹出窗口的事件处理程序的JS文件
            this.RegisterClientScriptInclude("W_Index", "W_Index.win.js");
            AjaxPro.Utility.RegisterTypeForAjax(typeof(PubMethod));
        }
Exemple #43
0
 public static Ice.DispatchStatus get_user_info___(AppService obj__, IceInternal.Incoming inS__, Ice.Current current__)
 {
     Ice.ObjectImpl.checkMode__(Ice.OperationMode.Normal, current__.mode);
     inS__.readEmptyParams();
     try
     {
         minie.irpc.cm_user_rpc ret__ = obj__.get_user_info(current__);
         IceInternal.BasicStream os__ = inS__.startWriteParams__(Ice.FormatType.DefaultFormat);
         os__.writeObject(ret__);
         os__.writePendingObjects();
         inS__.endWriteParams__(true);
         return Ice.DispatchStatus.DispatchOK;
     }
     catch(minie.irpc.GenericError ex__)
     {
         inS__.writeUserException__(ex__, Ice.FormatType.DefaultFormat);
         return Ice.DispatchStatus.DispatchUserException;
     }
 }
        internal async Task <DataWrapper <InvoiceResponse> > CreateInvoiceCore(CreateInvoiceRequest invoice, StoreData store, string serverUrl, List <string> additionalTags = null, CancellationToken cancellationToken = default)
        {
            invoice.Currency = invoice.Currency?.ToUpperInvariant() ?? "USD";
            InvoiceLogs logs = new InvoiceLogs();

            logs.Write("Creation of invoice starting");
            var entity = _InvoiceRepository.CreateNewInvoice();

            var getAppsTaggingStore = _InvoiceRepository.GetAppsTaggingStore(store.Id);
            var storeBlob           = store.GetStoreBlob();
            EmailAddressAttribute emailValidator = new EmailAddressAttribute();

            entity.ExpirationTime = invoice.ExpirationTime is DateTimeOffset v ? v : entity.InvoiceTime.AddMinutes(storeBlob.InvoiceExpiration);
            if (entity.ExpirationTime - TimeSpan.FromSeconds(30.0) < entity.InvoiceTime)
            {
                throw new BitpayHttpException(400, "The expirationTime is set too soon");
            }
            entity.MonitoringExpiration = entity.ExpirationTime + TimeSpan.FromMinutes(storeBlob.MonitoringExpiration);
            entity.OrderId                 = invoice.OrderId;
            entity.ServerUrl               = serverUrl;
            entity.FullNotifications       = invoice.FullNotifications || invoice.ExtendedNotifications;
            entity.ExtendedNotifications   = invoice.ExtendedNotifications;
            entity.NotificationURLTemplate = invoice.NotificationURL;
            entity.NotificationEmail       = invoice.NotificationEmail;
            entity.BuyerInformation        = Map <CreateInvoiceRequest, BuyerInformation>(invoice);
            entity.PaymentTolerance        = storeBlob.PaymentTolerance;
            if (additionalTags != null)
            {
                entity.InternalTags.AddRange(additionalTags);
            }
            //Another way of passing buyer info to support
            FillBuyerInfo(invoice.Buyer, entity.BuyerInformation);
            if (entity?.BuyerInformation?.BuyerEmail != null)
            {
                if (!EmailValidator.IsEmail(entity.BuyerInformation.BuyerEmail))
                {
                    throw new BitpayHttpException(400, "Invalid email");
                }
                entity.RefundMail = entity.BuyerInformation.BuyerEmail;
            }

            var taxIncluded = invoice.TaxIncluded.HasValue ? invoice.TaxIncluded.Value : 0m;

            var currencyInfo = _CurrencyNameTable.GetNumberFormatInfo(invoice.Currency, false);

            if (currencyInfo != null)
            {
                int divisibility = currencyInfo.CurrencyDecimalDigits;
                invoice.Price       = invoice.Price.RoundToSignificant(ref divisibility);
                divisibility        = currencyInfo.CurrencyDecimalDigits;
                invoice.TaxIncluded = taxIncluded.RoundToSignificant(ref divisibility);
            }
            invoice.Price       = Math.Max(0.0m, invoice.Price);
            invoice.TaxIncluded = Math.Max(0.0m, taxIncluded);
            invoice.TaxIncluded = Math.Min(taxIncluded, invoice.Price);

            entity.ProductInformation = Map <CreateInvoiceRequest, ProductInformation>(invoice);


            entity.RedirectURLTemplate = invoice.RedirectURL ?? store.StoreWebsite;

            entity.RedirectAutomatically =
                invoice.RedirectAutomatically.GetValueOrDefault(storeBlob.RedirectAutomatically);

            entity.Status      = InvoiceStatus.New;
            entity.SpeedPolicy = ParseSpeedPolicy(invoice.TransactionSpeed, store.SpeedPolicy);

            HashSet <CurrencyPair> currencyPairsToFetch = new HashSet <CurrencyPair>();
            var rules         = storeBlob.GetRateRules(_NetworkProvider);
            var excludeFilter = storeBlob.GetExcludedPaymentMethods(); // Here we can compose filters from other origin with PaymentFilter.Any()

            if (invoice.PaymentCurrencies?.Any() is true)
            {
                foreach (string paymentCurrency in invoice.PaymentCurrencies)
                {
                    invoice.SupportedTransactionCurrencies.TryAdd(paymentCurrency,
                                                                  new InvoiceSupportedTransactionCurrency()
                    {
                        Enabled = true
                    });
                }
            }
            if (invoice.SupportedTransactionCurrencies != null && invoice.SupportedTransactionCurrencies.Count != 0)
            {
                var supportedTransactionCurrencies = invoice.SupportedTransactionCurrencies
                                                     .Where(c => c.Value.Enabled)
                                                     .Select(c => PaymentMethodId.TryParse(c.Key, out var p) ? p : null)
                                                     .ToHashSet();
                excludeFilter = PaymentFilter.Or(excludeFilter,
                                                 PaymentFilter.Where(p => !supportedTransactionCurrencies.Contains(p)));
            }

            foreach (var network in store.GetSupportedPaymentMethods(_NetworkProvider)
                     .Where(s => !excludeFilter.Match(s.PaymentId))
                     .Select(c => _NetworkProvider.GetNetwork <BTCPayNetworkBase>(c.PaymentId.CryptoCode))
                     .Where(c => c != null))
            {
                currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, invoice.Currency));
                //TODO: abstract
                if (storeBlob.LightningMaxValue != null)
                {
                    currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, storeBlob.LightningMaxValue.Currency));
                }
                if (storeBlob.OnChainMinValue != null)
                {
                    currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, storeBlob.OnChainMinValue.Currency));
                }
            }

            var rateRules = storeBlob.GetRateRules(_NetworkProvider);
            var fetchingByCurrencyPair = _RateProvider.FetchRates(currencyPairsToFetch, rateRules, cancellationToken);
            var fetchingAll            = WhenAllFetched(logs, fetchingByCurrencyPair);

            var supportedPaymentMethods = store.GetSupportedPaymentMethods(_NetworkProvider)
                                          .Where(s => !excludeFilter.Match(s.PaymentId) && _paymentMethodHandlerDictionary.Support(s.PaymentId))
                                          .Select(c =>
                                                  (Handler: _paymentMethodHandlerDictionary[c.PaymentId],
                                                   SupportedPaymentMethod: c,
                                                   Network: _NetworkProvider.GetNetwork <BTCPayNetworkBase>(c.PaymentId.CryptoCode)))
                                          .Where(c => c.Network != null)
                                          .Select(o =>
                                                  (SupportedPaymentMethod: o.SupportedPaymentMethod,
                                                   PaymentMethod: CreatePaymentMethodAsync(fetchingByCurrencyPair, o.Handler, o.SupportedPaymentMethod, o.Network, entity, store, logs)))
                                          .ToList();
            List <ISupportedPaymentMethod> supported = new List <ISupportedPaymentMethod>();
            var paymentMethods = new PaymentMethodDictionary();

            foreach (var o in supportedPaymentMethods)
            {
                var paymentMethod = await o.PaymentMethod;
                if (paymentMethod == null)
                {
                    continue;
                }
                supported.Add(o.SupportedPaymentMethod);
                paymentMethods.Add(paymentMethod);
            }

            if (supported.Count == 0)
            {
                StringBuilder errors = new StringBuilder();
                if (!store.GetSupportedPaymentMethods(_NetworkProvider).Any())
                {
                    errors.AppendLine("Warning: No wallet has been linked to your BTCPay Store. See the following link for more information on how to connect your store and wallet. (https://docs.btcpayserver.org/WalletSetup/)");
                }
                foreach (var error in logs.ToList())
                {
                    errors.AppendLine(error.ToString());
                }
                throw new BitpayHttpException(400, errors.ToString());
            }

            entity.SetSupportedPaymentMethods(supported);
            entity.SetPaymentMethods(paymentMethods);
            entity.PosData = invoice.PosData;

            foreach (var app in await getAppsTaggingStore)
            {
                entity.InternalTags.Add(AppService.GetAppInternalTag(app.Id));
            }

            using (logs.Measure("Saving invoice"))
            {
                entity = await _InvoiceRepository.CreateInvoiceAsync(store.Id, entity);
            }
            _ = Task.Run(async() =>
            {
                try
                {
                    await fetchingAll;
                }
                catch (AggregateException ex)
                {
                    ex.Handle(e => { logs.Write($"Error while fetching rates {ex}"); return(true); });
                }
                await _InvoiceRepository.AddInvoiceLogs(entity.Id, logs);
            });
            _EventAggregator.Publish(new Events.InvoiceEvent(entity, 1001, InvoiceEvent.Created));
            var resp = entity.EntityToDTO();

            return(new DataWrapper <InvoiceResponse>(resp)
            {
                Facade = "pos/invoice"
            });
        }
Exemple #45
0
 public static Ice.DispatchStatus get_members___(AppService obj__, IceInternal.Incoming inS__, Ice.Current current__)
 {
     Ice.ObjectImpl.checkMode__(Ice.OperationMode.Normal, current__.mode);
     IceInternal.BasicStream is__ = inS__.startReadParams();
     string nodeID;
     nodeID = is__.readString();
     inS__.endReadParams();
     try
     {
         _System.Collections.Generic.List<minie.irpc.cm_node_user_rpc> ret__ = obj__.get_members(nodeID, current__);
         IceInternal.BasicStream os__ = inS__.startWriteParams__(Ice.FormatType.DefaultFormat);
         minie.irpc.cm_node_user_rpc_listHelper.write(os__, ret__);
         os__.writePendingObjects();
         inS__.endWriteParams__(true);
         return Ice.DispatchStatus.DispatchOK;
     }
     catch(minie.irpc.InvalidDataError ex__)
     {
         inS__.writeUserException__(ex__, Ice.FormatType.DefaultFormat);
         return Ice.DispatchStatus.DispatchUserException;
     }
 }
 public static async Task<ResourceGroup> MarkInUse(this ResourceGroup resourceGroup, string userId, TimeSpan lifeTime, AppService appService)
 {
     resourceGroup.Tags[Constants.UserId] = userId;
     resourceGroup.Tags[Constants.StartTime] = DateTime.UtcNow.ToString("u");
     resourceGroup.Tags[Constants.LifeTimeInMinutes] = lifeTime.TotalMinutes.ToString();
     resourceGroup.Tags[Constants.AppService] = appService.ToString();
     return await Update(resourceGroup);
 }
Exemple #47
0
 public static Ice.DispatchStatus get_blacklist___(AppService obj__, IceInternal.Incoming inS__, Ice.Current current__)
 {
     Ice.ObjectImpl.checkMode__(Ice.OperationMode.Normal, current__.mode);
     inS__.readEmptyParams();
     try
     {
         _System.Collections.Generic.List<minie.irpc.cm_user_defriend_rpc> ret__ = obj__.get_blacklist(current__);
         IceInternal.BasicStream os__ = inS__.startWriteParams__(Ice.FormatType.DefaultFormat);
         minie.irpc.cm_user_defriend_rpc_listHelper.write(os__, ret__);
         os__.writePendingObjects();
         inS__.endWriteParams__(true);
         return Ice.DispatchStatus.DispatchOK;
     }
     catch(minie.irpc.GenericError ex__)
     {
         inS__.writeUserException__(ex__, Ice.FormatType.DefaultFormat);
         return Ice.DispatchStatus.DispatchUserException;
     }
 }
Exemple #48
0
        //单据保存
        protected void Save()
        {
            string userID    = AppService.GetUserID();
            string id        = Request.Form["id"].ToString();
            var    operation = Request.Form["operation"].ToString();
            string dw_master = Request.Form["dw_master"].ToString();
            string dw_jzxxx  = Request.Form["dw_jzxxx"].ToString();
            SafeDS ds_master = new SafeDS("dw_sxgjksz_edit");
            SafeDS ds_jzxxx  = new SafeDS("dw_sxgjksz_edit_cmd");

            try
            {
                ds_master.SetChanges(dw_master);
                ds_jzxxx.SetChanges(dw_jzxxx);
                if (operation == "copy" || operation == "modify")
                {
                    ds_master.SetRowStatus(1, Sybase.DataWindow.DataBuffer.Primary, Sybase.DataWindow.RowStatus.New);

                    for (int row = 1; row <= ds_jzxxx.RowCount; row++)
                    {
                        ds_jzxxx.SetRowStatus(row, Sybase.DataWindow.DataBuffer.Primary, Sybase.DataWindow.RowStatus.New);
                    }
                }
                ;

                //TODO  在服务器端,最好是重做一次数据校验,Demo简化处理,不再重复校验了。
                if (id == null || id == "")
                {
                    if (ds_master.GetRowStatus(1, Sybase.DataWindow.DataBuffer.Primary) == Sybase.DataWindow.RowStatus.NewAndModified)
                    {
                        //var year = System.DateTime.Now.ToShortDateString().Substring(0, 8);
                        var        year  = System.DateTime.Now.ToString("yyyyMMdd");
                        SqlCommand cmd   = this.DBHelp.GetCommand("select max(right(id,5)) from interTb where substring(id,1,8) = '" + year.Substring(0, 8) + "'");
                        object     value = cmd.ExecuteScalar();
                        if (Convert.IsDBNull(value) || value == null)
                        {
                            id = year.Substring(0, 8) + "00001";
                        }
                        else
                        {
                            id = year.Substring(0, 8) + String.Format("{0:00000}", (long.Parse((string)value) + 1));
                        }
                        ds_master.SetItemString(1, "id", id);
                    }
                    else
                    {
                        id = ds_master.GetItemString(1, "id");
                    }
                }



                for (int row = 1; row <= ds_jzxxx.RowCount; row++)
                {
                    ds_jzxxx.SetItemString(row, "interid", id);
                    var idcxh = id + row.ToString();
                    ds_jzxxx.SetItemString(row, "id", idcxh);
                }


                ds_master.SetTransaction(this.DBHelp.TransAction);
                ds_jzxxx.SetTransaction(this.DBHelp.TransAction);

                this.DBHelp.BeginTransAction();
                if (ds_master.UpdateData() == 1)
                {
                    ds_jzxxx.UpdateData();


                    this.DBHelp.Commit();
                    //把单据号码,传回到客户端
                    Response.Write(id);
                }
                else
                {
                    this.DBHelp.Rollback();
                    this.SetErrorInfo("产品信息库保存失败!\n\n详细错误信息:\n" + ds_master.DBError + "  " + ds_master.LastError);
                }
            }

            catch (Exception ex)
            {
                this.SetErrorInfo(ex.Message);
            }
            finally
            {
                ds_master.Dispose();
                ds_master = null;

                ds_jzxxx.Dispose();
                ds_jzxxx = null;
            }
        }
Exemple #49
0
 public static Ice.DispatchStatus grant_privilige___(AppService obj__, IceInternal.Incoming inS__, Ice.Current current__)
 {
     Ice.ObjectImpl.checkMode__(Ice.OperationMode.Normal, current__.mode);
     IceInternal.BasicStream is__ = inS__.startReadParams();
     string valid_thru;
     IceInternal.ParamPatcher<minie.irpc.cm_user_friend_rpc> friend__PP = new IceInternal.ParamPatcher<minie.irpc.cm_user_friend_rpc>(minie.irpc.cm_user_friend_rpc.ice_staticId());
     is__.readObject(friend__PP);
     IceInternal.ParamPatcher<minie.irpc.cm_node_rpc> room__PP = new IceInternal.ParamPatcher<minie.irpc.cm_node_rpc>(minie.irpc.cm_node_rpc.ice_staticId());
     is__.readObject(room__PP);
     valid_thru = is__.readString();
     is__.readPendingObjects();
     inS__.endReadParams();
     minie.irpc.cm_friend_privilege_rpc ret__ = obj__.grant_privilige(friend__PP.value, room__PP.value, valid_thru, current__);
     IceInternal.BasicStream os__ = inS__.startWriteParams__(Ice.FormatType.DefaultFormat);
     os__.writeObject(ret__);
     os__.writePendingObjects();
     inS__.endWriteParams__(true);
     return Ice.DispatchStatus.DispatchOK;
 }
        // ARM
        public async Task <ResourceGroup> ActivateWebApp(BaseTemplate template, TryWebsitesIdentity userIdentity, string anonymousUserName, AppService temp = AppService.Web)
        {
            // Start site specific stuff
            var deploymentType = template != null && template.GithubRepo != null
                ? DeploymentType.GitWithCsmDeploy
                : DeploymentType.ZipDeploy;

            return(await ActivateResourceGroup(userIdentity, temp, deploymentType, async (resourceGroup, inProgressOperation) => {
                SimpleTrace.TraceInformation("{0}; {1}; {2}; {3}; {4}; ",
                                             AnalyticsEvents.OldUserCreatedSiteWithLanguageAndTemplateName, "NA", template.Name, resourceGroup.ResourceUniqueId, temp.ToString());

                var site = resourceGroup.Site;
                //if (template != null && template.FileName != null)
                //{
                //    var credentials = new NetworkCredential(site.PublishingUserName, site.PublishingPassword);
                //    var zipManager = new RemoteZipManager(site.ScmUrl + "zip/", credentials, retryCount: 3);
                //    var vfsSCMManager = new RemoteVfsManager(site.ScmUrl + "vfs/", credentials, retryCount: 3);
                //    Task scmRedirectUpload = vfsSCMManager.Put("site/applicationHost.xdt", Path.Combine(HostingEnvironment.MapPath(@"~/App_Data"), "applicationHost.xdt"));

                //    var vfsManager = new RemoteVfsManager(site.ScmUrl + "vfs/", credentials, retryCount: 3);
                //    Task deleteHostingStart = vfsManager.Delete("site/wwwroot/hostingstart.html");

                //    await Task.WhenAll(scmRedirectUpload, deleteHostingStart);
                //}
                resourceGroup.Tags[Constants.TemplateName] = template.Name;
                site.SubscriptionId = resourceGroup.SubscriptionId;
                await site.LoadAppSettings();
                site.AppSettings["LAST_MODIFIED_TIME_UTC"] = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture);
                //site.AppSettings["WEBSITE_TRY_MODE"] = "1";
                //if (site.SubscriptionType != SubscriptionType.VSCodeLinux)
                //{
                //    site.AppSettings["SITE_LIFE_TIME_IN_MINUTES"] = SimpleSettings.SiteExpiryMinutes;
                //}
                //if (site.AppSettings.ContainsKey("FUNCTIONS_EXTENSION_VERSION"))
                //{
                //    site.AppSettings.Remove("FUNCTIONS_EXTENSION_VERSION");
                //}

                //if (template.Name.Equals("ASP.NET with Azure Search Site", StringComparison.OrdinalIgnoreCase))
                //{
                //    site.AppSettings["SearchServiceName"] = SimpleSettings.SearchServiceName;
                //    site.AppSettings["SearchServiceApiKey"] = AzureSearchHelper.GetApiKey();
                //}

                await Task.WhenAll(site.UpdateAppSettings(), resourceGroup.Update());

                //if (template.Name.Equals("WordPress", StringComparison.OrdinalIgnoreCase))
                //{
                //    await site.UpdateConfig(new {properties = new {scmType = "LocalGit", httpLoggingEnabled = true, localMySqlEnabled = true} });
                //}

                Util.WarmUpSite(site);
                return resourceGroup;
            }, template));
        }
Exemple #51
0
 public static void write(Ice.OutputStream outS__, AppService v__)
 {
     outS__.writeObject(v__);
 }
        // ARM
        private async Task <ResourceGroup> ActivateResourceGroup(TryWebsitesIdentity userIdentity, AppService appService, DeploymentType deploymentType, Func <ResourceGroup, InProgressOperation, Task <ResourceGroup> > func, BaseTemplate template = null)
        {
            ResourceGroup resourceGroup = null;

            if (userIdentity == null)
            {
                throw new InvalidUserIdentityException();
            }

            var userId = userIdentity.Name;

            try
            {
                if (await StorageHelper.GetAssignedResourceGroup(userId) != null)
                {
                    throw new MoreThanOneResourceGroupException();
                }
                bool resourceGroupFound = false;
                SimpleTrace.TraceInformation($"Searching vscodequeue for template '{template.QueueName}': Count of templates:{await StorageHelper.GetQueueCount(template.QueueName)} ");

                if (await StorageHelper.GetQueueCount(template.QueueName) > 0)
                {
                    var totalTries = 3;
                    var tries      = 0;
                    //bool siteFound = false;
                    while (tries++ < totalTries && !resourceGroupFound)
                    {
                        resourceGroup = await StorageHelper.GetQueueMessage(template.QueueName);

                        resourceGroupFound = (resourceGroup != null);
                        if (resourceGroupFound)
                        {
                            //    try
                            //    {
                            //        var a = Dns.GetHostEntry(resourceGroup.Sites.FirstOrDefault().HostName);
                            //        if (a != null)
                            //        {
                            //            siteFound = true;
                            //        }
                            //    }
                            //    catch
                            //    {
                            //        resourceGroupFound = false;
                            //        SimpleTrace.TraceInformation($"Found ResourceGroup but HostName isnt active '{resourceGroup.ResourceGroupName}' with template {resourceGroup.DeployedTemplateName}");
                            //    }
                            SimpleTrace.TraceInformation($"Found ResourceGroup '{resourceGroup.ResourceGroupName}' with template {resourceGroup.DeployedTemplateName}");
                        }
                        else
                        {
                            SimpleTrace.TraceInformation($"No resource found in free queue for '{template.Name}' ");
                        }
                    }
                }
                if (resourceGroupFound)
                {
                    //mark site in use as soon as it's checked out so that if there is a reload it will be sorted out to the used queue.
                    await resourceGroup.MarkInUse(userId, appService);

                    //var rbacTask = Task.FromResult(false); //RbacHelper.AddRbacUser(userIdentity.Puid, userIdentity.Email, resourceGroup);
                    var process = new InProgressOperation(resourceGroup, deploymentType);
                    _backgroundQueueManager.ResourceGroupsInProgress.AddOrUpdate(userId, s => process, (s, task) => process);
                    SimpleTrace.Diagnostics.Information("site {siteId} is now in use", String.Concat(resourceGroup.CsmId, "/", resourceGroup.Site.SiteName));

                    resourceGroup = await func(resourceGroup, process);

                    var addedResourceGroup = await StorageHelper.AssignResourceGroup(userId, resourceGroup);

                    if (addedResourceGroup)
                    {
                        //this means we just added the resourceGroup for the user.
                        //Removing this line since we have already marked the resourcegroup as in use by the user
                        //await addedResourceGroup.MarkInUse(userId, appService);
                        return(resourceGroup);
                    }
                    else
                    {
                        //this means the user is trying to add more than 1 site.
                        //delete the new site that's not yet added to the used list
                        SimpleTrace.Diagnostics.Information("User asked for more than 1 site. Replacing {resourceGroup.CsmId}", resourceGroup.CsmId);
                        await resourceGroup.DeleteAndCreateReplacement();

                        throw new MoreThanOneResourceGroupException();
                    }
                }
                else
                {
                    SimpleTrace.Diagnostics.Information("No resource group found yet. Shouldnt be here");
                    throw new NoFreeResourceGroupsException();
                }
                // End site specific stuff
            }
            catch (MoreThanOneResourceGroupException)
            {
                throw;
            }
            catch (NoFreeResourceGroupsException)
            {
                throw;
            }
            catch (InvalidGithubRepoException)
            {
                throw;
            }
            catch (Exception e)
            {
                //unknown exception, log it
                SimpleTrace.Diagnostics.Fatal(e, "Unknown error during UserCreate, Count {Count}", Interlocked.Increment(ref _unknownErrorInCreateErrorCount));
            }
            finally
            {
                InProgressOperation temp;
                if (_backgroundQueueManager.ResourceGroupsInProgress.TryRemove(userId, out temp))
                {
                    temp.Complete();
                    LogQueueStatistics();
                }
            }
            //if we are here that means a bad exception happened above, but we might leak a site if we don't remove the site and replace it correctly.
            if (resourceGroup != null)
            {
                DeleteResourceGroup(resourceGroup);
            }
            throw new Exception(Resources.Server.Error_GeneralErrorMessage);
        }
Exemple #53
0
 public AppController(HWLEntities dbContext, IHostingEnvironment hostingEnvironment)
 {
     this.dbContext          = dbContext;
     this.hostingEnvironment = hostingEnvironment;
     this.appService         = new AppService(dbContext);
 }
        // ARM
        private async Task <ResourceGroup> ActivateResourceGroup(TryWebsitesIdentity userIdentity, AppService appService, DeploymentType deploymentType, Func <ResourceGroup, InProgressOperation, Task <ResourceGroup> > func, string template = "")
        {
            ResourceGroup resourceGroup = null;

            if (userIdentity == null)
            {
                throw new InvalidUserIdentityException();
            }

            var userId = userIdentity.Name;

            try
            {
                if (_backgroundQueueManager.ResourceGroupsInUse.TryGetValue(userId, out resourceGroup))
                {
                    throw new MoreThanOneResourceGroupException();
                }
                bool resourceGroupFound = false;
                if (appService == AppService.Containers || appService == AppService.Linux)
                {
                    resourceGroupFound = _backgroundQueueManager.FreeLinuxResourceGroups.TryDequeue(out resourceGroup);
                }
                else if ((appService == AppService.VSCodeLinux))
                {
                    if (_backgroundQueueManager.FreeVSCodeLinuxResourceGroups[template] != null)
                    {
                        resourceGroupFound = _backgroundQueueManager.FreeVSCodeLinuxResourceGroups[template].TryDequeue(out resourceGroup);
                    }
                    else
                    {
                        resourceGroupFound = false;
                    }
                }
                else if ((appService != AppService.MonitoringTools))
                {
                    resourceGroupFound = _backgroundQueueManager.FreeResourceGroups.TryDequeue(out resourceGroup);
                }
                else if ((appService == AppService.MonitoringTools))
                {
                    resourceGroup = _backgroundQueueManager.MonitoringResourceGroup;
                    BackgroundQueueManager.MonitoringResourceGroupCheckoutTimes.AddOrUpdate(userId, DateTime.UtcNow, (key, oldValue) => DateTime.UtcNow);
                    SimpleTrace.Diagnostics.Information("resourceGroup {resourceGroupId} is now assigned", resourceGroup.CsmId);
                    return(await func(resourceGroup, null));
                }
                if (resourceGroupFound)
                {
                    //mark site in use as soon as it's checked out so that if there is a reload it will be sorted out to the used queue.
                    await resourceGroup.MarkInUse(userId, appService);

                    //var rbacTask = Task.FromResult(false); //RbacHelper.AddRbacUser(userIdentity.Puid, userIdentity.Email, resourceGroup);
                    var process = new InProgressOperation(resourceGroup, deploymentType);
                    _backgroundQueueManager.ResourceGroupsInProgress.AddOrUpdate(userId, s => process, (s, task) => process);
                    SimpleTrace.Diagnostics.Information("site {siteId} is now in use", String.Concat(resourceGroup.CsmId, "/", resourceGroup.Sites.FirstOrDefault(s => s.IsSimpleWAWSOriginalSite).SiteName));

                    resourceGroup = await func(resourceGroup, process);

                    var addedResourceGroup = _backgroundQueueManager.ResourceGroupsInUse.GetOrAdd(userId, resourceGroup);
                    if (addedResourceGroup.ResourceGroupName == resourceGroup.ResourceGroupName)
                    {
                        //this means we just added the resourceGroup for the user.
                        //Removing this line since we have already marked the resourcegroup as in use by the user
                        //await addedResourceGroup.MarkInUse(userId, appService);
                        return(addedResourceGroup);
                    }
                    else
                    {
                        //this means the user is trying to add more than 1 site.
                        //delete the new site that's not yet added to the used list
                        SimpleTrace.Diagnostics.Information("User asked for more than 1 site. Replacing {resourceGroup.CsmId}", resourceGroup.CsmId);
                        await resourceGroup.DeleteAndCreateReplacement();

                        throw new MoreThanOneResourceGroupException();
                    }
                }
                else
                {
                    throw new NoFreeResourceGroupsException();
                }
                // End site specific stuff
            }
            catch (MoreThanOneResourceGroupException)
            {
                throw;
            }
            catch (NoFreeResourceGroupsException)
            {
                throw;
            }
            catch (InvalidGithubRepoException)
            {
                throw;
            }
            catch (Exception e)
            {
                //unknown exception, log it
                SimpleTrace.Diagnostics.Fatal(e, "Unknown error during UserCreate, Count {Count}", Interlocked.Increment(ref _unknownErrorInCreateErrorCount));
            }
            finally
            {
                InProgressOperation temp;
                if (_backgroundQueueManager.ResourceGroupsInProgress.TryRemove(userId, out temp))
                {
                    temp.Complete();
                    LogQueueStatistics();
                }
            }
            //if we are here that means a bad exception happened above, but we might leak a site if we don't remove the site and replace it correctly.
            if (resourceGroup != null)
            {
                DeleteResourceGroup(resourceGroup);
            }
            throw new Exception(Resources.Server.Error_GeneralErrorMessage);
        }
        public IActionResult OnGet()
        {
            Init();

            #region << InitPage >>
            int           pager     = 0;
            string        sortBy    = "";
            QuerySortType sortOrder = QuerySortType.Ascending;
            PageUtils.GetListQueryParams(PageContext.HttpContext, out pager, out sortBy, out sortOrder);
            Pager     = pager;
            SortBy    = sortBy;
            SortOrder = sortOrder;

            ErpEntity = new EntityManager().ReadEntity(ParentRecordId ?? Guid.Empty).Object;

            if (ErpEntity == null)
            {
                return(NotFound());
            }

            if (String.IsNullOrWhiteSpace(ReturnUrl))
            {
                ReturnUrl = $"/sdk/objects/entity/r/{ErpEntity.Id}/";
            }


            var pageSer = new PageService();
            var entMan  = new EntityManager();
            var appServ = new AppService();

            var pages    = pageSer.GetAll();
            var entities = entMan.ReadEntities().Object;
            var apps     = appServ.GetAllApplications();

            #region << Apply filters >>
            var submittedFilters = PageUtils.GetPageFiltersFromQuery(PageContext.HttpContext);
            foreach (var filter in submittedFilters)
            {
                switch (filter.Name)
                {
                default:
                case "label":
                    if (filter.Type == FilterType.CONTAINS)
                    {
                        pages = pages.FindAll(x => x.Label.ToLowerInvariant().Contains(filter.Value.ToLowerInvariant())).ToList();
                    }
                    break;

                case "name":
                    if (filter.Type == FilterType.CONTAINS)
                    {
                        pages = pages.FindAll(x => x.Name.ToLowerInvariant().Contains(filter.Value.ToLowerInvariant())).ToList();
                    }
                    break;

                case "app":
                    if (filter.Type == FilterType.EQ)
                    {
                        var app = apps.FirstOrDefault(x => x.Name.ToLowerInvariant() == filter.Value.ToLowerInvariant());
                        if (app != null)
                        {
                            pages = pages.FindAll(x => x.AppId == app.Id).ToList();
                        }
                        else
                        {
                            pages = new List <ErpPage>();
                        }
                    }
                    break;

                case "entity":
                    if (filter.Type == FilterType.EQ)
                    {
                        var entity = entities.FirstOrDefault(x => x.Name.ToLowerInvariant() == filter.Value.ToLowerInvariant());
                        if (entity != null)
                        {
                            pages = pages.FindAll(x => x.EntityId == entity.Id).ToList();
                        }
                        else
                        {
                            pages = new List <ErpPage>();
                        }
                    }
                    break;

                case "type":
                    if (filter.Type == FilterType.CONTAINS)
                    {
                        foreach (var typeEnum in Enum.GetValues(typeof(PageType)).Cast <PageType>())
                        {
                            var enumDescription = typeEnum.GetLabel();
                            if (!enumDescription.ToLowerInvariant().Contains(filter.Value.ToLowerInvariant()))
                            {
                                pages = pages.FindAll(x => x.Type != typeEnum).ToList();
                            }
                        }
                        //pages = pages.FindAll(x => x.Type == entity.Id).ToList();
                    }
                    break;

                case "system":
                    if (filter.Type == FilterType.EQ)
                    {
                        if (filter.Value == "true")
                        {
                            pages = pages.FindAll(x => x.System).ToList();
                        }
                        else if (filter.Value == "false")
                        {
                            pages = pages.FindAll(x => !x.System).ToList();
                        }
                    }
                    break;

                case "customized":
                    if (filter.Type == FilterType.EQ)
                    {
                        if (filter.Value == "true")
                        {
                            pages = pages.FindAll(x => x.IsRazorBody).ToList();
                        }
                        else if (filter.Value == "false")
                        {
                            pages = pages.FindAll(x => !x.IsRazorBody).ToList();
                        }
                    }
                    break;
                }
            }
            #endregion

            TotalCount = pages.Count;

            ReturnUrlEncoded = HttpUtility.UrlEncode(PageContext.HttpContext.Request.Path + PageContext.HttpContext.Request.QueryString);

            PageDescription = PageUtils.GenerateListPageDescription(PageContext.HttpContext, "", TotalCount);

            HeaderToolbar.AddRange(AdminPageUtils.GetEntityAdminSubNav(ErpEntity, "pages"));
            #endregion

            #region << Create Columns >>

            Columns = new List <GridColumn>()
            {
                new GridColumn()
                {
                    Name  = "action",
                    Width = "1%"
                },
                new GridColumn()
                {
                    Label      = "Label",
                    Name       = "label",
                    Sortable   = true,
                    Searchable = true
                },
                new GridColumn()
                {
                    Label      = "Name",
                    Name       = "name",
                    Sortable   = true,
                    Searchable = true
                },
                new GridColumn()
                {
                    Label = "App",
                    Name  = "app",
                    Width = "140px"
                },
                new GridColumn()
                {
                    Label = "Entity",
                    Name  = "entity",
                    Width = "140px"
                },
                new GridColumn()
                {
                    Label    = "Type",
                    Name     = "type",
                    Sortable = true,
                    Width    = "120px"
                },
                new GridColumn()
                {
                    Label    = "system",
                    Name     = "system",
                    Sortable = true,
                    Width    = "80px"
                },
                new GridColumn()
                {
                    Label    = "Customized",
                    Name     = "customized",
                    Sortable = true,
                    Width    = "80px"
                }
            };

            #endregion

            #region << Records >>
            pages = pages.FindAll(x => x.EntityId == ErpEntity.Id).ToList();
            switch (SortBy)
            {
            default:
            case "label":
                if (SortOrder == QuerySortType.Descending)
                {
                    pages = pages.OrderByDescending(x => x.Label).ToList();
                }
                else
                {
                    pages = pages.OrderBy(x => x.Label).ToList();
                }
                break;

            case "name":
                if (SortOrder == QuerySortType.Descending)
                {
                    pages = pages.OrderByDescending(x => x.Name).ToList();
                }
                else
                {
                    pages = pages.OrderBy(x => x.Name).ToList();
                }
                break;

            case "type":
                if (SortOrder == QuerySortType.Descending)
                {
                    pages = pages.OrderByDescending(x => x.Type).ToList();
                }
                else
                {
                    pages = pages.OrderBy(x => x.Type).ToList();
                }
                break;

            case "system":
                if (SortOrder == QuerySortType.Descending)
                {
                    pages = pages.OrderByDescending(x => x.System).ToList();
                }
                else
                {
                    pages = pages.OrderBy(x => x.System).ToList();
                }
                break;

            case "customized":
                if (SortOrder == QuerySortType.Descending)
                {
                    pages = pages.OrderByDescending(x => x.IsRazorBody).ToList();
                }
                else
                {
                    pages = pages.OrderBy(x => x.IsRazorBody).ToList();
                }
                break;
            }

            //Apply pager
            var skipPages = (Pager - 1) * PagerSize;
            pages = pages.Skip(skipPages).Take(PagerSize).ToList();

            foreach (var page in pages)
            {
                var record = new EntityRecord();
                record["action"] = $"<a class='btn btn-sm btn-white' target='_blank' href='/sdk/objects/page/r/{page.Id}'><span class='ti-eye'></span></a>";
                record["label"]  = page.Label;
                record["name"]   = page.Name;
                record["app"]    = page.AppId != null?apps.First(x => x.Id == page.AppId).Name : "";

                record["entity"]     = page.EntityId != null?entities.First(x => x.Id == page.EntityId).Name : "";;
                record["type"]       = $"{page.Type.GetLabel()}";
                record["system"]     = page.System;
                record["customized"] = page.IsRazorBody;
                Records.Add(record);
            }
            #endregion

            return(Page());
        }
        public override void OnLoad()
        {
            base.OnLoad();

            //系统模块编码
            ReportService report = (ReportService)this.dw_list.Services.Add(ServiceName.Report);

            report.RequestorDrawTitle = false;
            var userid    = AppService.GetUserID();
            var username  = AppService.GetUserName();
            var ShareMode = AppService.GetShareMode();
            var Dlwtf     = AppService.GetDlwtf();

            this.SetParm("userid", userid);
            this.SetParm("username", username);
            this.SetParm("ShareMode", ShareMode);
            this.SetParm("Dlwtf", Dlwtf);

            // 数据分页检索,必须在数据检索之前设置
            //this.dw_list.PageSize = 50;   //每页检索50条记录

            //DataWindowChild dwc = dw_list.GetChild("ywy");
            //dwc.SetTransaction(this.AdoTransaction);
            //dwc.Retrieve("");

            //dwc = dw_list.GetChild("zdr");
            //dwc.SetTransaction(this.AdoTransaction);
            //dwc.Retrieve("");

            //dwc = dw_list.GetChild("dz_zdy");
            //dwc.SetTransaction(this.AdoTransaction);
            //dwc.Retrieve("");

            DataWindowChild dwc_fybm = dw_list.GetChild("fybm");

            dwc_fybm.SetTransaction(this.AdoTransaction);
            dwc_fybm.Retrieve("0106");

            this.ds_1.DataWindowObject = "d_sys_modules_all";
            this.ds_1.Retrieve();

            var      node    = "009105";
            var      li_row  = this.ds_1.FindRow("id='" + node + "'", 1, this.ds_1.RowCount);
            var      role_no = this.ds_1.GetItemString(li_row, "role_no");
            DateTime date    = System.DateTime.Now.AddDays(-180);

            this.dp_begin.Value = date;


            ds_role.Retrieve(userid, role_no);
            if (ds_role.RowCount > 0)
            {
                dw_list.Modify("DataWindow.Readonly=no");
                this.SetParm("Readonly", "no");
            }
            else
            {
                dw_list.Modify("DataWindow.Readonly=yes");
                this.SetParm("Readonly", "yes");
            }



            // 数据检索
            this.dw_list.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()));
            //注册相关的js文件
            this.RegisterClientScriptInclude("ExtPB_Demo", "/Beta3/ExtPB_Demo.js");
            this.RegisterClientScriptInclude("W_Fybz_KythfyList", "/Fybz/W_Fybz_KythfyList.win.js");
            this.RegisterClientScriptInclude("W_Wldw_Select", "/Xt_Popwin/W_Wldw_Select.win.js");
            this.RegisterClientScriptInclude("W_Filter", "/Hddz/W_Filter.win.js");
            //注册需要使用的弹出窗口的事件处理程序的JS文件
            this.RegisterClientScriptInclude("W_Index", "W_Index.win.js");
            AjaxPro.Utility.RegisterTypeForAjax(typeof(PubMethod));
        }
Exemple #57
0
        public void ConfigureServices(IServiceCollection services)
        {
            var localizationCollector = new LocalizationCollector();
            var moduleInit            = new InitializationManager();

            moduleInit.Add(new CNCLib.Logic.ModuleInitializer());
            moduleInit.Add(new CNCLib.Logic.Client.ModuleInitializer());
            moduleInit.Add(new CNCLib.Repository.ModuleInitializer()
            {
                OptionsAction = SqliteDatabaseTools.OptionBuilder
            });
            moduleInit.Add(new CNCLib.Service.Logic.ModuleInitializer());
            moduleInit.Add(new Framework.Tools.ModuleInitializer());
            moduleInit.Add(new Framework.Schedule.ModuleInitializer());
            moduleInit.Add(new Framework.Logic.ModuleInitializer()
            {
                MapperConfiguration = new MapperConfiguration(cfg => { cfg.AddProfile <LogicAutoMapperProfile>(); })
            });

            var controllerAssembly = typeof(CambamController).Assembly;

            services.AddSingleton <ILocalizationCollector>(localizationCollector);

            services.AddControllers();

            services.AddCors(options => options.AddPolicy(CorsAllowAllName, options => options.SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()));

            services.AddSignalR(hu => hu.EnableDetailedErrors = true);

            services.AddTransient <GCodeLoadHelper>();
            services.AddTransient <SetUserContextFilter>();
            services.AddTransient <UnhandledExceptionFilter>();
            services.AddTransient <MethodCallLogFilter>();
            services.AddMvc(
                options =>
            {
                options.EnableEndpointRouting = false;
                options.Filters.AddService <UnhandledExceptionFilter>();
                options.Filters.AddService <MethodCallLogFilter>();
                options.Filters.AddService <SetUserContextFilter>();
            })
            .SetCompatibilityVersion(CompatibilityVersion.Latest)
            .AddNewtonsoftJson(
                options =>
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver())
            .AddApplicationPart(controllerAssembly);

            services.AddAuthentication(AuthenticationScheme)
            .AddScheme <AuthenticationSchemeOptions, BasicAuthenticationHandler>(AuthenticationScheme, null);

            services.AddAuthorization(options => { options.AddPolicy(Policies.IsAdmin, policy => policy.RequireClaim(CNCLibClaimTypes.IsAdmin)); });

            services.AddScoped <IAuthenticationManager, UserManager>();
            services.AddTransient <IOneWayPasswordProvider, Pbkdf2PasswordProvider>();

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "CNCLib API", Version = "v1"
                });
                c.AddSecurityDefinition("basic", new OpenApiSecurityScheme
                {
                    Name        = "Authorization",
                    Type        = SecuritySchemeType.Http,
                    Scheme      = "basic",
                    In          = ParameterLocation.Header,
                    Description = "Basic Authorization header using the Bearer scheme."
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "basic"
                            }
                        },
                        new string[] { }
                    }
                });
                c.OperationFilter <SecurityRequirementsOperationFilter>(true, "basic");
            });

            moduleInit.Initialize(services, localizationCollector);

            services.AddScoped <ICNCLibUserContext, CNCLibUserContext>();

            AppService.ServiceCollection = services;
            AppService.BuildServiceProvider();
        }
Exemple #58
0
        public void CanComputeCrowdfundModel()
        {
            using (var tester = ServerTester.Create())
            {
                tester.Start();
                var user = tester.NewAccount();
                user.GrantAccess();
                user.RegisterDerivationScheme("BTC");
                user.ModifyStore(s => s.NetworkFeeMode = NetworkFeeMode.Never);
                var apps = user.GetController <AppsController>();
                var vm   = Assert.IsType <CreateAppViewModel>(Assert.IsType <ViewResult>(apps.CreateApp().Result).Model);
                vm.Name            = "test";
                vm.SelectedAppType = AppType.Crowdfund.ToString();
                Assert.IsType <RedirectToActionResult>(apps.CreateApp(vm).Result);
                var appId = Assert.IsType <ListAppsViewModel>(Assert.IsType <ViewResult>(apps.ListApps().Result).Model)
                            .Apps[0].Id;

                Logs.Tester.LogInformation("We create an invoice with a hardcap");
                var crowdfundViewModel = Assert.IsType <UpdateCrowdfundViewModel>(Assert
                                                                                  .IsType <ViewResult>(apps.UpdateCrowdfund(appId).Result).Model);
                crowdfundViewModel.Enabled             = true;
                crowdfundViewModel.EndDate             = null;
                crowdfundViewModel.TargetAmount        = 100;
                crowdfundViewModel.TargetCurrency      = "BTC";
                crowdfundViewModel.UseAllStoreInvoices = true;
                crowdfundViewModel.EnforceTargetAmount = true;
                Assert.IsType <RedirectToActionResult>(apps.UpdateCrowdfund(appId, crowdfundViewModel).Result);

                var anonAppPubsController = tester.PayTester.GetController <AppsPublicController>();
                var publicApps            = user.GetController <AppsPublicController>();

                var model = Assert.IsType <ViewCrowdfundViewModel>(Assert
                                                                   .IsType <ViewResult>(publicApps.ViewCrowdfund(appId, String.Empty).Result).Model);


                Assert.Equal(crowdfundViewModel.TargetAmount, model.TargetAmount);
                Assert.Equal(crowdfundViewModel.EndDate, model.EndDate);
                Assert.Equal(crowdfundViewModel.StartDate, model.StartDate);
                Assert.Equal(crowdfundViewModel.TargetCurrency, model.TargetCurrency);
                Assert.Equal(0m, model.Info.CurrentAmount);
                Assert.Equal(0m, model.Info.CurrentPendingAmount);
                Assert.Equal(0m, model.Info.ProgressPercentage);


                Logs.Tester.LogInformation("Unpaid invoices should show as pending contribution because it is hardcap");
                Logs.Tester.LogInformation("Because UseAllStoreInvoices is true, we can manually create an invoice and it should show as contribution");
                var invoice = user.BitPay.CreateInvoice(new Invoice()
                {
                    Buyer = new Buyer()
                    {
                        email = "*****@*****.**"
                    },
                    Price             = 1m,
                    Currency          = "BTC",
                    PosData           = "posData",
                    ItemDesc          = "Some description",
                    TransactionSpeed  = "high",
                    FullNotifications = true
                }, Facade.Merchant);


                model = Assert.IsType <ViewCrowdfundViewModel>(Assert
                                                               .IsType <ViewResult>(publicApps.ViewCrowdfund(appId, String.Empty).Result).Model);

                Assert.Equal(0m, model.Info.CurrentAmount);
                Assert.Equal(1m, model.Info.CurrentPendingAmount);
                Assert.Equal(0m, model.Info.ProgressPercentage);
                Assert.Equal(1m, model.Info.PendingProgressPercentage);

                Logs.Tester.LogInformation("Let's check current amount change once payment is confirmed");
                var invoiceAddress = BitcoinAddress.Create(invoice.CryptoInfo[0].Address, tester.ExplorerNode.Network);
                tester.ExplorerNode.SendToAddress(invoiceAddress, invoice.BtcDue);
                tester.ExplorerNode.Generate(1); // By default invoice confirmed at 1 block
                TestUtils.Eventually(() =>
                {
                    model = Assert.IsType <ViewCrowdfundViewModel>(Assert
                                                                   .IsType <ViewResult>(publicApps.ViewCrowdfund(appId, String.Empty).Result).Model);
                    Assert.Equal(1m, model.Info.CurrentAmount);
                    Assert.Equal(0m, model.Info.CurrentPendingAmount);
                });

                Logs.Tester.LogInformation("Because UseAllStoreInvoices is true, let's make sure the invoice is tagged");
                var invoiceEntity = tester.PayTester.InvoiceRepository.GetInvoice(invoice.Id).GetAwaiter().GetResult();
                Assert.True(invoiceEntity.Version >= InvoiceEntity.InternalTagSupport_Version);
                Assert.Contains(AppService.GetAppInternalTag(appId), invoiceEntity.InternalTags);

                crowdfundViewModel.UseAllStoreInvoices = false;
                Assert.IsType <RedirectToActionResult>(apps.UpdateCrowdfund(appId, crowdfundViewModel).Result);

                Logs.Tester.LogInformation("Because UseAllStoreInvoices is false, let's make sure the invoice is not tagged");
                invoice = user.BitPay.CreateInvoice(new Invoice()
                {
                    Buyer = new Buyer()
                    {
                        email = "*****@*****.**"
                    },
                    Price             = 1m,
                    Currency          = "BTC",
                    PosData           = "posData",
                    ItemDesc          = "Some description",
                    TransactionSpeed  = "high",
                    FullNotifications = true
                }, Facade.Merchant);
                invoiceEntity = tester.PayTester.InvoiceRepository.GetInvoice(invoice.Id).GetAwaiter().GetResult();
                Assert.DoesNotContain(AppService.GetAppInternalTag(appId), invoiceEntity.InternalTags);

                Logs.Tester.LogInformation("After turning setting a softcap, let's check that only actual payments are counted");
                crowdfundViewModel.EnforceTargetAmount = false;
                crowdfundViewModel.UseAllStoreInvoices = true;
                Assert.IsType <RedirectToActionResult>(apps.UpdateCrowdfund(appId, crowdfundViewModel).Result);
                invoice = user.BitPay.CreateInvoice(new Invoice()
                {
                    Buyer = new Buyer()
                    {
                        email = "*****@*****.**"
                    },
                    Price             = 1m,
                    Currency          = "BTC",
                    PosData           = "posData",
                    ItemDesc          = "Some description",
                    TransactionSpeed  = "high",
                    FullNotifications = true
                }, Facade.Merchant);
                Assert.Equal(0m, model.Info.CurrentPendingAmount);
                invoiceAddress = BitcoinAddress.Create(invoice.CryptoInfo[0].Address, tester.ExplorerNode.Network);
                tester.ExplorerNode.SendToAddress(invoiceAddress, Money.Coins(0.5m));
                tester.ExplorerNode.SendToAddress(invoiceAddress, Money.Coins(0.2m));
                TestUtils.Eventually(() =>
                {
                    model = Assert.IsType <ViewCrowdfundViewModel>(Assert
                                                                   .IsType <ViewResult>(publicApps.ViewCrowdfund(appId, String.Empty).Result).Model);
                    Assert.Equal(0.7m, model.Info.CurrentPendingAmount);
                });
            }
        }
    private void LoadWidgetsData(AdminWidgetsModel m, AppService appSvc)
    {
      //TODO: move into service
      var targets = new List<Target>();

      var container = (IContainer)HttpContext.Application["container"];
      var instances = container.Model.AllInstances.Where(i => i.PluginType.Equals(typeof(IWidget)));
      var widgets = instances.Select(i => i.Get<IWidget>()).ToList();
      //var widgets = container.GetAllInstances<IWidget>();
      var pages = container.GetAllInstances<IPage>();

      //load data based on scope
      if (Scope.IsWorkspace || Scope.IsCollection)
      {
        var w = appSvc.GetWorkspace(Scope.Workspace);
        if (Scope.IsCollection)
        {
          var c = w.GetCollection(Scope.Collection);
          var cTargets = c.Pages.Cast<TargetBase>().Concat(c.Widgets.Cast<TargetBase>());
          targets.AddRange(cTargets.Select(p => GetTarget(p, !Scope.IsCollection, pages, widgets, m)));
        }
        var wTargets = w.Pages.Cast<TargetBase>().Concat(w.Widgets.Cast<TargetBase>())
          .Select(p => GetTarget(p, !Scope.IsWorkspace, pages, widgets, m));
        MergeTargets(wTargets, targets);
      }
      var sTargets = appSvc.Pages.Cast<TargetBase>().Concat(appSvc.Widgets.Cast<TargetBase>())
        .Select(p => GetTarget(p, !Scope.IsEntireSite, pages, widgets, m));
      MergeTargets(sTargets, targets);

      // select first target
      if (string.IsNullOrEmpty(m.TargetName) && targets.Count > 0)
      {
        m.TargetName = targets[0].Name;
        m.TargetType = targets[0].IsPage ? "page" : "widget";
      }
      m.Targets = targets.OrderBy(t => t.Inherited);

      // get areas for target
      var target = m.Targets.Where(t => t.Name == m.TargetName && t.IsPage == (m.TargetType == "page")).FirstOrDefault();
      m.Areas = (target != null) ? target.Areas.OrderBy(a => a.Inherited).ToArray() : new Area[] { };

      // select first area
      if (m.AreaName == null && m.Areas.Count() > 0) m.AreaName = m.Areas.First().Name;

      var area = m.Areas.Where(a => a.Name == m.AreaName).FirstOrDefault();
      m.Includes = (area != null) ? area.Includes.OrderBy(a => a.Inherited).ToArray() : new WidgetInclude[] { };
    }
        public override void OnLoad()
        {
            base.OnLoad();

            //系统模块编码
            ReportService report = (ReportService)this.dw_list.Services.Add(ServiceName.Report);

            report.RequestorDrawTitle = false;
            var userid    = AppService.GetUserID();
            var username  = AppService.GetUserName();
            var ShareMode = AppService.GetShareMode();
            var Dlwtf     = AppService.GetDlwtf();

            this.SetParm("userid", userid);
            this.SetParm("username", username);
            this.SetParm("ShareMode", ShareMode);
            this.SetParm("Dlwtf", Dlwtf);

            // 数据分页检索,必须在数据检索之前设置
            //this.dw_list.PageSize = 50;   //每页检索50条记录

            //DataWindowChild dwc = dw_list.GetChild("ywy");
            //dwc.SetTransaction(this.AdoTransaction);
            //dwc.Retrieve("");

            //dwc = dw_list.GetChild("zdr");
            //dwc.SetTransaction(this.AdoTransaction);
            //dwc.Retrieve("");

            //dwc = dw_list.GetChild("dz_zdy");
            //dwc.SetTransaction(this.AdoTransaction);
            //dwc.Retrieve("");

            //dwc = dw_list.GetChild("yw_Kptzs_dzjh_zdy");
            //dwc.SetTransaction(this.AdoTransaction);
            //dwc.Retrieve("");

            this.ds_1.DataWindowObject = "d_sys_modules_all";
            this.ds_1.Retrieve();

            var      node    = "000312";
            var      li_row  = this.ds_1.FindRow("id='" + node + "'", 1, this.ds_1.RowCount);
            var      role_no = this.ds_1.GetItemString(li_row, "role_no");
            DateTime date    = System.DateTime.Now.AddDays(-180);

            this.dp_begin.Value = date;


            ds_role.Retrieve(userid, role_no);
            if (ds_role.RowCount > 0)
            {
                dw_list.Modify("DataWindow.Readonly=no");
            }
            else
            {
                dw_list.Modify("DataWindow.Readonly=yes");
            }
            //接单人
            this.ds_2.DataWindowObject = "d_sys_userroles_wldw";
            this.ds_2.Retrieve(userid);
            this.ddlb_jdrjc.Items.Add("全部");
            for (int row = 1; row <= ds_2.RowCount; row++)
            {
                this.ddlb_jdrjc.Items.Add(ds_2.GetItemString(row, "dwjc"));
            }
            // 数据检索
            this.dw_list.Retrieve(DateTime.Parse(this.dp_begin.Value.ToString()), DateTime.Parse(this.dp_end.Value.ToString()), "未离开检疫点", "N", userid, "全部");
            this.dw_log.Retrieve(userid, "kyjz");
            //注册相关的js文件
            this.RegisterClientScriptInclude("ExtPB_Demo", "/Beta3/ExtPB_Demo.js");
            this.RegisterClientScriptInclude("W_Hy_JyztList", "/Wlxx/W_Hy_JyztList.win.js");
            this.RegisterClientScriptInclude("W_Filter", "/Hddz/W_Filter.win.js");
            this.RegisterClientScriptInclude("W_HdfyjydfyyfkEdit", "/Yw_Zjgl/W_HdfyjydfyyfkEdit.win.js");
            //注册需要使用的弹出窗口的事件处理程序的JS文件
            this.RegisterClientScriptInclude("W_Index", "W_Index.win.js");
            AjaxPro.Utility.RegisterTypeForAjax(typeof(PubMethod));
        }