public ResourceResponse OnRequest(ResourceRequest request)
        {
            var webRequest = HttpWebRequest.CreateHttp(request.Url);
            webRequest = request.ToWebRequest(webRequest);
            Stream stream = null;
            var startTime = DateTime.Now;
            try
            {
                var response = webRequest.GetResponse();
                stream = response.GetResponseStream();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            var streamData = stream.ReadFully();
            var endTime = DateTime.Now;

            var timeTaken = (endTime - startTime).TotalMilliseconds;
            var filename = Guid.NewGuid().ToString();
            File.WriteAllBytes(filename, streamData);

            RecordTimeOfResourceOccured.Invoke(new ResourceTimingResult
            {
                ResourceUrl = request.Url.ToString(),
                TimeTaken = timeTaken,
                Size = streamData.Length,
            });
            return ResourceResponse.Create(filename);
        }
        public ResourceResponse OnRequest(ResourceRequest request)
        {
            if(UserAgent != null)
                request.AppendExtraHeader("User-Agent", UserAgent);

            return null;
        }
 protected override ResourceResponse OnRequest(ResourceRequest request)
 {
     // try to recover login data
     if (request.Count>0 && request.Method == "POST" && request.Url.AbsoluteUri.ToLower().EndsWith(LoginUrl))
     {
         _lastLoginData = ParseData(Uri.UnescapeDataString(request[0].Bytes));
     }
     return base.OnRequest(request);
 }
        public ResourceResponse OnRequest(ResourceRequest request)
        {
            /*Console.WriteLine("OnRequest:\t" + request.Url);
            if (request.Url.Host == "home")
            {

                return ResourceResponse.Create("/Core/home.html");
            }*/
            return null;
        }
 public ResourceResponse OnRequest(ResourceRequest request)
 {
     string login = "******";
       string password = "******";
       string data = @"_filter%5Btitle%5D=&_filter%5Bcount_min%5D=&_filter%5Bcount_max%5D=&_filter%5Blevel_min%5D=&_filter%5Blevel_max%5D=&_filter%5Bkind%5D=g1_12&_filter%5Bquality%5D=-1&_filterapply=%D0%9E%D0%BA";
       request.Method = @"POST";
       request.AppendUploadBytes(data, (uint)data.Length);
       request.AppendExtraHeader("Content-Type", "application/x-www-form-urlencoded");
       return null;
 }
        public virtual Task ProcessAsync(ResourceRequest request)
        {
            if (IsDifferentToCurrentDownloadUrl(request.Target))
            {
                CancelDownload();
                Download = _loader.DownloadAsync(request);
                return FinishDownloadAsync();
            }

            return null;
        }
        public override Task ProcessAsync(ResourceRequest request)
        {
            if (Engine != null && IsDifferentToCurrentDownloadUrl(request.Target))
            {
                CancelDownload();
                Download = DownloadWithCors(request);
                return FinishDownloadAsync();
            }

            return null;
        }
        /// <summary>
        /// Loads the data for the request asynchronously.
        /// </summary>
        /// <param name="request">The issued request.</param>
        /// <returns>The active download.</returns>
        public virtual IDownload DownloadAsync(ResourceRequest request)
        {
            var data = new Request
            {
                Address = request.Target,
                Method = HttpMethod.Get
            };

            data.Headers[HeaderNames.Referer] = request.Source.Owner.DocumentUri;
            return DownloadAsync(data, request.Source);
        }
        public override Task ProcessAsync(ResourceRequest request)
        {
            var contentHtml = _element.GetContentHtml();

            if (contentHtml != null)
            {
                var referer = _element.Owner.DocumentUri;
                return ProcessResponse(contentHtml, referer);
            }

            return base.ProcessAsync(request);
        }
Beispiel #10
0
 /// <summary>
 /// Befores the handling request.
 /// </summary>
 /// <param name="context">The context.</param>
 public void BeforeHandlingRequest(RequestProcessingContext context)
 {
     if (context != null && context.Request != null)
     {
         var request = context.Request;
         var resource = new ResourceRequest { request.GetType ().FullName };
         if ( !_accessControlManager.CanAccess ( resource ) )
         {
             throw new InvalidOperationException ( "You do not have permission to access: " + resource );
         }
     }
 }
Beispiel #11
0
        /// <summary>
        /// Loads the data for the request asynchronously.
        /// </summary>
        /// <param name="request">The issued request.</param>
        /// <param name="cancel">The cancellation token.</param>
        /// <returns>The task creating the response.</returns>
        public virtual Task<IResponse> LoadAsync(ResourceRequest request, CancellationToken cancel)
        {
            var events = _document.Context.Configuration.Events;
            var data = new Request
            {
                Address = request.Target,
                Method = HttpMethod.Get
            };

            data.Headers[HeaderNames.Referer] = request.Source.Owner.DocumentUri;
            return _filter(data) ? _requesters.LoadAsync(data, events, cancel) : TaskEx.FromResult(default(IResponse));
        }
Beispiel #12
0
        /// <summary>
        /// Determines whether access to the specified resource request should be granted.
        /// </summary>
        /// <param name="resourceRequest">The resource request.</param>
        /// <returns>
        ///   <c>true</c> if this instance can access the specified resource request; otherwise, <c>false</c>.
        /// </returns>
        public bool CanAccess( ResourceRequest resourceRequest )
        {
            if ( resourceRequest == null )
            {
                throw new ArgumentException ( "resource request is required." );
            }

            if ( resourceRequest.ResourceHierarchy.Count == 0 )
            {
                throw new ArgumentException ( "Invalid resource request." );
            }

            Permission requiredPermission = null;
            var canAccess = false;
            var resourceList = _resourceList;
            foreach ( var resourceName in resourceRequest.ResourceHierarchy )
            {
                if ( resourceList == null )
                {
                    break;
                }

                var name = resourceName;
                var resource = resourceList.FirstOrDefault ( r => r.Name == name );
                if ( resource == null )
                {
                    break;
                }

                requiredPermission = resource.Permission;
                resourceList = resource.Resources;
            }

            if ( requiredPermission != null )
            {
                canAccess = _currentUserPermissionService.DoesUserHavePermission ( requiredPermission );
                Logger.Debug (
                    "Permission ({0}) {1} for resource request ({2}).",
                    requiredPermission,
                    canAccess ? "granted" : "denied",
                    resourceRequest );
            }
            else
            {
                Logger.Debug ( "No permission defined for resource request ({0}).", resourceRequest );
            }

            return canAccess;
        }
      public void prova()
      {
         //persona = myres.Get<Person>(new {userId=10}, succ, err);
         
         //persona = myres.Action<Person>("fetch", new {userId=10}, succ, err);

         //persona.Action("fetch");
        
         ResourceRequest<Person> r = new ResourceRequest<Person>(myres);         
         r.Action = "fetch";
         r.Parameters["userId"] = 10;
         r.PostData = null;
         r.Success = succ;
         r.Error = err;
         persona = r.ExecuteRequest();

         persona.Action("save");
      }
        public ResourceResponse OnRequest(ResourceRequest request)
        {
            var path = request.Url.ToString().ToLower();

            try {
                path = path.IndexOf("?", StringComparison.InvariantCultureIgnoreCase) >= 0 ? path.Substring(0, path.IndexOf("?", StringComparison.InvariantCultureIgnoreCase)) : path;
                var fileName = path.Substring(path.LastIndexOf("/", StringComparison.InvariantCultureIgnoreCase) + 1);
                var ext = Path.GetExtension(fileName);
                var badFileName = !string.IsNullOrEmpty(ext) && !_enabledExtensions.Contains(ext.ToLower());
                if (badFileName) {
                    request.Cancel();
                    return null;
                }
            } catch (Exception e) {
                request.Cancel();
                return null;
            }

            return null;
        }
Beispiel #15
0
        /// <summary>
        /// Loads the data for the request asynchronously.
        /// </summary>
        /// <param name="request">The issued request.</param>
        /// <returns>The active download.</returns>
        public virtual IDownload DownloadAsync(ResourceRequest request)
        {
            var data = new Request
            {
                Address = request.Target,
                Method = HttpMethod.Get,
                Headers = new Dictionary<String, String>
                {
                    { HeaderNames.Referer, request.Source.Owner.DocumentUri }
                }
            };

            var cookie = GetCookie(request.Target);

            if (cookie != null)
            {
                data.Headers[HeaderNames.Cookie] = cookie;
            }

            return DownloadAsync(data, request.Source);
        }
        public ResourceResponse OnRequest(ResourceRequest request)
        {
            // This tries to get a local resource. If there is no local resource null is returned by GetLocalResource, which
            // triggers the default handler, which should respect the "target='_blank'" attribute added
            // in ParsedDocument.ToHtml(), thus avoiding a bug in Awesomium where trying to navigate to a
            // local resource fails when showing an in-memory file (https://github.com/Code52/DownmarkerWPF/pull/208)

            // What works:
            //	- resource requests for remote resources (like <link href="http://somecdn.../jquery.js"/>)
            //	- resource requests for local resources that exist relative to filename of the file (like <img src="images/logo.png"/>)
            //	- clicking links for remote resources (like [Google](http://www.google.com))
            //	- clicking links for local resources which don't exist (eg [test](test)) does nothing (WebControl_LinkClicked checks for existence)
            // What fails:
            //	- clicking links for local resources where the resource exists (like [test](images/logo.png))
            //		- This _sometimes_ opens the resource in the preview pane, and sometimes opens the resource 
            //		using Process.Start (WebControl_LinkClicked gets triggered). The behaviour seems stochastic.
            //	- alt text for images where the image resource is not found
            if (request.Url.ToString().StartsWith(LocalRequestUrlBase))
                return GetLocalResource(request.Url.ToString().Replace(LocalRequestUrlBase, ""));

            // If the request wasn't local, return null to let the usual handler load the url from the network			

            return null;
        }
        private void PutPastureInStore()
        {
            AmountHarvested           = 0;
            AmountAvailableForHarvest = 0;
            List <Ruminant> herd = new List <Ruminant>();

            if (this.TimingOK)
            {
                // determine amount to be cut and carried
                if (CutStyle != RuminantFeedActivityTypes.SpecifiedDailyAmount)
                {
                    herd = CurrentHerd(false);
                }
                switch (CutStyle)
                {
                case RuminantFeedActivityTypes.SpecifiedDailyAmount:
                    AmountHarvested += Supply * 30.4;
                    break;

                case RuminantFeedActivityTypes.ProportionOfWeight:
                    foreach (Ruminant ind in herd)
                    {
                        AmountHarvested += Supply * ind.Weight * 30.4;
                    }
                    break;

                case RuminantFeedActivityTypes.ProportionOfPotentialIntake:
                    foreach (Ruminant ind in herd)
                    {
                        AmountHarvested += Supply * ind.PotentialIntake;
                    }
                    break;

                case RuminantFeedActivityTypes.ProportionOfRemainingIntakeRequired:
                    foreach (Ruminant ind in herd)
                    {
                        AmountHarvested += Supply * (ind.PotentialIntake - ind.Intake);
                    }
                    break;

                default:
                    throw new Exception(String.Format("FeedActivityType {0} is not supported in {1}", CutStyle, this.Name));
                }

                AmountAvailableForHarvest = AmountHarvested;
                // reduce amount by limiter if present.
                if (limiter != null)
                {
                    double canBeCarried = limiter.GetAmountAvailable(Clock.Today.Month);
                    AmountHarvested = Math.Max(AmountHarvested, canBeCarried);
                    limiter.AddWeightCarried(AmountHarvested);
                }

                double labourlimiter = 1.0;


                AmountHarvested *= labourlimiter;

                if (AmountHarvested > 0)
                {
                    FoodResourcePacket packet = new FoodResourcePacket()
                    {
                        Amount   = AmountHarvested,
                        PercentN = pasture.Nitrogen,
                        DMD      = pasture.EstimateDMD(pasture.Nitrogen)
                    };

                    // take resource
                    ResourceRequest request = new ResourceRequest()
                    {
                        ActivityModel     = this,
                        AdditionalDetails = this,
                        Reason            = "Cut and carry",
                        Required          = AmountHarvested,
                        Resource          = pasture
                    };
                    pasture.Remove(request);

                    foodstore.Add(packet, this, "Cut and carry");
                }
                SetStatusSuccess();
            }
            // report activity performed.
            ActivityPerformedEventArgs activitye = new ActivityPerformedEventArgs
            {
                Activity = this
            };

            this.OnActivityPerformed(activitye);
        }
 public static IObservable <TAsset> AsObservable <TAsset>(this ResourceRequest This)
     where TAsset : Object =>
 Observable.FromCoroutine <TAsset>((observer, _) => AsObservableCore(This, observer));
Beispiel #19
0
 public static ResourceRequestAwaiter GetAwaiter(this ResourceRequest resourceRequest)
 {
     Error.ThrowArgumentNullException(resourceRequest, nameof(resourceRequest));
     return(new ResourceRequestAwaiter(resourceRequest));
 }
Beispiel #20
0
 /// <summary>
 /// 异步加载
 /// </summary>
 public void LoadAsync()
 {
     this.request = Resources.LoadAsync(AssetName, AssetType);
 }
Beispiel #21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            intProfile       = Int32.Parse(Request.Cookies["profileid"].Value);
            oProject         = new Projects(intProfile, dsn);
            oFunction        = new Functions(intProfile, dsn, intEnvironment);
            oUser            = new Users(intProfile, dsn);
            oPage            = new Pages(intProfile, dsn);
            oResourceRequest = new ResourceRequest(intProfile, dsn);
            oRequestItem     = new RequestItems(intProfile, dsn);
            oRequest         = new Requests(intProfile, dsn);
            oService         = new Services(intProfile, dsn);
            oRequestField    = new RequestFields(intProfile, dsn);
            oServiceRequest  = new ServiceRequests(intProfile, dsn);
            oApplication     = new Applications(intProfile, dsn);
            oCustomized      = new Customized(intProfile, dsn);
            oDelegate        = new Delegates(intProfile, dsn);
            if (Request.QueryString["applicationid"] != null && Request.QueryString["applicationid"] != "")
            {
                intApplication = Int32.Parse(Request.QueryString["applicationid"]);
            }
            if (Request.QueryString["pageid"] != null && Request.QueryString["pageid"] != "")
            {
                intPage = Int32.Parse(Request.QueryString["pageid"]);
            }
            if (Request.Cookies["application"] != null && Request.Cookies["application"].Value != "")
            {
                intApplication = Int32.Parse(Request.Cookies["application"].Value);
            }
            if (Request.QueryString["rrid"] != null && Request.QueryString["rrid"] != "")
            {
                // Start Workflow Change
                lblResourceWorkflow.Text = Request.QueryString["rrid"];
                int     intResourceWorkflow = Int32.Parse(Request.QueryString["rrid"]);
                int     intResourceParent   = oResourceRequest.GetWorkflowParent(intResourceWorkflow);
                DataSet ds = oResourceRequest.Get(intResourceParent);
                // End Workflow Change
                intRequest = Int32.Parse(ds.Tables[0].Rows[0]["requestid"].ToString());
                intItem    = Int32.Parse(ds.Tables[0].Rows[0]["itemid"].ToString());
                intNumber  = Int32.Parse(ds.Tables[0].Rows[0]["number"].ToString());
                // Start Workflow Change
                bool boolComplete = (oResourceRequest.GetWorkflow(intResourceWorkflow, "status") == "3");
                int  intUser      = Int32.Parse(oResourceRequest.GetWorkflow(intResourceWorkflow, "userid"));
                txtCustom.Text = oResourceRequest.GetWorkflow(intResourceWorkflow, "name");
                double dblAllocated = double.Parse(oResourceRequest.GetWorkflow(intResourceWorkflow, "allocated"));
                // End Workflow Change
                int intService = Int32.Parse(ds.Tables[0].Rows[0]["serviceid"].ToString());
                lblService.Text = oService.Get(intService, "name");
                int intApp = oRequestItem.GetItemApplication(intItem);

                double dblUsed = oResourceRequest.GetWorkflowUsed(intResourceWorkflow);
                lblUpdated.Text = oResourceRequest.GetUpdated(intResourceWorkflow);
                if (oService.Get(intService, "sla") != "")
                {
                    oFunction.ConfigureToolButton(btnSLA, "/images/tool_sla");
                    int intDays = oResourceRequest.GetSLA(intResourceParent);
                    if (intDays < 1)
                    {
                        btnSLA.Style["border"] = "solid 2px #FF0000";
                    }
                    else if (intDays < 3)
                    {
                        btnSLA.Style["border"] = "solid 2px #FF9999";
                    }
                    btnSLA.Attributes.Add("onclick", "return OpenWindow('RESOURCE_REQUEST_SLA','?rrid=" + intResourceParent.ToString() + "');");
                }
                else
                {
                    btnSLA.ImageUrl = "/images/tool_sla_dbl.gif";
                    btnSLA.Enabled  = false;
                }
                dblUsed = (dblUsed / dblAllocated) * 100;
                if (Request.QueryString["save"] != null && Request.QueryString["save"] != "")
                {
                    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "saved", "<script type=\"text/javascript\">alert('Information Saved Successfully');<" + "/" + "script>");
                }
                if (Request.QueryString["status"] != null && Request.QueryString["status"] != "")
                {
                    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "statusd", "<script type=\"text/javascript\">alert('Status Updates has been Added');<" + "/" + "script>");
                }
                intProject          = oRequest.GetProjectNumber(intRequest);
                hdnTab.Value        = "D";
                panWorkload.Visible = true;
                LoadStatus(intResourceWorkflow);
                bool boolDone = LoadInformation(intResourceWorkflow);
                if (boolDone == true)
                {
                    if (boolComplete == false)
                    {
                        oFunction.ConfigureToolButton(btnComplete, "/images/tool_complete");
                        btnComplete.Attributes.Add("onclick", "return confirm('Are you sure you want to mark this as completed and remove it from your workload?');");
                    }
                    else
                    {
                        oFunction.ConfigureToolButton(btnComplete, "/images/tool_complete");
                        btnComplete.Attributes.Add("onclick", "alert('This task has already been marked COMPLETE. You can close this window.');return false;");
                    }
                }
                else
                {
                    btnComplete.ImageUrl = "/images/tool_complete_dbl.gif";
                    btnComplete.Enabled  = false;
                }

                btnDenied.Attributes.Add("onclick", "return CloseWindow();");
                oFunction.ConfigureToolButton(btnSave, "/images/tool_save");
                oFunction.ConfigureToolButton(btnPrint, "/images/tool_print");
                btnPrint.Attributes.Add("onclick", "return PrintWindow();");
                oFunction.ConfigureToolButton(btnClose, "/images/tool_close");
                btnClose.Attributes.Add("onclick", "return ExitWindow();");
                btnSave.Attributes.Add("onclick", "return ValidateStatus('" + ddlStatus.ClientID + "','" + txtComments.ClientID + "');");
                // 6/1/2009 - Load ReadOnly View
                if (oResourceRequest.CanUpdate(intProfile, intResourceWorkflow, false) == false)
                {
                    oFunction.ConfigureToolButtonRO(btnSave, btnComplete);
                    //panDenied.Visible = true;
                }
            }
            else
            {
                panDenied.Visible = true;
            }
        }
Beispiel #22
0
        private IntPtr internalResourceRequestCallback(IntPtr caller, IntPtr request)
        {
            ResourceRequest requestWrap = new ResourceRequest(request);

            ResourceRequestEventArgs e = new ResourceRequestEventArgs(this, requestWrap);

            if (OnResourceRequest != null)
            {
                ResourceResponse response = OnResourceRequest(this, e);

                if (response != null)
                    return response.getInstance();
            }

            return IntPtr.Zero;
        }
Beispiel #23
0
 public RequestProcessResource(ResourceRequest req)
 {
     mReq = req;
 }
Beispiel #24
0
 public static IEnumerator LoadAssetFromResources(System.Action<GameObject> ReturnObject, string AssetName) {
     ResourceRequest resourceRequest = null;
     resourceRequest = Resources.LoadAsync(AssetName);
     yield return resourceRequest;
     ReturnObject(Instantiate<GameObject>((GameObject)resourceRequest.asset));
 }
 public void UpdateProgress(ResourceRequest resourceRequest)
 {
     isDone   = resourceRequest.isDone;
     progress = resourceRequest.progress;
 }
Beispiel #26
0
        public TestWriteInvalidInputUserField() : base()
        {
            var fieldRequestBuilder = FieldRequest.CreateFields();

            foreach (var resourceId in Enum.GetValues(typeof(Enums.ResourceType)).Cast <Enums.ResourceType>())
            {
                fieldRequestBuilder.Append((ResourceId)(int)resourceId, HRBCClientPrivate.API.Field.FieldType.SingleLineText, "API automation test field",
                                           builder => builder.TextLength(TextLength), $"{resourceId}");
            }
            var fieldRequest = ((CreateFieldsRequest.IBuilderWithRecord)fieldRequestBuilder).Build().Content;

            customFields = new HrbcFieldCreator(fieldRequest, new List <FieldProperty> {
                FieldProperty.Id, FieldProperty.Name, FieldProperty.Resource
            });
            int testUser = 1;

            records = new HrbcRecordCreator(() => ResourceRequest.CreateRecords()
                                            .Append(ResourceId.Client,
                                                    content => content
                                                    .Append("P_Name", "Test Client")
                                                    .Append("P_Owner", testUser),
                                                    "client1")
                                            .Append(ResourceId.Recruiter,
                                                    content => content
                                                    .Append("P_Name", "Test Recruiter")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1")),
                                                    "recruiter1")
                                            .Append(ResourceId.Job,
                                                    content => content
                                                    .Append("P_Position", "Test Job")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1"))
                                                    .Append("P_Recruiter", new CreateRecordRequest.Reference("recruiter1")),
                                                    "job1")
                                            .Append(ResourceId.Job,
                                                    content => content
                                                    .Append("P_Position", "Test Job")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1"))
                                                    .Append("P_Recruiter", new CreateRecordRequest.Reference("recruiter1")),
                                                    "job2")
                                            .Append(ResourceId.Person,
                                                    content => content
                                                    .Append("P_Name", "Test Person")
                                                    .Append("P_Owner", testUser),
                                                    "person1")
                                            .Append(ResourceId.Resume,
                                                    content => content
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Candidate", new CreateRecordRequest.Reference("person1")),
                                                    "resume1")
                                            .Append(ResourceId.Resume,
                                                    content => content
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Candidate", new CreateRecordRequest.Reference("person1")),
                                                    "resume2")

                                            /* Example of a progress element:
                                             *               .Append(ResourceId.Process,
                                             *                  content => content
                                             *                      .Append("P_Owner", testUser)
                                             *                      .Append("P_Client", new CreateRecordRequest.Reference("client"))
                                             *                      .Append("P_Recruiter", new CreateRecordRequest.Reference("recruiter"))
                                             *                      .Append("P_Job", new CreateRecordRequest.Reference("job"))
                                             *                      .Append("P_Candidate", new CreateRecordRequest.Reference("person"))
                                             *                      .Append("P_Resume", new CreateRecordRequest.Reference("resume")),
                                             *                  "process")
                                             */
                                            .Append(ResourceId.Sales,
                                                    content => content
                                                    //.Append("P_SalesAmount", 5000)
                                                    .Append("P_Owner", testUser),
                                                    "sales1")
                                            .Append(ResourceId.Activity,
                                                    content => content
                                                    .Append("P_Title", "Test Activity")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_FromDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                                                    "activity1")
                                            .Append(ResourceId.Contract,
                                                    content => content
                                                    .Append("P_Name", "Test Contract")
                                                    //.Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1")),
                                                    "contract1"));
        }
 public static ResourcesRequestAwaiter GetAwaiter(this ResourceRequest asyncOp) =>
 new ResourcesRequestAwaiter(asyncOp);
Beispiel #28
0
        private System.Collections.IEnumerator LoadCoroutine <T>(ResourceInfoBase info, Action <float> loadingAction, Action <T> loadDoneAction, bool isPrefab = false, Transform parent = null, bool isUI = false) where T : UnityEngine.Object
        {
            if (!_isLoading)
            {
                _isLoading = true;
            }
            else
            {
                yield return(_loadWait);
            }

            UnityEngine.Object asset = null;

            if (Mode == ResourceMode.Resource)
            {
                ResourceRequest request = Resources.LoadAsync <T>(info.ResourcePath);
                while (!request.isDone)
                {
                    if (loadingAction != null)
                    {
                        loadingAction(request.progress);
                    }
                    yield return(null);
                }
                asset = request.asset;
                if (!asset)
                {
                    GlobalTools.LogError("加载资源失败:Resources文件夹中不存在 " + typeof(T) + " 资源 " + info.ResourcePath);
                }
                else
                {
                    if (isPrefab)
                    {
                        asset = ClonePrefab(asset as GameObject, parent, isUI);
                    }
                }
            }
            else
            {
#if UNITY_EDITOR
                if (loadingAction != null)
                {
                    loadingAction(1);
                }
                yield return(null);

                asset = AssetDatabase.LoadAssetAtPath <T>(info.AssetPath);
                if (!asset)
                {
                    GlobalTools.LogError("加载资源失败:路径中不存在资源 " + info.AssetPath);
                }
                else
                {
                    if (isPrefab)
                    {
                        asset = ClonePrefab(asset as GameObject, parent, isUI);
                    }
                }
#else
                if (_assetBundles.ContainsKey(info.AssetBundleName))
                {
                    if (loadingAction != null)
                    {
                        loadingAction(1);
                    }
                    yield return(null);

                    asset = _assetBundles[info.AssetBundleName].LoadAsset <T>(info.AssetPath);
                    if (!asset)
                    {
                        GlobalTools.LogError("加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath);
                    }
                    else
                    {
                        if (isPrefab)
                        {
                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                        }
                    }
                }
                else
                {
                    UnityWebRequest            request = UnityWebRequest.Get(_assetBundlePath + info.AssetBundleName);
                    DownloadHandlerAssetBundle handler = new DownloadHandlerAssetBundle(request.url, 0);
                    request.downloadHandler = handler;
                    request.SendWebRequest();
                    while (!request.isDone)
                    {
                        if (loadingAction != null)
                        {
                            loadingAction(request.downloadProgress);
                        }
                        yield return(null);
                    }
                    if (!request.isNetworkError && !request.isHttpError)
                    {
                        if (handler.assetBundle)
                        {
                            asset = handler.assetBundle.LoadAsset <T>(info.AssetPath);
                            if (!asset)
                            {
                                GlobalTools.LogError("加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath);
                            }
                            else
                            {
                                if (isPrefab)
                                {
                                    asset = ClonePrefab(asset as GameObject, parent, isUI);
                                }
                            }

                            if (IsCacheAssetBundle)
                            {
                                if (!_assetBundles.ContainsKey(info.AssetBundleName))
                                {
                                    _assetBundles.Add(info.AssetBundleName, handler.assetBundle);
                                }
                            }
                            else
                            {
                                handler.assetBundle.Unload(false);
                            }
                        }
                        else
                        {
                            GlobalTools.LogError("请求:" + request.url + " 未下载到AB包!");
                        }
                    }
                    else
                    {
                        GlobalTools.LogError("请求:" + request.url + " 遇到网络错误:" + request.error);
                    }
                    request.Dispose();
                    handler.Dispose();
                }
#endif
            }

            if (asset)
            {
                DataSetInfo dataSet = info as DataSetInfo;
                if (dataSet != null && dataSet.Data != null)
                {
                    (asset as DataSet).Fill(dataSet.Data);
                }

                if (loadDoneAction != null)
                {
                    loadDoneAction(asset as T);
                }
            }
            asset = null;

            _isLoading = false;
        }
Beispiel #29
0
    // Method that loads a terrain
    public IEnumerator Load(string fileName, bool instantiateCamera)
    {
        // Create the load path
        string path = "Saved Maps/" + fileName;

        // Create a binaryFormatter
        BinaryFormatter binaryFormatter = new BinaryFormatter();

        // load the map at path as a textasset
        ResourceRequest request = Resources.LoadAsync(path);

        yield return(request);

        TextAsset loaded = (TextAsset)request.asset;
        // create a memory stream of the bytes in the loaded textasset
        MemoryStream stream = new MemoryStream(loaded.bytes);
        float        timeS  = Time.realtimeSinceStartup;
        // Deserialize to a world terrainsaver objects
        TerrainSaver world = (TerrainSaver)binaryFormatter.Deserialize(stream);

        Debug.Log(Time.realtimeSinceStartup - timeS);
        // get all terrain parameters
        length    = world.length;
        width     = world.width;
        maxHeight = world.maxHeight;
        seed      = world.seed;

        terrainOctaves     = world.terrainOctaves;
        terrainPersistance = world.terrainPersistance;
        terrainFrequency   = world.terrainFrequency;
        biomeOctaves       = world.biomeOctaves;
        biomePersistance   = world.biomePersistance;
        biomeFrequency     = world.biomeFrequency;

        chunkSize = world.chunkSize;
        tileSize  = world.tileSize;
        tileSlope = world.tileSlope;

        waterChunkSize   = world.waterChunkSize;
        waterTileSize    = world.waterTileSize;
        waterOctaves     = world.waterOctaves;
        waterPersistance = world.waterPersistance;
        waterFrequency   = world.waterFrequency;
        waterLevel       = world.waterLevel;
        maxWaveHeight    = world.maxWaveHeight;

        // Get the list of all chunks
        List <TerrainSaveObject> chunkList = world.terrainSaveList;

        // Initialize the code so the map can be created
        Initialize();

        // Loop through all chunks and recreate them with their respective parameters
        float timeSinceUpdate = Time.realtimeSinceStartup;
        int   index           = 0;

        foreach (TerrainSaveObject obj in chunkList)
        {
            GameObject curChunk    = (GameObject)Instantiate(chunkPrefab, obj.chunkLoc.GetVec3(), Quaternion.identity);
            Chunk      chunkScript = curChunk.GetComponent <Chunk>();
            chunkScript.map      = obj.GetVec3Map();
            chunkScript.biomeMap = obj.biomeMap;
            curChunk.transform.SetParent(transform);
            // try to save ram by deleting the chunks from the chunklist
            chunkList[index] = null;
            System.GC.Collect();

            // Show an update if a certain ammount of chunks has been built
            if (Time.realtimeSinceStartup - timeSinceUpdate > 1f / 10f)
            {
                timeSinceUpdate = Time.realtimeSinceStartup;
                yield return(null);
            }

            index++;
        }

        // Create the water
        BuildWater();

        // Create all biome objects
        StartCoroutine(GenerateBiomeAttributes());
    }
Beispiel #30
0
        /// <summary>
        /// When overridden in a derived class, is invoked whenever application code or internal processes (such as a rebuilding layout pass) call <see cref="M:System.Windows.Controls.Control.ApplyTemplate"/>. In simplest terms, this means the method is called just before a UI element displays in an application. For more information, see Remarks.
        /// </summary>
        public override void OnApplyTemplate ()
        {
            base.OnApplyTemplate ();
            if ( string.IsNullOrEmpty ( Name ) )
            {
                throw new InvalidOperationException ( "A secure control requires the Name property to be set." );
            }

            //TODO: adding RadTileViewItem here but should be some cleaner way of adding more parent realm types
            var parentRealm = this.FindAncestor<UserControl> () ?? ( FrameworkElement )this.FindAncestor<RadTileViewItem> ();
            if ( parentRealm == null )
            {
                parentRealm = this.FindAncestor<ChildWindow> ();
            }

            //TODO: revisit this to possibly not require secure control to be in a user control
            if ( parentRealm == null && HtmlPage.IsEnabled )
            {
                throw new InvalidOperationException ( "A secure control must be a child of a user control or Child Window." );
            }
            _resourceRequest = new ResourceRequest { parentRealm.GetType ().FullName, ( string.IsNullOrEmpty ( Name ) ? string.Empty : Name ) };
            CheckRemAccess ();
        }
 private IDownload DownloadWithCors(ResourceRequest request)
 {
     return _loader.FetchWithCors(new CorsRequest(request)
     {
         Setting = _link.CrossOrigin.ToEnum(CorsSetting.None),
         Behavior = OriginBehavior.Taint,
         Integrity = _document.Options.GetProvider<IIntegrityProvider>()
     });
 }
        public TestReadValidInputApplicationField() : base()
        {
            List <FieldProperty> select = new List <FieldProperty>()
            {
                FieldProperty.TextLength
            };

            readFields = new HrbcFieldReader(new List <string> {
                AppField
            }, select);

            int testUser = 1;

            records = new HrbcRecordCreator(() => ResourceRequest.CreateRecords()
                                            .Append(ResourceId.Client,
                                                    content => content
                                                    .Append("P_Name", "Test Client")
                                                    .Append("P_Owner", testUser),
                                                    "client1")
                                            .Append(ResourceId.Recruiter,
                                                    content => content
                                                    .Append("P_Name", "Test Recruiter")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1")),
                                                    "recruiter1")
                                            .Append(ResourceId.Job,
                                                    content => content
                                                    .Append("P_Position", "Test Job")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1"))
                                                    .Append("P_Recruiter", new CreateRecordRequest.Reference("recruiter1")),
                                                    "job1")
                                            .Append(ResourceId.Job,
                                                    content => content
                                                    .Append("P_Position", "Test Job")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1"))
                                                    .Append("P_Recruiter", new CreateRecordRequest.Reference("recruiter1")),
                                                    "job2")
                                            .Append(ResourceId.Person,
                                                    content => content
                                                    .Append("P_Name", "Test Person")
                                                    .Append("P_Owner", testUser),
                                                    "person1")
                                            .Append(ResourceId.Resume,
                                                    content => content
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Candidate", new CreateRecordRequest.Reference("person1")),
                                                    "resume1")
                                            .Append(ResourceId.Resume,
                                                    content => content
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Candidate", new CreateRecordRequest.Reference("person1")),
                                                    "resume2")

                                            /* Example of a progress element:
                                             *               .Append(ResourceId.Process,
                                             *                  content => content
                                             *                      .Append("P_Owner", testUser)
                                             *                      .Append("P_Client", new CreateRecordRequest.Reference("client"))
                                             *                      .Append("P_Recruiter", new CreateRecordRequest.Reference("recruiter"))
                                             *                      .Append("P_Job", new CreateRecordRequest.Reference("job"))
                                             *                      .Append("P_Candidate", new CreateRecordRequest.Reference("person"))
                                             *                      .Append("P_Resume", new CreateRecordRequest.Reference("resume")),
                                             *                  "process")
                                             */
                                            .Append(ResourceId.Sales,
                                                    content => content
                                                    //.Append("P_SalesAmount", 5000)
                                                    .Append("P_Owner", testUser),
                                                    "sales1")
                                            .Append(ResourceId.Activity,
                                                    content => content
                                                    .Append("P_Title", "Test Activity")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_FromDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                                                    "activity1")
                                            .Append(ResourceId.Contract,
                                                    content => content
                                                    .Append("P_Name", "Test Contract")
                                                    //.Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1")),
                                                    "contract1"));
        }
        private void OnCLEMAnimalSell(object sender, EventArgs e)
        {
            // Sell excess above store reserve level calculated from AE and daily target of first feed target
            // Performed here so all activities have access to human food stores before being sold.

            if (SellExcess && TimingOK)
            {
                // only uses the first target metric as measure
                double[] stored      = new double[MonthsStorage + 1];
                double[] target      = new double[MonthsStorage + 1];
                int[]    daysInMonth = new int[MonthsStorage + 1];

                // determine AEs to be fed - NOTE does not account ofr aging in reserve calcualtion
                double aE = people.Items.Where(a => IncludeHiredLabour || a.Hired == false).Sum(a => a.AdultEquivalent);

                LabourActivityFeedTarget feedTarget = this.FindAllChildren <LabourActivityFeedTarget>().FirstOrDefault() as LabourActivityFeedTarget;

                for (int i = 1; i <= MonthsStorage; i++)
                {
                    DateTime month = Clock.Today.AddMonths(i);
                    daysInMonth[i] = DateTime.DaysInMonth(month.Year, month.Month);
                    target[i]      = daysInMonth[i] * aE * feedTarget.TargetValue;
                }

                foreach (HumanFoodStoreType foodStore in food.FindAllChildren <HumanFoodStoreType>().Cast <HumanFoodStoreType>().ToList())
                {
                    double amountStored    = 0;
                    double amountAvailable = foodStore.Pools.Sum(a => a.Amount);

                    if (amountAvailable > 0)
                    {
                        foreach (HumanFoodStorePool pool in foodStore.Pools.OrderBy(a => ((foodStore.UseByAge == 0) ? MonthsStorage : a.Age)))
                        {
                            if (foodStore.UseByAge != 0 && pool.Age == foodStore.UseByAge)
                            {
                                // don't sell food expiring this month as spoiled
                                amountStored += pool.Amount;
                            }
                            else
                            {
                                int    currentMonth  = ((foodStore.UseByAge == 0) ? MonthsStorage : foodStore.UseByAge - pool.Age + 1);
                                double poolRemaining = pool.Amount;
                                while (currentMonth > 0)
                                {
                                    if (stored[currentMonth] < target[currentMonth])
                                    {
                                        // place amount in store
                                        double amountNeeded       = target[currentMonth] - stored[currentMonth];
                                        double towardTarget       = pool.Amount * foodStore.EdibleProportion * foodStore.ConversionFactor(feedTarget.Metric);
                                        double amountSupplied     = Math.Min(towardTarget, amountNeeded);
                                        double proportionProvided = amountSupplied / towardTarget;

                                        amountStored         += pool.Amount * proportionProvided;
                                        poolRemaining        -= pool.Amount * proportionProvided;
                                        stored[currentMonth] += amountSupplied;

                                        if (poolRemaining <= 0)
                                        {
                                            break;
                                        }
                                    }
                                    currentMonth--;
                                }
                            }
                        }

                        double amountSold = amountAvailable - amountStored;
                        if (amountSold > 0)
                        {
                            ResourcePricing priceToUse = new ResourcePricing()
                            {
                                PacketSize = 1
                            };
                            if (foodStore.PricingExists(PurchaseOrSalePricingStyleType.Purchase))
                            {
                                priceToUse = foodStore.Price(PurchaseOrSalePricingStyleType.Purchase);
                            }

                            double units = amountSold / priceToUse.PacketSize;
                            if (priceToUse.UseWholePackets)
                            {
                                units = Math.Truncate(units);
                            }
                            // remove resource
                            ResourceRequest purchaseRequest = new ResourceRequest
                            {
                                ActivityModel               = this,
                                Required                    = units * priceToUse.PacketSize,
                                AllowTransmutation          = false,
                                Reason                      = "Sell excess",
                                MarketTransactionMultiplier = this.FarmMultiplier
                            };
                            foodStore.Remove(purchaseRequest);

                            // transfer money earned
                            if (bankAccount != null)
                            {
                                ResourceRequest purchaseFinance = new ResourceRequest
                                {
                                    ActivityModel               = this,
                                    Required                    = units * priceToUse.PacketSize,
                                    AllowTransmutation          = false,
                                    Reason                      = $"Sales {foodStore.Name}",
                                    MarketTransactionMultiplier = this.FarmMultiplier
                                };
                                bankAccount.Add(purchaseFinance, this, $"Sales {foodStore.Name}");
                            }
                        }
                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            intProfile      = Int32.Parse(Request.Cookies["profileid"].Value);
            oProjectRequest = new ProjectRequest(intProfile, dsn);
            oApprove        = new ProjectRequest_Approval(intProfile, dsn, intEnvironment);
            oProject        = new Projects(intProfile, dsn);
            oAD             = new AD(intProfile, dsn, intEnvironment);
            oFunction       = new Functions(intProfile, dsn, intEnvironment);
            oUser           = new Users(intProfile, dsn);
            int intRequest = 0;

            oApplication     = new Applications(intProfile, dsn);
            oPage            = new Pages(intProfile, dsn);
            oAppPage         = new AppPages(intProfile, dsn);
            oVariable        = new Variables(intEnvironment);
            oOrganization    = new Organizations(intProfile, dsn);
            oRequestItem     = new RequestItems(intProfile, dsn);
            oService         = new Services(intProfile, dsn);
            oResourceRequest = new ResourceRequest(intProfile, dsn);
            oRequest         = new Requests(intProfile, dsn);
            oDocument        = new Documents(intProfile, dsn);
            bool boolWorkflow = false;

            if (Request.QueryString["action"] != null && Request.QueryString["action"] != "")
            {
                panFinish.Visible = true;
                if (Request.QueryString["rid"] != null && Request.QueryString["rid"] != "")
                {
                    lblRequest.Text = Request.QueryString["rid"];
                }
            }
            else
            {
                if (Request.QueryString["applicationid"] != null && Request.QueryString["applicationid"] != "")
                {
                    intApplication = Int32.Parse(Request.QueryString["applicationid"]);
                }
                if (Request.QueryString["pageid"] != null && Request.QueryString["pageid"] != "")
                {
                    intPage = Int32.Parse(Request.QueryString["pageid"]);
                }
                if (Request.Cookies["application"] != null && Request.Cookies["application"].Value != "")
                {
                    intApplication = Int32.Parse(Request.Cookies["application"].Value);
                }
                if (!IsPostBack)
                {
                    if (Request.QueryString["rid"] != null && Request.QueryString["rid"] != "")
                    {
                        intRequest      = Int32.Parse(Request.QueryString["rid"]);
                        lblRequest.Text = Request.QueryString["rid"];
                    }
                    if (intRequest > 0)
                    {
                        ds = oApprove.Get(intRequest, intProfile);
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            bool boolButtons = false;
                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                if (dr["approval"].ToString() == "0")
                                {
                                    boolButtons  = true;
                                    lblStep.Text = dr["step"].ToString();
                                }
                                boolWorkflow           = true;
                                panDiscussion.Visible  = true;
                                rptComments.DataSource = oProjectRequest.GetComments(intRequest);
                                rptComments.DataBind();
                                foreach (RepeaterItem ri in rptComments.Items)
                                {
                                    LinkButton oDelete = (LinkButton)ri.FindControl("btnDelete");
                                    oDelete.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this comment?');");
                                }
                                lblNoComments.Visible = (rptComments.Items.Count == 0);
                                lblUser.Text          = oUser.GetFullName(oUser.GetName(intProfile));
                            }
                            btnApprove.Enabled = boolButtons;
                            btnDeny.Enabled    = boolButtons;
                            btnShelf.Enabled   = boolButtons;
                        }
                    }
                    else if (Int32.Parse(oProjectRequest.Get(intRequest, "userid")) == intProfile)
                    {
                        boolWorkflow           = true;
                        panDiscussionX.Visible = true;
                    }
                    if (boolWorkflow == true)
                    {
                        panWorkflow.Visible = true;
                        string strApplication = "";
                        if (intApplication > 0)
                        {
                            ds             = oApplication.Get(intApplication);
                            strApplication = ds.Tables[0].Rows[0]["url"].ToString();
                        }
                        ds = oProjectRequest.Get(intRequest);
                        DataSet dsRequest  = oRequest.Get(intRequest);
                        int     intProject = Int32.Parse(dsRequest.Tables[0].Rows[0]["projectid"].ToString());
                        DataSet dsProject  = oProject.Get(intProject);
                        // PRIORITY
                        strPriority = "<div align=\"center\">" + oProjectRequest.GetPriority(intRequest, intEnvironment) + "</div>";
                        // DOCUMENTS
                        chkDescription.Checked = (Request.QueryString["doc"] != null);
                        lblDocuments.Text      = oDocument.GetDocuments_Project(intProject, intProfile, oVariable.DocumentsFolder(), 1, (Request.QueryString["doc"] != null));
                        // GetDocuments(string _physical, int _projectid, int _requestid, int _userid, int _security, bool _show_description, bool _mine)
                        //lblDocuments.Text = oDocument.GetDocuments(Request.PhysicalApplicationPath, intProject, 0, intProfile, 1, (Request.QueryString["doc"] != null), false);
                        // DETAILS
                        int intRequestor = Int32.Parse(dsRequest.Tables[0].Rows[0]["userid"].ToString());
                        lblName2.Text        = oUser.GetFullName(intRequestor);
                        lblDate2.Text        = ds.Tables[0].Rows[0]["modified"].ToString();
                        lblProjectTask.Text  = dsProject.Tables[0].Rows[0]["name"].ToString();
                        lblOrganization.Text = oOrganization.GetName(Int32.Parse(dsProject.Tables[0].Rows[0]["organization"].ToString()));
                        lblBaseDisc.Text     = dsProject.Tables[0].Rows[0]["bd"].ToString();
                        lblClarity2.Text     = dsProject.Tables[0].Rows[0]["number"].ToString();
                        if (lblClarity2.Text == "")
                        {
                            lblClarity2.Text = "<i>To Be Determined</i>";
                        }
                        lblExecutive2.Text = oUser.GetFullName(Int32.Parse(oProject.Get(intProject, "executive")));
                        lblWorking2.Text   = oUser.GetFullName(Int32.Parse(oProject.Get(intProject, "working")));
                        lblC1.Text         = (ds.Tables[0].Rows[0]["c1"].ToString() == "1" ? "Yes" : "No");
                        lblEndLife.Text    = (ds.Tables[0].Rows[0]["endlife"].ToString() == "1" ? "Yes" : "No");
                        if (ds.Tables[0].Rows[0]["endlife_date"].ToString() == "")
                        {
                            lblEndLifeDate.Text = "<i>Not Applicable</i>";
                        }
                        else
                        {
                            lblEndLifeDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["endlife_date"].ToString()).ToShortDateString();
                        }
                        lblInitiative.Text  = dsRequest.Tables[0].Rows[0]["description"].ToString();
                        lblRequirement.Text = (ds.Tables[0].Rows[0]["req_type"].ToString() == "1" ? "Yes" : "No");
                        if (ds.Tables[0].Rows[0]["req_date"].ToString() == "")
                        {
                            lblRequirementDate.Text = "<i>Not Applicable</i>";
                        }
                        else
                        {
                            lblRequirementDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["req_date"].ToString()).ToShortDateString();
                        }
                        lblInterdependency.Text      = ds.Tables[0].Rows[0]["interdependency"].ToString();
                        lblProjects.Text             = ds.Tables[0].Rows[0]["projects"].ToString();
                        lblCapability.Text           = ds.Tables[0].Rows[0]["capability"].ToString();
                        lblHours.Text                = ds.Tables[0].Rows[0]["man_hours"].ToString();
                        lblStart.Text                = DateTime.Parse(dsRequest.Tables[0].Rows[0]["start_date"].ToString()).ToShortDateString();
                        lblCompletion.Text           = DateTime.Parse(dsRequest.Tables[0].Rows[0]["end_date"].ToString()).ToShortDateString();
                        lblCapital.Text              = ds.Tables[0].Rows[0]["expected_capital"].ToString();
                        lblInternal.Text             = ds.Tables[0].Rows[0]["internal_labor"].ToString();
                        lblExternal.Text             = ds.Tables[0].Rows[0]["external_labor"].ToString();
                        lblMaintenance.Text          = ds.Tables[0].Rows[0]["maintenance_increase"].ToString();
                        lblExpenses.Text             = ds.Tables[0].Rows[0]["project_expenses"].ToString();
                        lblCostAvoidance.Text        = ds.Tables[0].Rows[0]["estimated_avoidance"].ToString();
                        lblSavings.Text              = ds.Tables[0].Rows[0]["estimated_savings"].ToString();
                        lblRealized.Text             = ds.Tables[0].Rows[0]["realized_savings"].ToString();
                        lblBusinessAvoidance.Text    = ds.Tables[0].Rows[0]["business_avoidance"].ToString();
                        lblMaintenanceAvoidance.Text = ds.Tables[0].Rows[0]["maintenance_avoidance"].ToString();
                        lblReusability.Text          = ds.Tables[0].Rows[0]["asset_reusability"].ToString();
                        lblInternalImpact.Text       = ds.Tables[0].Rows[0]["internal_impact"].ToString();
                        lblExternalImpact.Text       = ds.Tables[0].Rows[0]["external_impact"].ToString();
                        lblImpact.Text               = ds.Tables[0].Rows[0]["business_impact"].ToString();
                        lblStrategic.Text            = ds.Tables[0].Rows[0]["strategic_opportunity"].ToString();
                        lblAcquisition.Text          = ds.Tables[0].Rows[0]["acquisition"].ToString();
                        lblCapabilities.Text         = ds.Tables[0].Rows[0]["technology_capabilities"].ToString();
                        lblTPM2.Text = (ds.Tables[0].Rows[0]["tpm"].ToString() == "1" ? "Yes" : "No");
                        if (ds.Tables[0].Rows[0]["modified"].ToString() != "")
                        {
                            lblUpdated.Visible = true;
                            DateTime _updated = DateTime.Parse(ds.Tables[0].Rows[0]["modified"].ToString());
                            lblUpdated.Text = "<img src='/images/bigAlert.gif' border='0' align='absmiddle' /> This project request was updated on " + _updated.ToShortDateString() + " at " + _updated.ToShortTimeString();
                        }
                        ds = oProjectRequest.GetPlatforms(intRequest);
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            lblPlatforms.Text += dr["name"].ToString() + "<br/>";
                        }
                        dsProject = oProjectRequest.GetResources(intRequest);
                        if (dsProject.Tables[0].Rows.Count > 0)
                        {
                            int intItem     = Int32.Parse(dsProject.Tables[0].Rows[0]["itemid"].ToString());
                            int intService  = Int32.Parse(dsProject.Tables[0].Rows[0]["serviceid"].ToString());
                            int intAccepted = Int32.Parse(dsProject.Tables[0].Rows[0]["accepted"].ToString());
                            int intManager  = Int32.Parse(dsProject.Tables[0].Rows[0]["userid"].ToString());
                            if (intItem > 0)
                            {
                                lblTPMService.Text = oService.GetName(intService);
                                panTPM.Visible     = true;
                            }
                            panPM.Visible = true;
                            if (intAccepted == -1)
                            {
                                lblPM.Text = "Pending Assignment (" + oUser.GetFullName(intRequestor) + ")";
                            }
                            else if (intManager > 0)
                            {
                                lblPM.Text = oUser.GetFullName(intManager);
                            }
                            else if (intItem > 0)
                            {
                                lblPM.Text = "Pending Assignment";
                            }
                        }
                        // HISTORY
                        rptHistory.DataSource = oApprove.Get(intRequest);
                        rptHistory.DataBind();
                        int intStep = oApprove.GetStep(intRequest);
                        foreach (RepeaterItem ri in rptHistory.Items)
                        {
                            Label oStep   = (Label)ri.FindControl("lblStep");
                            Label oUserId = (Label)ri.FindControl("lblUserId");
                            int   intUser = Int32.Parse(oUserId.Text);
                            if (intUser > 0)
                            {
                                oUserId.Text = oUser.GetFullName(intUser);
                            }
                            else
                            {
                                oUserId.Text = "---";
                            }
                            Label oImage    = (Label)ri.FindControl("lblImage");
                            Label oModified = (Label)ri.FindControl("lblModified");
                            Label oApproval = (Label)ri.FindControl("lblApproval");
                            switch (oApproval.Text)
                            {
                            case "-100":
                                oApproval.Text     = "<span class=\"expedited\">EXPEDITED</span>";
                                oModified.Text     = "Not Available";
                                oModified.CssClass = "pending";
                                break;

                            case "-10":
                                oApproval.Text = "<span class=\"waiting\">Waiting</span>";
                                break;

                            case "-1":
                                oApproval.Text = "<span class=\"denied\">Denied</span>";
                                break;

                            case "0":
                                oApproval.Text = "<span class=\"pending\">Pending</span>";
                                if (Int32.Parse(oStep.Text) == intStep)
                                {
                                    oImage.Text = "<img src=\"/images/green_right.gif\" border=\"0\" align=\"absmiddle\">&nbsp;";
                                }
                                break;

                            case "1":
                                oApproval.Text = "<span class=\"approved\">Approved</span>";
                                break;

                            case "10":
                                oApproval.Text = "<span class=\"shelved\">Shelved</span>";
                                break;

                            case "100":
                                if (oStep.Text == "2")
                                {
                                    oApproval.Text = "<span class=\"pending\">Already Approved</span>";
                                }
                                else
                                {
                                    oApproval.Text = "<span class=\"pending\">Majority Voted</span>";
                                }
                                oModified.Text     = "Not Available";
                                oModified.CssClass = "pending";
                                break;
                            }
                            switch (oStep.Text)
                            {
                            case "1":
                                oStep.Text = "Manager";
                                break;

                            case "2":
                                oStep.Text = "Platform";
                                break;

                            case "3":
                                oStep.Text = "Board";
                                break;

                            case "4":
                                oStep.Text = "Director";
                                break;
                            }
                        }
                    }
                    else
                    {
                        panDenied.Visible = true;
                    }
                }
            }
            if (Request.QueryString["div"] != null)
            {
                switch (Request.QueryString["div"])
                {
                case "D":
                    boolDocuments = true;
                    break;

                case "C":
                    boolDiscussion = true;
                    break;
                }
            }
            if (boolDetails == false && boolDocuments == false && boolDiscussion == false)
            {
                boolDetails = true;
            }
            btnClose.Attributes.Add("onclick", "return CloseWindow();");
            btnFinish.Attributes.Add("onclick", "return CloseWindow();");
            btnApprove.Attributes.Add("onclick", "return confirm('Are you sure you want to APPROVE this request?');");
            btnDeny.Attributes.Add("onclick", "return confirm('Are you sure you want to DENY this request?');");
            btnShelf.Attributes.Add("onclick", "return confirm('Are you sure you want to SHELF this request?');");
        }
Beispiel #35
0
 public ResourceRequestEventArgs(WebView webView, ResourceRequest request)
 {
     this.webView = webView;
     this.request = request;
 }
Beispiel #36
0
 ResourceResponse IResourceInterceptor.OnRequest(ResourceRequest request)
 {
     // Resume normal processing.
     return(null);
 }
 public ResourceRequestEventArgs( ResourceRequest request )
 {
     this.request = request;
 }
        private void OnCLEMAnimalSell(object sender, EventArgs e)
        {
            Status = ActivityStatus.NoTask;

            RuminantHerd ruminantHerd = Resources.RuminantHerd();

            int    trucks     = 0;
            double saleValue  = 0;
            double saleWeight = 0;
            int    head       = 0;
            double aESum      = 0;

            // only perform this activity if timing ok, or selling required as a result of forces destock
            List <Ruminant> herd = new List <Ruminant>();

            if (this.TimingOK || this.CurrentHerd(false).Where(a => a.SaleFlag == HerdChangeReason.DestockSale).Count() > 0)
            {
                this.Status = ActivityStatus.NotNeeded;
                // get current untrucked list of animals flagged for sale
                herd = this.CurrentHerd(false).Where(a => a.SaleFlag != HerdChangeReason.None).OrderByDescending(a => a.Weight).ToList();
            }

            // no individuals to sell
            if (herd.Count() == 0)
            {
                return;
            }

            if (trucking == null)
            {
                // no trucking just sell
                SetStatusSuccess();
                foreach (var ind in herd)
                {
                    aESum      += ind.AdultEquivalent;
                    saleValue  += ind.BreedParams.ValueofIndividual(ind, PurchaseOrSalePricingStyleType.Sale);
                    saleWeight += ind.Weight;
                    ruminantHerd.RemoveRuminant(ind, this);
                }
            }
            else
            {
                // if sale herd > min loads before allowing sale
                if (herd.Select(a => a.Weight / 450.0).Sum() / trucking.Number450kgPerTruck >= trucking.MinimumTrucksBeforeSelling)
                {
                    // while truck to fill
                    while (herd.Select(a => a.Weight / 450.0).Sum() / trucking.Number450kgPerTruck > trucking.MinimumLoadBeforeSelling)
                    {
                        bool nonloaded = true;
                        trucks++;
                        double load450kgs = 0;
                        // while truck below carrying capacity load individuals
                        foreach (var ind in herd)
                        {
                            if (load450kgs + (ind.Weight / 450.0) <= trucking.Number450kgPerTruck)
                            {
                                nonloaded = false;
                                head++;
                                aESum      += ind.AdultEquivalent;
                                load450kgs += ind.Weight / 450.0;
                                saleValue  += ind.BreedParams.ValueofIndividual(ind, PurchaseOrSalePricingStyleType.Sale);
                                saleWeight += ind.Weight;
                                ruminantHerd.RemoveRuminant(ind, this);

                                //TODO: work out what to do with suckling calves still with mothers if mother sold.
                            }
                        }
                        if (nonloaded)
                        {
                            Summary.WriteWarning(this, String.Format("There was a problem loading the sale truck as sale individuals did not meet the loading criteria for breed [r={0}]", this.PredictedHerdBreed));
                            break;
                        }
                        herd = this.CurrentHerd(false).Where(a => a.SaleFlag != HerdChangeReason.None).OrderByDescending(a => a.Weight).ToList();
                    }
                    // create trucking emissions
                    trucking.ReportEmissions(trucks, true);
                    // if sold all
                    Status = (this.CurrentHerd(false).Where(a => a.SaleFlag != HerdChangeReason.None).Count() == 0) ? ActivityStatus.Success : ActivityStatus.Warning;
                }
            }
            if (bankAccount != null && head > 0) //(trucks > 0 || trucking == null)
            {
                ResourceRequest expenseRequest = new ResourceRequest
                {
                    ActivityModel      = this,
                    AllowTransmutation = false
                };

                // calculate transport costs
                if (trucking != null)
                {
                    expenseRequest.Required = trucks * trucking.DistanceToMarket * trucking.CostPerKmTrucking;
                    expenseRequest.Reason   = "Transport sales";
                    bankAccount.Remove(expenseRequest);
                }

                foreach (RuminantActivityFee item in Apsim.Children(this, typeof(RuminantActivityFee)))
                {
                    switch (item.PaymentStyle)
                    {
                    case AnimalPaymentStyleType.Fixed:
                        expenseRequest.Required = item.Amount;
                        break;

                    case AnimalPaymentStyleType.perHead:
                        expenseRequest.Required = head * item.Amount;
                        break;

                    case AnimalPaymentStyleType.perAE:
                        expenseRequest.Required = aESum * item.Amount;
                        break;

                    case AnimalPaymentStyleType.ProportionOfTotalSales:
                        expenseRequest.Required = saleValue * item.Amount;
                        break;

                    default:
                        throw new Exception(String.Format("PaymentStyle ({0}) is not supported for ({1}) in ({2})", item.PaymentStyle, item.Name, this.Name));
                    }
                    expenseRequest.Reason = item.Name;
                    // uses bank account specified in the RuminantActivityFee
                    item.BankAccount.Remove(expenseRequest);
                }

                // add and remove from bank
                if (saleValue > 0)
                {
                    bankAccount.Add(saleValue, this, this.PredictedHerdName + " sales");
                }
            }
        }
Beispiel #39
0
        protected void Page_Load(object sender, EventArgs e)
        {
            intProfile       = Int32.Parse(Request.Cookies["profileid"].Value);
            oProject         = new Projects(intProfile, dsn);
            oFunction        = new Functions(intProfile, dsn, intEnvironment);
            oUser            = new Users(intProfile, dsn);
            oPage            = new Pages(intProfile, dsn);
            oResourceRequest = new ResourceRequest(intProfile, dsn);
            oRequestItem     = new RequestItems(intProfile, dsn);
            oRequest         = new Requests(intProfile, dsn);
            oService         = new Services(intProfile, dsn);
            oServiceRequest  = new ServiceRequests(intProfile, dsn);
            oRequestField    = new RequestFields(intProfile, dsn);
            oApplication     = new Applications(intProfile, dsn);
            oServiceDetail   = new ServiceDetails(intProfile, dsn);
            oDelegate        = new Delegates(intProfile, dsn);
            oAudit           = new Audit(intProfile, dsn);
            oOnDemandTasks   = new OnDemandTasks(intProfile, dsn);

            if (Request.QueryString["applicationid"] != null && Request.QueryString["applicationid"] != "")
            {
                intApplication = Int32.Parse(Request.QueryString["applicationid"]);
            }
            if (Request.QueryString["pageid"] != null && Request.QueryString["pageid"] != "")
            {
                intPage = Int32.Parse(Request.QueryString["pageid"]);
            }
            if (Request.Cookies["application"] != null && Request.Cookies["application"].Value != "")
            {
                intApplication = Int32.Parse(Request.Cookies["application"].Value);
            }
            if (Request.QueryString["rrid"] != null && Request.QueryString["rrid"] != "")
            {
                // Start Workflow Change
                lblResourceWorkflow.Text = Request.QueryString["rrid"];
                int intResourceWorkflow = Int32.Parse(Request.QueryString["rrid"]);
                int intResourceParent   = oResourceRequest.GetWorkflowParent(intResourceWorkflow);
                ds = oResourceRequest.Get(intResourceParent);
                // End Workflow Change
                intRequest          = Int32.Parse(ds.Tables[0].Rows[0]["requestid"].ToString());
                lblRequestedBy.Text = oUser.GetFullName(oRequest.GetUser(intRequest));
                lblRequestedOn.Text = DateTime.Parse(oResourceRequest.Get(intResourceParent, "created")).ToString();
                lblDescription.Text = oRequest.Get(intRequest, "description");
                if (lblDescription.Text == "")
                {
                    lblDescription.Text = "<i>No information</i>";
                }
                intItem   = Int32.Parse(ds.Tables[0].Rows[0]["itemid"].ToString());
                intNumber = Int32.Parse(ds.Tables[0].Rows[0]["number"].ToString());
                // Start Workflow Change
                bool boolComplete = (oResourceRequest.GetWorkflow(intResourceWorkflow, "status") == "3");
                int  intUser      = Int32.Parse(oResourceRequest.GetWorkflow(intResourceWorkflow, "userid"));
                txtCustom.Text = oResourceRequest.GetWorkflow(intResourceWorkflow, "name");
                double dblAllocated = double.Parse(oResourceRequest.GetWorkflow(intResourceWorkflow, "allocated"));
                boolJoined = (oResourceRequest.GetWorkflow(intResourceWorkflow, "joined") == "1");
                // End Workflow Change
                intService      = Int32.Parse(ds.Tables[0].Rows[0]["serviceid"].ToString());
                lblService.Text = oService.Get(intService, "name");
                int intApp = oRequestItem.GetItemApplication(intItem);

                if (Request.QueryString["save"] != null && Request.QueryString["save"] != "")
                {
                    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "saved", "<script type=\"text/javascript\">alert('Information Saved Successfully');<" + "/" + "script>");
                }
                if (Request.QueryString["status"] != null && Request.QueryString["status"] != "")
                {
                    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "statusd", "<script type=\"text/javascript\">alert('Status Updates has been Added');<" + "/" + "script>");
                }
                if (!IsPostBack)
                {
                    double dblUsed = oResourceRequest.GetWorkflowUsed(intResourceWorkflow);
                    lblUpdated.Text = oResourceRequest.GetUpdated(intResourceParent);
                    if (dblAllocated == dblUsed)
                    {
                        if (boolComplete == false)
                        {
                            oFunction.ConfigureToolButton(btnComplete, "/images/tool_complete");
                            btnComplete.Attributes.Add("onclick", "return confirm('Are you sure you want to mark this as completed and remove it from your workload?');");
                        }
                        else
                        {
                            oFunction.ConfigureToolButton(btnComplete, "/images/tool_complete");
                            btnComplete.Attributes.Add("onclick", "alert('This task has already been marked COMPLETE. You can close this window.');return false;");
                        }
                    }
                    else
                    {
                        btnComplete.ImageUrl = "/images/tool_complete_dbl.gif";
                        btnComplete.Enabled  = false;
                    }
                    bool boolSLABreached = false;
                    if (oService.Get(intService, "sla") != "")
                    {
                        oFunction.ConfigureToolButton(btnSLA, "/images/tool_sla");
                        int intDays = oResourceRequest.GetSLA(intResourceParent);
                        if (intDays > -99999)
                        {
                            if (intDays < 1)
                            {
                                btnSLA.Style["border"] = "solid 2px #FF0000";
                            }
                            else if (intDays < 3)
                            {
                                btnSLA.Style["border"] = "solid 2px #FF9999";
                            }
                            boolSLABreached = (intDays < 0);
                            btnSLA.Attributes.Add("onclick", "return OpenWindow('RESOURCE_REQUEST_SLA','?rrid=" + intResourceParent.ToString() + "');");
                        }
                        else
                        {
                            btnSLA.ImageUrl = "/images/tool_sla_dbl.gif";
                            btnSLA.Enabled  = false;
                        }
                    }
                    else
                    {
                        btnSLA.ImageUrl = "/images/tool_sla_dbl.gif";
                        btnSLA.Enabled  = false;
                    }
                    oFunction.ConfigureToolButton(btnEmail, "/images/tool_email");
                    btnEmail.Attributes.Add("onclick", "return OpenWindow('RESOURCE_REQUEST_EMAIL','?rrid=" + intResourceWorkflow.ToString() + "&type=GENERIC');");
                    dblUsed             = (dblUsed / dblAllocated) * 100;
                    intProject          = oRequest.GetProjectNumber(intRequest);
                    hdnTab.Value        = "D";
                    panWorkload.Visible = true;
                    bool   boolRed          = LoadStatus(intResourceWorkflow);
                    string strValidSave     = "";
                    string strValidComplete = "";
                    if (boolRed == false && boolSLABreached == true)
                    {
                        btnComplete.Attributes.Add("onclick", "alert('NOTE: Your Service Level Agreement (SLA) has been breached!\\n\\nYou must provide a RED STATUS update with an explanation of why your SLA was breached for this request.\\n\\nOnce a RED STATUS update has been provided, you will be able to complete this request.');return false;");
                    }
                    else
                    {
                        btnComplete.Attributes.Add("onclick", "return ValidateRadioButtons('" + radActionIgnore.ClientID + "','" + radActionFix.ClientID + "','Please select an action')" +
                                                   " && (document.getElementById('" + radActionIgnore.ClientID + "').checked == false || (document.getElementById('" + radActionIgnore.ClientID + "').checked == true && ValidateText('" + txtReason.ClientID + "','Please enter the reason for ignoring this message')))" +
                                                   " && confirm('Are you sure you want to mark this as completed and remove it from your workload?')" +
                                                   ";");
                    }
                    LoadInformation(intResourceWorkflow);

                    radActionIgnore.Attributes.Add("onclick", "ShowHideDiv('" + trIgnore.ClientID + "','inline');");
                    radActionFix.Attributes.Add("onclick", "ShowHideDiv('" + trIgnore.ClientID + "','none');");
                    btnDenied.Attributes.Add("onclick", "return CloseWindow();");
                    oFunction.ConfigureToolButton(btnSave, "/images/tool_save");
                    oFunction.ConfigureToolButton(btnPrint, "/images/tool_print");
                    btnPrint.Attributes.Add("onclick", "return PrintWindow();");
                    oFunction.ConfigureToolButton(btnClose, "/images/tool_close");
                    btnClose.Attributes.Add("onclick", "return ExitWindow();");
                    btnSave.Attributes.Add("onclick", "return ValidateRadioButtons('" + radActionIgnore.ClientID + "','" + radActionFix.ClientID + "','Please select an action')" +
                                           " && (document.getElementById('" + radActionIgnore.ClientID + "').checked == false || (document.getElementById('" + radActionIgnore.ClientID + "').checked == true && ValidateText('" + txtReason.ClientID + "','Please enter the reason for ignoring this message')))" +
                                           " && ValidateStatus('" + ddlStatus.ClientID + "','" + txtComments.ClientID + "')" +
                                           ";");

                    // 6/1/2009 - Load ReadOnly View
                    if (oResourceRequest.CanUpdate(intProfile, intResourceWorkflow, false) == false)
                    {
                        oFunction.ConfigureToolButtonRO(btnSave, btnComplete);
                        //panDenied.Visible = true;
                    }
                }
            }
            else
            {
                panDenied.Visible = true;
            }
        }
Beispiel #40
0
        /// <summary>
        /// Method to determine available labour based on filters and take it if requested.
        /// </summary>
        /// <param name="request">Resource request details</param>
        /// <param name="removeFromResource">Determines if only calculating available labour or labour removed</param>
        /// <param name="callingModel">Model calling this method</param>
        /// <param name="resourceHolder">Location of resource holder</param>
        /// <param name="partialAction">Action on partial resources available</param>
        /// <returns></returns>
        public static double TakeLabour(ResourceRequest request, bool removeFromResource, IModel callingModel, ResourcesHolder resourceHolder, OnPartialResourcesAvailableActionTypes partialAction)
        {
            double            amountProvided = 0;
            double            amountNeeded   = request.Required;
            LabourFilterGroup current        = request.FilterDetails.OfType <LabourFilterGroup>().FirstOrDefault() as LabourFilterGroup;

            LabourRequirement lr;

            if (current != null)
            {
                if (current.Parent is LabourRequirement)
                {
                    lr = current.Parent as LabourRequirement;
                }
                else
                {
                    // coming from Transmutation request
                    lr = new LabourRequirement()
                    {
                        ApplyToAll       = false,
                        MaximumPerPerson = 1000,
                        MinimumPerPerson = 0
                    };
                }
            }
            else
            {
                lr = callingModel.FindAllChildren <LabourRequirement>().FirstOrDefault() as LabourRequirement;
            }

            int currentIndex = 0;

            if (current == null)
            {
                // no filtergroup provided so assume any labour
                current = new LabourFilterGroup();
            }

            request.ResourceTypeName = "Labour";
            ResourceRequest removeRequest = new ResourceRequest()
            {
                ActivityID         = request.ActivityID,
                ActivityModel      = request.ActivityModel,
                AdditionalDetails  = request.AdditionalDetails,
                AllowTransmutation = request.AllowTransmutation,
                Available          = request.Available,
                FilterDetails      = request.FilterDetails,
                Provided           = request.Provided,
                Category           = request.Category,
                RelatesToResource  = request.RelatesToResource,
                Required           = request.Required,
                Resource           = request.Resource,
                ResourceType       = request.ResourceType,
                ResourceTypeName   = (request.Resource is null? "":(request.Resource as CLEMModel).NameWithParent)
            };

            // start with top most LabourFilterGroup
            while (current != null && amountProvided < amountNeeded)
            {
                List <LabourType> items = (resourceHolder.GetResourceGroupByType(request.ResourceType) as Labour).Items;
                items = items.Where(a => (a.LastActivityRequestID != request.ActivityID) || (a.LastActivityRequestID == request.ActivityID && a.LastActivityRequestAmount < lr.MaximumPerPerson)).ToList();
                items = items.Filter(current as Model);

                // search for people who can do whole task first
                while (amountProvided < amountNeeded && items.Where(a => a.LabourCurrentlyAvailableForActivity(request.ActivityID, lr.MaximumPerPerson) >= request.Required).Count() > 0)
                {
                    // get labour least available but with the amount needed
                    LabourType lt = items.Where(a => a.LabourCurrentlyAvailableForActivity(request.ActivityID, lr.MaximumPerPerson) >= request.Required).OrderBy(a => a.LabourCurrentlyAvailableForActivity(request.ActivityID, lr.MaximumPerPerson)).FirstOrDefault();

                    double amount = Math.Min(amountNeeded - amountProvided, lt.LabourCurrentlyAvailableForActivity(request.ActivityID, lr.MaximumPerPerson));

                    // limit to max allowed per person
                    amount = Math.Min(amount, lr.MaximumPerPerson);
                    // limit to min per person to do activity
                    if (amount < lr.MinimumPerPerson)
                    {
                        request.Category = "Min labour limit";
                        return(amountProvided);
                    }

                    amountProvided        += amount;
                    removeRequest.Required = amount;
                    if (removeFromResource)
                    {
                        lt.LastActivityRequestID     = request.ActivityID;
                        lt.LastActivityRequestAmount = amount;
                        lt.Remove(removeRequest);
                        request.Provided += removeRequest.Provided;
                        request.Value    += request.Provided * lt.PayRate();
                    }
                }

                // if still needed and allow partial resource use.
                if (partialAction == OnPartialResourcesAvailableActionTypes.UseResourcesAvailable)
                {
                    if (amountProvided < amountNeeded)
                    {
                        // then search for those that meet criteria and can do part of task
                        foreach (LabourType item in items.Where(a => a.LabourCurrentlyAvailableForActivity(request.ActivityID, lr.MaximumPerPerson) >= 0).OrderByDescending(a => a.LabourCurrentlyAvailableForActivity(request.ActivityID, lr.MaximumPerPerson)))
                        {
                            if (amountProvided >= amountNeeded)
                            {
                                break;
                            }

                            double amount = Math.Min(amountNeeded - amountProvided, item.LabourCurrentlyAvailableForActivity(request.ActivityID, lr.MaximumPerPerson));

                            // limit to max allowed per person
                            amount = Math.Min(amount, lr.MaximumPerPerson);

                            // limit to min per person to do activity
                            if (amount >= lr.MinimumPerPerson)
                            {
                                amountProvided        += amount;
                                removeRequest.Required = amount;
                                if (removeFromResource)
                                {
                                    if (item.LastActivityRequestID != request.ActivityID)
                                    {
                                        item.LastActivityRequestAmount = 0;
                                    }
                                    item.LastActivityRequestID      = request.ActivityID;
                                    item.LastActivityRequestAmount += amount;
                                    item.Remove(removeRequest);
                                    request.Provided += removeRequest.Provided;
                                    request.Value    += request.Provided * item.PayRate();
                                }
                            }
                            else
                            {
                                currentIndex = request.FilterDetails.Count;
                            }
                        }
                    }
                }
                currentIndex++;
                if (current.Children.OfType <LabourFilterGroup>().Count() > 0)
                {
                    current = current.Children.OfType <LabourFilterGroup>().FirstOrDefault();
                }
                else
                {
                    current = null;
                }
            }
            // report amount gained.
            return(amountProvided);
        }
 /// <summary>
 ///     Determines if the request is for an embedded resource
 /// </summary>
 private bool IsEmbeddedResource(ResourceRequest request)
 {
     return EmbeddedResourceDomain.IsBaseOf(request.Url);
 }
Beispiel #42
0
        public TestWriteNullEmptySystemField() : base()
        {
            int testUser = 1;

            records = new HrbcRecordCreator(() => ResourceRequest.CreateRecords()
                                            .Append(ResourceId.Client,
                                                    content => content
                                                    .Append("P_Name", "Test Client")
                                                    .Append("P_Owner", testUser),
                                                    "client1")
                                            .Append(ResourceId.Recruiter,
                                                    content => content
                                                    .Append("P_Name", "Test Recruiter")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1")),
                                                    "recruiter1")
                                            .Append(ResourceId.Job,
                                                    content => content
                                                    .Append("P_Position", "Test Job")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1"))
                                                    .Append("P_Recruiter", new CreateRecordRequest.Reference("recruiter1")),
                                                    "job1")
                                            .Append(ResourceId.Job,
                                                    content => content
                                                    .Append("P_Position", "Test Job")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1"))
                                                    .Append("P_Recruiter", new CreateRecordRequest.Reference("recruiter1")),
                                                    "job2")
                                            .Append(ResourceId.Person,
                                                    content => content
                                                    .Append("P_Name", "Test Person")
                                                    .Append("P_Owner", testUser),
                                                    "person1")
                                            .Append(ResourceId.Resume,
                                                    content => content
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Candidate", new CreateRecordRequest.Reference("person1")),
                                                    "resume1")
                                            .Append(ResourceId.Resume,
                                                    content => content
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Candidate", new CreateRecordRequest.Reference("person1")),
                                                    "resume2")

                                            /* Example of a progress element:
                                             *               .Append(ResourceId.Process,
                                             *                  content => content
                                             *                      .Append("P_Owner", testUser)
                                             *                      .Append("P_Client", new CreateRecordRequest.Reference("client"))
                                             *                      .Append("P_Recruiter", new CreateRecordRequest.Reference("recruiter"))
                                             *                      .Append("P_Job", new CreateRecordRequest.Reference("job"))
                                             *                      .Append("P_Candidate", new CreateRecordRequest.Reference("person"))
                                             *                      .Append("P_Resume", new CreateRecordRequest.Reference("resume")),
                                             *                  "process")
                                             */
                                            .Append(ResourceId.Sales,
                                                    content => content
                                                    //.Append("P_SalesAmount", 5000)
                                                    .Append("P_Owner", testUser),
                                                    "sales1")
                                            .Append(ResourceId.Activity,
                                                    content => content
                                                    .Append("P_Title", "Test Activity")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_FromDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                                                    "activity1")
                                            .Append(ResourceId.Contract,
                                                    content => content
                                                    .Append("P_Name", "Test Contract")
                                                    //.Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1")),
                                                    "contract1"));
        }
        /// <summary>
        ///     Creates a response using the contents of an embedded assembly resource.
        /// </summary>
        private ResourceResponse CreateResponseFromResource(ResourceRequest request)
        {
            string resourceName;
            string filePath;

            // this project embeds static HTML/JS/CSS/PNG files as resources
            // by translating the resource's relative file path like Resources\foo/bar.html
            // to a logical name like /www/foo/bar.html
            resourceName = String.Concat("www", request.Url.AbsolutePath);
            filePath = Path.GetFullPath(Path.Combine(TempFolder, resourceName.Replace('/', Path.DirectorySeparatorChar)));

            // cache the resource to a temp file if
            if (!File.Exists(filePath))
            {
                ExtractResourceToFile(resourceName, filePath);
            }

            return ResourceResponse.Create(filePath);
        }
Beispiel #44
0
 public static UniTask <UnityEngine.Object> ToUniTask(this ResourceRequest resourceRequest)
 {
     Error.ThrowArgumentNullException(resourceRequest, nameof(resourceRequest));
     return(new UniTask <UnityEngine.Object>(new ResourceRequestAwaiter(resourceRequest)));
 }
        /// <summary>
        ///     Intercepts any requests for the EmbeddedResourceDomain base Uri,
        ///     and returns a response using the embedded resource in this app's assembly/DLL file
        /// </summary>
        public virtual ResourceResponse OnRequest(ResourceRequest request)
        {
            ResourceResponse response = null;

            // log the request to the debugger output
            System.Diagnostics.Debug.Print(String.Concat(request.Method, ' ', request.Url.ToString()));

            if (IsEmbeddedResource(request))
            {
                response = CreateResponseFromResource(request);
            }

            return response;
        }
 public Task<Resource> GetTrashInfoAsync(ResourceRequest request, CancellationToken cancellationToken)
 {
     return GetAsync<ResourceRequest, Resource>("trash/resources", request, cancellationToken);
 }
Beispiel #47
0
		/// <summary>
		///   Informs the station a container is available.
		/// </summary>
		/// <param name="source">The station currently holding the container.</param>
		/// <param name="condition">The container's current condition.</param>
		public void ResourceReady(Station source, Condition condition)
		{
			var request = new ResourceRequest(source, condition);
			if (!_resourceRequests.Contains(request))
				_resourceRequests.Add(request);
		}
Beispiel #48
0
    private void OnSpriteLoaded(ResourceRequest request)
    {
        Sprite sprite = request.asset as Sprite;

        loadSpriteBack?.Invoke(sprite);
    }
            public static IEnumerator ResourceRequest(SimpleCoroutineAwaiter <Object> awaiter, ResourceRequest instruction)
            {
                yield return(instruction);

                awaiter.Complete(instruction.asset, null);
            }
Beispiel #50
0
        public void NotifyTeamLead(int _itemid, int _rrid, int _assignpage, int _viewpage, int _environment, string _cc, string _se_dsn, string _dsn_asset, string _dsn_ip, int _userid_assigned)
        {
            RequestItems    oRequestItem     = new RequestItems(user, dsn);
            Users           oUser            = new Users(user, dsn);
            Applications    oApplication     = new Applications(user, dsn);
            Pages           oPage            = new Pages(user, dsn);
            Functions       oFunction        = new Functions(user, dsn, _environment);
            Variables       oVariable        = new Variables(_environment);
            Services        oService         = new Services(user, dsn);
            ResourceRequest oResourceRequest = new ResourceRequest(user, dsn);
            Log             oLog             = new Log(user, dsn);
            int             intService       = Int32.Parse(oResourceRequest.Get(_rrid, "serviceid"));
            string          strService       = oService.GetName(intService);

            if (intService == 0)
            {
                strService = oRequestItem.GetItemName(_itemid);
            }
            int      intApp         = oRequestItem.GetItemApplication(_itemid);
            int      intRequest     = Int32.Parse(oResourceRequest.Get(_rrid, "requestid"));
            int      intNumber      = Int32.Parse(oResourceRequest.Get(_rrid, "number"));
            Requests oRequest       = new Requests(user, dsn);
            int      intProject     = oRequest.GetProjectNumber(intRequest);
            Projects oProject       = new Projects(user, dsn);
            int      intRequester   = oRequest.GetUser(intRequest);
            string   strSpacerRow   = "<tr><td colspan=\"3\"><img src=\"" + oVariable.ImageURL() + "/images/spacer.gif\" border=\"0\" width=\"1\" height=\"7\" /></td></tr>";
            string   strEmail       = oService.Get(intService, "email");
            string   strEMailIdsBCC = oFunction.GetGetEmailAlertsEmailIds("EMAILGRP_REQUEST_ASSIGNMENT");
            string   strCVT         = "CVT" + intRequest.ToString() + "-" + intService.ToString() + "-" + intNumber.ToString();

            int  intUser  = _userid_assigned;
            bool boolTech = false;

            if (intUser > 0)
            {
                boolTech = true;
                string strNotify = "";
                //if (oProject.Get(intProject, "number").StartsWith("CV") == false)
                //    strNotify = "<p><span style=\"color:#0000FF\"><b>PROJECT COORDINATOR:</b> Please allocate the hours listed above for each resource in Clarity.</span></p>";
                // Add Workflow
                int intResourceWorkflow = oResourceRequest.AddWorkflow(_rrid, 0, oResourceRequest.Get(_rrid, "name"), intUser, Int32.Parse(oResourceRequest.Get(_rrid, "devices")), double.Parse(oResourceRequest.Get(_rrid, "allocated")), 2, 0);
                oLog.AddEvent(intRequest.ToString(), strCVT, "Request assigned to " + oUser.GetFullNameWithLanID(intUser) + " by the system", LoggingType.Debug);
                string strDefault = oUser.GetApplicationUrl(intUser, _viewpage);
                if (strDefault == "")
                {
                    oFunction.SendEmail("Request Assignment: " + strService, oUser.GetName(intUser), _cc, strEMailIdsBCC, "Request Assignment: " + strService, "<p><b>The following request has been automatically assigned to you</b><p><p>" + oResourceRequest.GetWorkflowSummary(intResourceWorkflow, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p>", true, false);
                }
                else
                {
                    if (intProject > 0)
                    {
                        oFunction.SendEmail("Request Assignment: " + strService, oUser.GetName(intUser), _cc, strEMailIdsBCC, "Request Assignment: " + strService, "<p><b>The following request has been automatically assigned to you</b><p><p><a href=\"" + oVariable.URL() + "/redirect.aspx?referrer=/" + strDefault + oPage.GetFullLink(_viewpage) + "?pid=" + intProject.ToString() + "\" target=\"_blank\">Click here to review your new assignment.</a></p><p>" + oResourceRequest.GetWorkflowSummary(intResourceWorkflow, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p>", true, false);
                    }
                    else
                    {
                        oFunction.SendEmail("Request Assignment: " + strService, oUser.GetName(intUser), _cc, strEMailIdsBCC, "Request Assignment: " + strService, "<p><b>The following request has been automatically assigned to you</b><p><p><a href=\"" + oVariable.URL() + "/redirect.aspx?referrer=/frame/resource_request.aspx?rrid=" + intResourceWorkflow.ToString() + "\" target=\"_blank\">Click here to review your new assignment.</a></p><p>" + oResourceRequest.GetWorkflowSummary(intResourceWorkflow, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p>", true, false);
                    }
                }
                string strActivity = "<tr><td><b>Resource:</b></td><td>&nbsp;&nbsp;&nbsp;</td><td>" + oUser.GetFullName(intUser) + "</td></tr>";
                strActivity += strSpacerRow;
                strActivity += "<tr><td><b>Activity Type:</b></td><td>&nbsp;&nbsp;&nbsp;</td><td>" + oRequestItem.GetItemName(_itemid) + "</td></tr>";
                strActivity  = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"" + oVariable.DefaultFontStyle() + "\">" + strActivity + "</table>";
                string strDeliverable = oApplication.Get(intApp, "deliverables_doc");
                if (strDeliverable.Trim() != "")
                {
                    strDeliverable = "<p><a href=\"" + oVariable.URL() + strDeliverable + "\">Click here to view the service deliverables</a></p>";
                }
                if (oService.Get(intService, "notify_client") != "0")
                {
                    oFunction.SendEmail("Request Assignment: " + strService, oUser.GetName(intRequester), _cc, strEMailIdsBCC, "Request Assignment: " + strService, "<p><b>A resource has been assigned to the following request...</b><p><p>" + oResourceRequest.GetWorkflowSummary(intResourceWorkflow, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p><p>" + strActivity + "</p>" + strDeliverable + strNotify, true, false);
                }
                oProject.Update(intProject, 2);
                oResourceRequest.UpdateAccepted(_rrid, 1);
                oResourceRequest.UpdateAssignedBy(_rrid, -1000);
            }
            else
            {
                DataSet dsTechnicians = oService.GetUser(intService, 0);
                foreach (DataRow drTechnician in dsTechnicians.Tables[0].Rows)
                {
                    boolTech = true;
                    intUser  = Int32.Parse(drTechnician["userid"].ToString());
                    string strNotify = "";
                    //if (oProject.Get(intProject, "number").StartsWith("CV") == false)
                    //    strNotify = "<p><span style=\"color:#0000FF\"><b>PROJECT COORDINATOR:</b> Please allocate the hours listed above for each resource in Clarity.</span></p>";
                    // Add Workflow
                    int intResourceWorkflow = oResourceRequest.AddWorkflow(_rrid, 0, oResourceRequest.Get(_rrid, "name"), intUser, Int32.Parse(oResourceRequest.Get(_rrid, "devices")), double.Parse(oResourceRequest.Get(_rrid, "allocated")), 2, 1);
                    oLog.AddEvent(intRequest.ToString(), strCVT, "Request assigned to " + oUser.GetFullNameWithLanID(intUser) + " from service techician configuration", LoggingType.Debug);
                    // NOTIFY
                    if (strEmail != "" && strEmail != "0")
                    {
                        string strDefault = oApplication.GetUrl(intApp, _viewpage);
                        if (strDefault == "")
                        {
                            oFunction.SendEmail("Request Assignment: " + strService, strEmail, oUser.GetEmail(_cc, _environment), strEMailIdsBCC, "Request Assignment: " + strService, "<p><b>The following request has been automatically assigned to you</b></p><p>" + oResourceRequest.GetWorkflowSummary(intResourceWorkflow, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p>", false, false);
                        }
                        else
                        {
                            if (intProject > 0)
                            {
                                oFunction.SendEmail("Request Assignment: " + strService, strEmail, oUser.GetEmail(_cc, _environment), strEMailIdsBCC, "Request Assignment: " + strService, "<p><b>The following request has been automatically assigned to you</b><p><p><a href=\"" + oVariable.URL() + "/redirect.aspx?referrer=/" + strDefault + oPage.GetFullLink(_viewpage) + "?pid=" + intProject.ToString() + "\" target=\"_blank\">Click here to review your new assignment.</a></p><p>" + oResourceRequest.GetWorkflowSummary(intResourceWorkflow, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p>", false, false);
                            }
                            else
                            {
                                oFunction.SendEmail("Request Assignment: " + strService, strEmail, oUser.GetEmail(_cc, _environment), strEMailIdsBCC, "Request Assignment: " + strService, "<p><b>The following request has been automatically assigned to you</b><p><p><a href=\"" + oVariable.URL() + "/redirect.aspx?referrer=/frame/resource_request.aspx?rrid=" + intResourceWorkflow.ToString() + "\" target=\"_blank\">Click here to review your new assignment.</a></p><p>" + oResourceRequest.GetWorkflowSummary(intResourceWorkflow, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p>", false, false);
                            }
                        }
                    }
                    else
                    {
                        string strDefault = oUser.GetApplicationUrl(intUser, _viewpage);
                        if (strDefault == "")
                        {
                            oFunction.SendEmail("Request Assignment: " + strService, oUser.GetName(intUser), _cc, strEMailIdsBCC, "Request Assignment: " + strService, "<p><b>The following request has been automatically assigned to you</b><p><p>" + oResourceRequest.GetWorkflowSummary(intResourceWorkflow, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p>", true, false);
                        }
                        else
                        {
                            if (intProject > 0)
                            {
                                oFunction.SendEmail("Request Assignment: " + strService, oUser.GetName(intUser), _cc, strEMailIdsBCC, "Request Assignment: " + strService, "<p><b>The following request has been automatically assigned to you</b><p><p><a href=\"" + oVariable.URL() + "/redirect.aspx?referrer=/" + strDefault + oPage.GetFullLink(_viewpage) + "?pid=" + intProject.ToString() + "\" target=\"_blank\">Click here to review your new assignment.</a></p><p>" + oResourceRequest.GetWorkflowSummary(intResourceWorkflow, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p>", true, false);
                            }
                            else
                            {
                                oFunction.SendEmail("Request Assignment: " + strService, oUser.GetName(intUser), _cc, strEMailIdsBCC, "Request Assignment: " + strService, "<p><b>The following request has been automatically assigned to you</b><p><p><a href=\"" + oVariable.URL() + "/redirect.aspx?referrer=/frame/resource_request.aspx?rrid=" + intResourceWorkflow.ToString() + "\" target=\"_blank\">Click here to review your new assignment.</a></p><p>" + oResourceRequest.GetWorkflowSummary(intResourceWorkflow, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p>", true, false);
                            }
                        }
                        string strActivity = "<tr><td><b>Resource:</b></td><td>&nbsp;&nbsp;&nbsp;</td><td>" + oUser.GetFullName(intUser) + "</td></tr>";
                        strActivity += strSpacerRow;
                        strActivity += "<tr><td><b>Activity Type:</b></td><td>&nbsp;&nbsp;&nbsp;</td><td>" + oRequestItem.GetItemName(_itemid) + "</td></tr>";
                        strActivity  = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"" + oVariable.DefaultFontStyle() + "\">" + strActivity + "</table>";
                        string strDeliverable = oApplication.Get(intApp, "deliverables_doc");
                        if (strDeliverable.Trim() != "")
                        {
                            strDeliverable = "<p><a href=\"" + oVariable.URL() + strDeliverable + "\">Click here to view the service deliverables</a></p>";
                        }
                        if (oService.Get(intService, "notify_client") != "0")
                        {
                            oFunction.SendEmail("Request Assignment: " + strService, oUser.GetName(intRequester), _cc, strEMailIdsBCC, "Request Assignment: " + strService, "<p><b>A resource has been assigned to the following request...</b><p><p>" + oResourceRequest.GetWorkflowSummary(intResourceWorkflow, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p><p>" + strActivity + "</p>" + strDeliverable + strNotify, true, false);
                        }
                    }
                    oProject.Update(intProject, 2);
                    oResourceRequest.UpdateAccepted(_rrid, 1);
                    oResourceRequest.UpdateAssignedBy(_rrid, -1000);
                }
            }
            if (boolTech == false)
            {
                oLog.AddEvent(intRequest.ToString(), strCVT, "Sending request to service manager(s) for assignment", LoggingType.Debug);
                // If no technicians assigned
                if (strEmail != "" && strEmail != "0")
                {
                    // If group mailbox
                    string strDefault = oApplication.GetUrl(intApp, _assignpage);
                    oLog.AddEvent(intRequest.ToString(), strCVT, "Request sent to " + strEmail + " (group mailbox) for assignment", LoggingType.Debug);
                    if (strDefault == "")
                    {
                        oFunction.SendEmail("Request Submitted: " + strService, strEmail, "", strEMailIdsBCC, "Request Submitted: " + strService, "<p><b>A resource from your department has been requested; you are required to assign a resource to this initiative.</b></p><p>" + oResourceRequest.GetSummary(_rrid, 0, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p>", false, false);
                    }
                    else
                    {
                        oFunction.SendEmail("Request Submitted: " + strService, strEmail, "", strEMailIdsBCC, "Request Submitted: " + strService, "<p><b>A resource from your department has been requested; you are required to assign a resource to this initiative.</b></p><p><a href=\"" + oVariable.URL() + "/redirect.aspx?referrer=/" + strDefault + oPage.GetFullLink(_assignpage) + "?rrid=" + _rrid.ToString() + "\" target=\"_blank\">Click here to assign a resource.</a></p><p>" + oResourceRequest.GetSummary(_rrid, 0, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p>", false, false);
                    }
                }
                else
                {
                    // If no group mailbox, notify team leads
                    DataSet dsManagers = oService.GetUser(intService, 1);
                    foreach (DataRow drManager in dsManagers.Tables[0].Rows)
                    {
                        intUser = Int32.Parse(drManager["userid"].ToString());
                        oLog.AddEvent(intRequest.ToString(), strCVT, "Request sent to " + oUser.GetFullNameWithLanID(intUser) + " for assignment", LoggingType.Debug);
                        string strDefault = oUser.GetApplicationUrl(intUser, _assignpage);
                        if (strDefault == "")
                        {
                            oFunction.SendEmail("Request Submitted: " + strService, oUser.GetName(intUser), "", strEMailIdsBCC, "Request Submitted: " + strService, "<p><b>A resource from your department has been requested; you are required to assign a resource to this initiative.</b></p><p>" + oResourceRequest.GetSummary(_rrid, 0, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p>", true, false);
                        }
                        else
                        {
                            oFunction.SendEmail("Request Submitted: " + strService, oUser.GetName(intUser), "", strEMailIdsBCC, "Request Submitted: " + strService, "<p><b>A resource from your department has been requested; you are required to assign a resource to this initiative.</b></p><p><a href=\"" + oVariable.URL() + "/redirect.aspx?referrer=/" + strDefault + oPage.GetFullLink(_assignpage) + "?rrid=" + _rrid.ToString() + "\" target=\"_blank\">Click here to assign a resource.</a></p><p>" + oResourceRequest.GetSummary(_rrid, 0, _environment, _se_dsn, _dsn_asset, _dsn_ip) + "</p>", true, false);
                        }
                    }
                }
            }
        }
Beispiel #51
0
        private IntPtr internalResourceRequestCallback( IntPtr caller, IntPtr request )
        {
            ResourceRequest requestWrap = new ResourceRequest( request );
            ResourceRequestEventArgs e = new ResourceRequestEventArgs( requestWrap );

            if ( ResourceRequest != null )
            {
                ResourceResponse response = this.OnResourceRequest( this, e );
                CommandManager.InvalidateRequerySuggested();

                if ( response != null )
                    return response.getInstance();
            }

            return IntPtr.Zero;
        }
Beispiel #52
0
        public bool NotifyApproval(int _requestid, int intService, int intNumber, int _resourcerequestapprove, int _environment, string _cc, string _dsn_service_editor)
        {
            bool            boolNotify       = false;
            RequestItems    oRequestItem     = new RequestItems(user, dsn);
            ResourceRequest oResourceRequest = new ResourceRequest(user, dsn);
            Applications    oApplication     = new Applications(user, dsn);
            Users           oUser            = new Users(user, dsn);
            Functions       oFunction        = new Functions(user, dsn, _environment);
            Requests        oRequest         = new Requests(user, dsn);
            Pages           oPage            = new Pages(user, dsn);
            Variables       oVariable        = new Variables(_environment);
            Platforms       oPlatform        = new Platforms(user, dsn);
            Services        oService         = new Services(user, dsn);
            Log             oLog             = new Log(user, dsn);
            string          strEMailIdsBCC   = oFunction.GetGetEmailAlertsEmailIds("EMAILGRP_REQUEST_STATUS");

            int intPlatform = 0;
            int intManager  = 0;
            int intApp      = 0;
            int intItem     = oService.GetItemId(intService);
            int RRID        = 0;

            DataSet dsResource = oResourceRequest.GetAllService(_requestid, intService, intNumber);

            if (dsResource.Tables[0].Rows.Count > 0)
            {
                Int32.TryParse(dsResource.Tables[0].Rows[0]["RRID"].ToString(), out RRID);
            }

            string strCVT = "CVT" + _requestid.ToString() + "-" + intService.ToString() + "-" + intNumber.ToString();

            if (intItem > 0)
            {
                intApp      = oRequestItem.GetItemApplication(intItem);
                intPlatform = Int32.Parse(oApplication.Get(intApp, "platform_approve"));
            }
            if (intService > 0)
            {
                Int32.TryParse(oService.Get(intService, "manager_approval"), out intManager);
            }

            DataSet dsSelected    = oService.GetSelected(_requestid, intService, intNumber);
            int     intSelectedID = 0;
            int     intApproved   = 0;

            if (dsSelected.Tables[0].Rows.Count > 0)
            {
                Int32.TryParse(dsSelected.Tables[0].Rows[0]["approved"].ToString(), out intApproved);
                Int32.TryParse(dsSelected.Tables[0].Rows[0]["id"].ToString(), out intSelectedID);
            }
            else
            {
                intApproved = 1;    // since not the first one submitted, automatically approve from a service owner perspective.
            }
            // First, check for the requestor's manager Approval
            if (intManager == 1 && Get(_requestid, "manager_approval") == "0")
            {
                // Send to Manager for approval
                intPlatform = 0;
                boolNotify  = true;
                int intUser = oUser.GetManager(oRequest.GetUser(_requestid), true);
                oLog.AddEvent(_requestid.ToString(), strCVT, "Sending to manager for approval - " + oUser.GetFullNameWithLanID(intUser), LoggingType.Debug);
                if (intUser == 0)
                {
                    intPlatform = 1;
                }
                else
                {
                    string strDefault = oUser.GetApplicationUrl(intUser, _resourcerequestapprove);
                    if (strDefault == "")
                    {
                        oFunction.SendEmail("Request #CVT" + _requestid.ToString() + " APPROVAL", oUser.GetName(intUser), _cc, strEMailIdsBCC, "Request #CVT" + _requestid.ToString() + " APPROVAL", "<p><b>A service request requires your approval; you are required to approve or deny this request.</b></p>", true, false);
                    }
                    else
                    {
                        oFunction.SendEmail("Request #CVT" + _requestid.ToString() + " APPROVAL", oUser.GetName(intUser), _cc, strEMailIdsBCC, "Request #CVT" + _requestid.ToString() + " APPROVAL", "<p><b>A service request requires your approval; you are required to approve or deny this request.</b></p><p><a href=\"" + oVariable.URL() + "/redirect.aspx?referrer=/" + strDefault + oPage.GetFullLink(_resourcerequestapprove) + "?rid=" + _requestid.ToString() + "&approve=true\" target=\"_blank\">Click here to review this request.</a></p>", true, false);
                    }
                }
            }
            else
            {
                // Next, check the service approval
                DataSet dsApprovers = oService.GetUser(intService, -10);
                //int intApproval = ((oService.Get(intService, "approval") == "1" && dsApprovers.Tables[0].Rows.Count > 0) ? 0 : 1);
                int intApproval = ((oService.Get(intService, "approval") == "1" && dsApprovers.Tables[0].Rows.Count > 0) ? 1 : 0);
                if (intApproval == 1 && intApproved == 0)
                {
                    // Send to Approvers for approval
                    boolNotify = true;
                    // Send to Approvers for approval
                    foreach (DataRow drApprover in dsApprovers.Tables[0].Rows)
                    {
                        int intUser = Int32.Parse(drApprover["userid"].ToString());
                        oLog.AddEvent(_requestid.ToString(), strCVT, "Sending to service approver for approval - " + oUser.GetFullNameWithLanID(intUser), LoggingType.Debug);
                        string strDefault = oUser.GetApplicationUrl(intUser, _resourcerequestapprove);
                        if (strDefault == "")
                        {
                            oFunction.SendEmail("Service Request APPROVAL", oUser.GetName(intUser), _cc, strEMailIdsBCC, "Service Request APPROVAL", "<p><b>A service request requires your approval; you are required to approve or deny this request.</b></p>", true, false);
                        }
                        else
                        {
                            oFunction.SendEmail("Service Request APPROVAL", oUser.GetName(intUser), _cc, strEMailIdsBCC, "Service Request APPROVAL", "<p><b>A service request requires your approval; you are required to approve or deny this request.</b></p><p><a href=\"" + oVariable.URL() + "/redirect.aspx?referrer=/" + strDefault + oPage.GetFullLink(_resourcerequestapprove) + "?srid=" + intSelectedID.ToString() + "\" target=\"_blank\">Click here to review this request.</a></p>", true, false);
                        }
                    }
                }
                else
                {
                    // Update that the service is approved.
                    if (intSelectedID > 0 && intApproved != 1)
                    {
                        oService.UpdateSelectedApprove(_requestid, intService, intNumber, 1, -999, DateTime.Now, "System Approval");
                    }

                    // Commenting since no current way of knowing if request has been approved by the platform
                    //if (intPlatform == 1)
                    //{
                    //    // Send to Platform for approval
                    //    if (intItem > 0)
                    //    {
                    //        int intUser = oPlatform.GetManager(Int32.Parse(oRequestItem.GetItem(intItem, "platformid")));
                    //        if (intUser > 0)
                    //        {
                    //            string strDefault = oUser.GetApplicationUrl(intUser, _resourcerequestapprove);
                    //            if (strDefault == "")
                    //                oFunction.SendEmail("Request APPROVAL", oUser.GetName(intUser), "", strEMailIdsBCC, "Request APPROVAL", "<p><b>A service request requires your approval; you are required to approve or deny this request.</b></p>", true, false);
                    //            else
                    //                oFunction.SendEmail("Request APPROVAL", oUser.GetName(intUser), "", strEMailIdsBCC, "Request APPROVAL", "<p><b>A service request requires your approval; you are required to approve or deny this request.</b></p><p><a href=\"" + oVariable.URL() + "/redirect.aspx?referrer=/" + strDefault + oPage.GetFullLink(_resourcerequestapprove) + "?rrid=" + _resourcerequestid.ToString() + "\" target=\"_blank\">Click here to review this request.</a></p>", true, false);
                    //        }
                    //    }
                    //}

                    // Notify 3rd part approvers
                    DataSet       dsAlready        = oResourceRequest.GetApprovals(_requestid, intService, intNumber);
                    ServiceEditor oServiceEditor   = new ServiceEditor(user, _dsn_service_editor);
                    DataSet       dsApprovalFields = oServiceEditor.GetApprovals(intService);
                    DataSet       dsServiceEditor  = oServiceEditor.GetRequestFirstData2(_requestid, intService, intNumber, 0, dsn);

                    foreach (DataRow drApprovalField in dsApprovalFields.Tables[0].Rows)
                    {
                        if (dsServiceEditor.Tables[0].Rows.Count > 0)
                        {
                            int intApprover = 0;
                            if (Int32.TryParse(dsServiceEditor.Tables[0].Rows[0][drApprovalField["dbfield"].ToString()].ToString(), out intApprover) == true && intApprover > 0)
                            {
                                // Check to see if already sent
                                bool boolAlready = false;
                                foreach (DataRow drAlready in dsAlready.Tables[0].Rows)
                                {
                                    if (intApprover == Int32.Parse(drAlready["userid"].ToString()))
                                    {
                                        boolAlready = true;
                                        break;
                                    }
                                }
                                if (boolAlready == false)
                                {
                                    boolNotify = true;
                                    oResourceRequest.AddApproval(_requestid, intService, intNumber, intApprover);
                                    oLog.AddEvent(_requestid.ToString(), strCVT, "Sending to 3rd party approver for approval - " + oUser.GetFullNameWithLanID(intApprover), LoggingType.Debug);
                                    string strDefault = oUser.GetApplicationUrl(intApprover, _resourcerequestapprove);
                                    if (strDefault == "")
                                    {
                                        oFunction.SendEmail("Request #CVT" + _requestid.ToString() + "-" + intService.ToString() + "-" + intNumber.ToString() + " APPROVAL", oUser.GetName(intApprover), "", strEMailIdsBCC, "Request #CVT" + _requestid.ToString() + "-" + intService.ToString() + "-" + intNumber.ToString() + " APPROVAL", "<p><b>A service request requires your approval; you are required to approve or deny this request.</b></p>", true, false);
                                    }
                                    else
                                    {
                                        oFunction.SendEmail("Request #CVT" + _requestid.ToString() + "-" + intService.ToString() + "-" + intNumber.ToString() + " APPROVAL", oUser.GetName(intApprover), "", strEMailIdsBCC, "Request #CVT" + _requestid.ToString() + "-" + intService.ToString() + "-" + intNumber.ToString() + " APPROVAL", "<p><b>A service request requires your approval; you are required to approve or deny this request.</b></p><p><a href=\"" + oVariable.URL() + "/redirect.aspx?referrer=/" + strDefault + oPage.GetFullLink(_resourcerequestapprove) + "?rrid=" + RRID.ToString() + "\" target=\"_blank\">Click here to review this request.</a></p>", true, false);
                                    }
                                }
                                else
                                {
                                    // No new people to notify, check to see all approvals are finished.
                                    foreach (DataRow drAlready in dsAlready.Tables[0].Rows)
                                    {
                                        if (drAlready["approved"].ToString() == "" && drAlready["denied"].ToString() == "")
                                        {
                                            boolNotify = true;
                                            break;
                                        }
                                    }
                                    oLog.AddEvent(_requestid.ToString(), strCVT, "Notify = " + boolNotify.ToString(), LoggingType.Debug);
                                }
                            }
                        }
                    }
                }
            }

            //if (intApproval)
            return(boolNotify);
        }
        private void BuyWithoutTrucking()
        {
            // This activity will purchase animals based on available funds.
            RuminantHerd ruminantHerd = Resources.RuminantHerd();

            // get current untrucked list of animal purchases
            List <Ruminant> herd = ruminantHerd.PurchaseIndividuals.Where(a => a.BreedParams.Breed == this.PredictedHerdBreed).ToList();

            if (herd.Count() > 0)
            {
                if (this.Status != ActivityStatus.Warning)
                {
                    this.Status = ActivityStatus.Success;
                }
            }

            double fundsAvailable = 0;

            if (bankAccount != null)
            {
                fundsAvailable = bankAccount.FundsAvailable;
            }
            double cost          = 0;
            double shortfall     = 0;
            bool   fundsexceeded = false;

            foreach (var newind in herd)
            {
                if (bankAccount != null)  // perform with purchasing
                {
                    double value = 0;
                    if (newind.SaleFlag == HerdChangeReason.SirePurchase)
                    {
                        value = newind.BreedParams.ValueofIndividual(newind, PurchaseOrSalePricingStyleType.Purchase, RuminantFilterParameters.BreedingSire, "true");
                    }
                    else
                    {
                        value = newind.BreedParams.ValueofIndividual(newind, PurchaseOrSalePricingStyleType.Purchase);
                    }
                    if (cost + value <= fundsAvailable && fundsexceeded == false)
                    {
                        ruminantHerd.PurchaseIndividuals.Remove(newind);
                        newind.ID = ruminantHerd.NextUniqueID;
                        ruminantHerd.AddRuminant(newind, this);
                        cost += value;
                    }
                    else
                    {
                        fundsexceeded = true;
                        shortfall    += value;
                    }
                }
                else // no financial transactions
                {
                    ruminantHerd.PurchaseIndividuals.Remove(newind);
                    newind.ID = ruminantHerd.NextUniqueID;
                    ruminantHerd.AddRuminant(newind, this);
                }
            }

            if (bankAccount != null)
            {
                ResourceRequest purchaseRequest = new ResourceRequest
                {
                    ActivityModel      = this,
                    Required           = cost,
                    AllowTransmutation = false,
                    Reason             = this.PredictedHerdName + " purchases"
                };
                bankAccount.Remove(purchaseRequest);

                // report any financial shortfall in purchases
                if (shortfall > 0)
                {
                    purchaseRequest.Available        = bankAccount.Amount;
                    purchaseRequest.Required         = cost + shortfall;
                    purchaseRequest.Provided         = cost;
                    purchaseRequest.ResourceType     = typeof(Finance);
                    purchaseRequest.ResourceTypeName = BankAccountName;
                    ResourceRequestEventArgs rre = new ResourceRequestEventArgs()
                    {
                        Request = purchaseRequest
                    };
                    OnShortfallOccurred(rre);
                }
            }
        }
        /// <summary>
        /// Method to determine resources required for this activity in the current month
        /// </summary>
        /// <returns>List of required resource requests</returns>
        public override List <ResourceRequest> GetResourcesNeededForActivity()
        {
            if (people is null | food is null)
            {
                return(null);
            }

            List <LabourType> peopleList = people.Items.Where(a => IncludeHiredLabour || a.Hired == false).ToList();

            peopleList.Select(a => a.FeedToTargetIntake == 0);

            // determine AEs to be fed
            double aE = peopleList.Sum(a => a.AdultEquivalent);

            if (aE <= 0)
            {
                return(null);
            }

            int daysInMonth = DateTime.DaysInMonth(Clock.Today.Year, Clock.Today.Month);

            // determine feed limits (max kg per AE per day * AEs * days)
            double intakeLimit = DailyIntakeLimit * aE * daysInMonth;

            // remove previous consumption
            double otherIntake = this.DailyIntakeOtherSources * aE * daysInMonth;

            otherIntake += peopleList.Sum(a => a.GetAmountConsumed());

            List <LabourActivityFeedTarget> labourActivityFeedTargets = this.FindAllChildren <LabourActivityFeedTarget>().Cast <LabourActivityFeedTarget>().ToList();

            // determine targets
            foreach (LabourActivityFeedTarget target in labourActivityFeedTargets)
            {
                // calculate target
                target.Target = target.TargetValue * aE * daysInMonth;

                // set initial level based on off store inputs
                target.CurrentAchieved = target.OtherSourcesValue * aE * daysInMonth;

                // calculate current level from previous intake this month (LabourActivityFeed)
                target.CurrentAchieved += people.GetDietaryValue(target.Metric, IncludeHiredLabour, true) * aE * daysInMonth;

                // add sources outside of this activity to peoples' diets
                if (target.OtherSourcesValue > 0)
                {
                    foreach (var person in peopleList)
                    {
                        LabourDietComponent outsideEat = new LabourDietComponent();
                        outsideEat.AddOtherSource(target.Metric, target.OtherSourcesValue * person.AdultEquivalent * daysInMonth);
                        person.AddIntake(outsideEat);
                    }
                }
            }

            // get max months before spoiling of all food stored (will be zero for non perishable food)
            int maxFoodAge = food.FindAllChildren <HumanFoodStoreType>().Cast <HumanFoodStoreType>().Max(a => a.Pools.Select(b => a.UseByAge - b.Age).DefaultIfEmpty(0).Max());

            // create list of all food parcels
            List <HumanFoodParcel> foodParcels = new List <HumanFoodParcel>();

            foreach (HumanFoodStoreType foodStore in food.FindAllChildren <HumanFoodStoreType>().Cast <HumanFoodStoreType>().ToList())
            {
                foreach (HumanFoodStorePool pool in foodStore.Pools)
                {
                    foodParcels.Add(new HumanFoodParcel()
                    {
                        FoodStore = foodStore,
                        Pool      = pool,
                        Expires   = ((foodStore.UseByAge == 0) ? maxFoodAge + 1: foodStore.UseByAge - pool.Age)
                    });
                }
            }

            foodParcels = foodParcels.OrderBy(a => a.Expires).ToList();

            // if a market exists add the available market produce to the list below that ordered above.
            // order market food by price ascending
            // this will include market available food in the decisions.
            // will need to purchase this food before taking it if cost associated.
            // We can check if the parent of the human food store used is a market and charge accordingly.

            // for each market
            List <HumanFoodParcel> marketFoodParcels = new List <HumanFoodParcel>();
            ResourcesHolder        resources         = Resources.FoundMarket.Resources;

            if (resources != null)
            {
                HumanFoodStore food = resources.HumanFoodStore();
                if (food != null)
                {
                    foreach (HumanFoodStoreType foodStore in food.FindAllChildren <HumanFoodStoreType>())
                    {
                        foreach (HumanFoodStorePool pool in foodStore.Pools)
                        {
                            marketFoodParcels.Add(new HumanFoodParcel()
                            {
                                FoodStore = foodStore,
                                Pool      = pool,
                                Expires   = ((foodStore.UseByAge == 0) ? maxFoodAge + 1 : foodStore.UseByAge - pool.Age)
                            });
                        }
                    }
                }
            }
            foodParcels.AddRange(marketFoodParcels.OrderBy(a => a.FoodStore.Price(PurchaseOrSalePricingStyleType.Purchase).PricePerPacket));

            double fundsAvailable = double.PositiveInfinity;

            if (bankAccount != null)
            {
                fundsAvailable = bankAccount.FundsAvailable;
            }

            int    parcelIndex = 0;
            double intake      = otherIntake;

            // start eating food from list from that about to expire first
            while (parcelIndex < foodParcels.Count)
            {
                foodParcels[parcelIndex].Proportion = 0;
                if (intake < intakeLimit & (labourActivityFeedTargets.Where(a => !a.TargetMet).Count() > 0 | foodParcels[parcelIndex].Expires == 0))
                {
                    // still able to eat and target not met or food about to expire this timestep
                    // reduce by amout that can be eaten
                    double propCanBeEaten = Math.Min(1, (intakeLimit - intake) / (foodParcels[parcelIndex].FoodStore.EdibleProportion * foodParcels[parcelIndex].Pool.Amount));
                    // reduce to target limits
                    double propToTarget = 1;
                    if (foodParcels[parcelIndex].Expires != 0)
                    {
                        // if the food is not going to spoil
                        // then adjust what can be eaten up to target otherwise allow over target consumption to avoid waste

                        LabourActivityFeedTarget targetUnfilled = labourActivityFeedTargets.Where(a => !a.TargetMet).FirstOrDefault();
                        if (targetUnfilled != null)
                        {
                            // calculate reduction to metric target
                            double metricneeded = Math.Max(0, targetUnfilled.Target - targetUnfilled.CurrentAchieved);
                            double amountneeded = metricneeded / foodParcels[parcelIndex].FoodStore.ConversionFactor(targetUnfilled.Metric);

                            propToTarget = Math.Min(1, amountneeded / (foodParcels[parcelIndex].FoodStore.EdibleProportion * foodParcels[parcelIndex].Pool.Amount));
                        }
                    }

                    foodParcels[parcelIndex].Proportion = Math.Min(propCanBeEaten, propToTarget);

                    // work out if there will be a cost limitation, only if a price structure exists for the resource
                    double propToPrice = 1;
                    if (foodParcels[parcelIndex].FoodStore.PricingExists(PurchaseOrSalePricingStyleType.Purchase))
                    {
                        ResourcePricing price = foodParcels[parcelIndex].FoodStore.Price(PurchaseOrSalePricingStyleType.Purchase);
                        double          cost  = (foodParcels[parcelIndex].Pool.Amount * foodParcels[parcelIndex].Proportion) / price.PacketSize * price.PricePerPacket;
                        if (cost > 0)
                        {
                            propToPrice = Math.Min(1, fundsAvailable / cost);
                            // remove cost from running check tally
                            fundsAvailable = Math.Max(0, fundsAvailable - (cost * propToPrice));

                            // real finance transactions will happen in the do activity as stuff is allocated
                            // there should not be shortfall as all the checks and reductions have happened here
                        }
                    }
                    foodParcels[parcelIndex].Proportion *= propToPrice;

                    // update intake
                    double newIntake = (foodParcels[parcelIndex].FoodStore.EdibleProportion * foodParcels[parcelIndex].Pool.Amount * foodParcels[parcelIndex].Proportion);
                    intake += newIntake;
                    // update metrics
                    foreach (LabourActivityFeedTarget target in labourActivityFeedTargets)
                    {
                        target.CurrentAchieved += newIntake * foodParcels[parcelIndex].FoodStore.ConversionFactor(target.Metric);
                    }
                }
                else if (intake >= intakeLimit && labourActivityFeedTargets.Where(a => !a.TargetMet).Count() > 1)
                {
                    // full but could still reach target with some substitution
                    // but can substitute to remove a previous target

                    // does the current parcel have better target values than any previous non age 0 pool of a different food type
                }
                else
                {
                    break;
                }
                parcelIndex++;
            }

            // fill resource requests
            List <ResourceRequest> requests = new List <ResourceRequest>();

            foreach (var item in foodParcels.GroupBy(a => a.FoodStore))
            {
                double amount = item.Sum(a => a.Pool.Amount * a.Proportion);
                if (amount > 0)
                {
                    double financeLimit = 1;
                    // if obtained from the market make financial transaction before taking
                    ResourcePricing price = item.Key.Price(PurchaseOrSalePricingStyleType.Sale);
                    if (bankAccount != null && item.Key.Parent.Parent.Parent == Market && price.PricePerPacket > 0)
                    {
                        // if shortfall reduce purchase
                        ResourceRequest marketRequest = new ResourceRequest
                        {
                            ActivityModel               = this,
                            Required                    = amount / price.PacketSize * price.PricePerPacket,
                            AllowTransmutation          = false,
                            Reason                      = "Food purchase",
                            MarketTransactionMultiplier = 1
                        };
                        bankAccount.Remove(marketRequest);
                    }

                    requests.Add(new ResourceRequest()
                    {
                        Resource           = item.Key,
                        ResourceType       = typeof(HumanFoodStore),
                        AllowTransmutation = false,
                        Required           = amount * financeLimit,
                        ResourceTypeName   = item.Key.Name,
                        ActivityModel      = this,
                        Reason             = "Consumption"
                    });
                }
            }

            // if still hungry and funds available, try buy food in excess of what stores (private or market) offered using transmutation if present.
            // This will force the market or private sources to purchase more food to meet demand if transmutation available.
            // if no market is present it will look to transmutating from its own stores if possible.
            // this means that other than a purchase from market (above) this activity doesn't need to worry about financial tranactions.
            if (intake < intakeLimit && (labourActivityFeedTargets.Where(a => !a.TargetMet).Count() > 0) && fundsAvailable > 0)
            {
                ResourcesHolder resourcesHolder = Resources;
                // if market is present point to market to find the resource
                if (Market != null)
                {
                    resourcesHolder = Market.FindChild <ResourcesHolder>();
                }

                // don't worry about money anymore. The over request will be handled by the transmutation.
                // move through specified purchase list
                foreach (LabourActivityFeedTargetPurchase purchase in this.FindAllChildren <LabourActivityFeedTargetPurchase>().Cast <LabourActivityFeedTargetPurchase>().ToList())
                {
                    HumanFoodStoreType foodtype = resourcesHolder.GetResourceItem(this, purchase.FoodStoreName, OnMissingResourceActionTypes.Ignore, OnMissingResourceActionTypes.Ignore) as HumanFoodStoreType;
                    if (foodtype != null && (foodtype.TransmutationDefined & intake < intakeLimit))
                    {
                        LabourActivityFeedTarget targetUnfilled = labourActivityFeedTargets.Where(a => !a.TargetMet).FirstOrDefault();
                        if (targetUnfilled != null)
                        {
                            // calculate reduction to metric target
                            double metricneeded = Math.Max(0, (targetUnfilled.Target - targetUnfilled.CurrentAchieved));
                            double amountneeded = metricneeded / foodtype.ConversionFactor(targetUnfilled.Metric);

                            if (intake + amountneeded > intakeLimit)
                            {
                                amountneeded = intakeLimit - intake;
                            }
                            double amountfood = amountneeded / foodtype.EdibleProportion;

                            // update intake
                            intake += amountfood;

                            // find in requests or create a new one
                            ResourceRequest foodRequestFound = requests.Find(a => a.Resource == foodtype) as ResourceRequest;
                            if (foodRequestFound is null)
                            {
                                requests.Add(new ResourceRequest()
                                {
                                    Resource           = foodtype,
                                    ResourceType       = typeof(HumanFoodStore),
                                    AllowTransmutation = true,
                                    Required           = amountfood,
                                    ResourceTypeName   = purchase.FoodStoreName.Split('.')[1],
                                    ActivityModel      = this,
                                    Reason             = "Consumption"
                                });
                            }
                            else
                            {
                                foodRequestFound.Required          += amountneeded;
                                foodRequestFound.AllowTransmutation = true;
                            }
                        }
                    }
                }
                // NOTE: proportions of purchased food are not modified if the sum does not add up to 1 or some of the food types are not available.
            }

            return(requests);
        }
        public Task ProcessAsync(ResourceRequest request)
        {
            if (_loader != null && Engine != null)
            {
                Download = _loader.FetchWithCors(new CorsRequest(request)
                {
                    Behavior = OriginBehavior.Taint,
                    Setting = _script.CrossOrigin.ToEnum(CorsSetting.None),
                    Integrity = _document.Options.GetProvider<IIntegrityProvider>()
                });
                return Download.Task;
            }

            return null;
        }
        private void BuyWithTrucking()
        {
            // This activity will purchase animals based on available funds.
            RuminantHerd ruminantHerd = Resources.RuminantHerd();

            int    trucks         = 0;
            int    head           = 0;
            double aESum          = 0;
            double fundsAvailable = 0;

            if (bankAccount != null)
            {
                fundsAvailable = bankAccount.FundsAvailable;
            }
            double cost          = 0;
            double shortfall     = 0;
            bool   fundsexceeded = false;

            // get current untrucked list of animal purchases
            List <Ruminant> herd = ruminantHerd.PurchaseIndividuals.Where(a => a.BreedParams.Breed == this.PredictedHerdBreed).OrderByDescending(a => a.Weight).ToList();

            if (herd.Count() == 0)
            {
                return;
            }

            // if purchase herd > min loads before allowing trucking
            if (herd.Select(a => a.Weight / 450.0).Sum() / trucking.Number450kgPerTruck >= trucking.MinimumTrucksBeforeBuying)
            {
                // while truck to fill
                while (herd.Select(a => a.Weight / 450.0).Sum() / trucking.Number450kgPerTruck > trucking.MinimumLoadBeforeBuying)
                {
                    bool nonloaded = true;
                    trucks++;
                    double load450kgs = 0;
                    // while truck below carrying capacity load individuals
                    foreach (var ind in herd)
                    {
                        if (load450kgs + (ind.Weight / 450.0) <= trucking.Number450kgPerTruck)
                        {
                            nonloaded = false;
                            head++;
                            aESum      += ind.AdultEquivalent;
                            load450kgs += ind.Weight / 450.0;

                            if (bankAccount != null)  // perform with purchasing
                            {
                                double value = 0;
                                if (ind.SaleFlag == HerdChangeReason.SirePurchase)
                                {
                                    value = ind.BreedParams.ValueofIndividual(ind, PurchaseOrSalePricingStyleType.Purchase, RuminantFilterParameters.BreedingSire, "true");
                                }
                                else
                                {
                                    value = ind.BreedParams.ValueofIndividual(ind, PurchaseOrSalePricingStyleType.Purchase);
                                }
                                if (cost + value <= fundsAvailable && fundsexceeded == false)
                                {
                                    ind.ID = ruminantHerd.NextUniqueID;
                                    ruminantHerd.AddRuminant(ind, this);
                                    ruminantHerd.PurchaseIndividuals.Remove(ind);
                                    cost += value;
                                }
                                else
                                {
                                    fundsexceeded = true;
                                    shortfall    += value;
                                }
                            }
                            else // no financial transactions
                            {
                                ind.ID = ruminantHerd.NextUniqueID;
                                ruminantHerd.AddRuminant(ind, this);
                                ruminantHerd.PurchaseIndividuals.Remove(ind);
                            }
                        }
                    }
                    if (nonloaded)
                    {
                        Summary.WriteWarning(this, String.Format("There was a problem loading the purchase truck as purchase individuals did not meet the loading criteria for breed [r={0}]", this.PredictedHerdBreed));
                        break;
                    }
                    if (shortfall > 0)
                    {
                        break;
                    }

                    herd = ruminantHerd.PurchaseIndividuals.Where(a => a.BreedParams.Breed == this.PredictedHerdBreed).OrderByDescending(a => a.Weight).ToList();
                }

                if (Status != ActivityStatus.Warning)
                {
                    if (ruminantHerd.PurchaseIndividuals.Where(a => a.BreedParams.Breed == this.PredictedHerdBreed).Count() == 0)
                    {
                        SetStatusSuccess();
                    }
                    else
                    {
                        Status = ActivityStatus.Partial;
                    }
                }

                // create trucking emissions
                if (trucking != null && trucks > 0)
                {
                    trucking.ReportEmissions(trucks, false);
                }

                if (bankAccount != null && (trucks > 0 || trucking == null))
                {
                    ResourceRequest purchaseRequest = new ResourceRequest
                    {
                        ActivityModel      = this,
                        Required           = cost,
                        AllowTransmutation = false,
                        Reason             = this.PredictedHerdName + " purchases"
                    };
                    bankAccount.Remove(purchaseRequest);

                    // report any financial shortfall in purchases
                    if (shortfall > 0)
                    {
                        purchaseRequest.Available        = bankAccount.Amount;
                        purchaseRequest.Required         = cost + shortfall;
                        purchaseRequest.Provided         = cost;
                        purchaseRequest.ResourceType     = typeof(Finance);
                        purchaseRequest.ResourceTypeName = BankAccountName;
                        ResourceRequestEventArgs rre = new ResourceRequestEventArgs()
                        {
                            Request = purchaseRequest
                        };
                        OnShortfallOccurred(rre);
                    }

                    ResourceRequest expenseRequest = new ResourceRequest
                    {
                        Available          = bankAccount.Amount,
                        ActivityModel      = this,
                        AllowTransmutation = false
                    };

                    // calculate transport costs
                    if (trucking != null)
                    {
                        expenseRequest.Required = trucks * trucking.DistanceToMarket * trucking.CostPerKmTrucking;
                        expenseRequest.Reason   = "Transport purchases";
                        bankAccount.Remove(expenseRequest);

                        if (expenseRequest.Required > expenseRequest.Available)
                        {
                            expenseRequest.Available        = bankAccount.Amount;
                            expenseRequest.ResourceType     = typeof(Finance);
                            expenseRequest.ResourceTypeName = BankAccountName;
                            ResourceRequestEventArgs rre = new ResourceRequestEventArgs()
                            {
                                Request = expenseRequest
                            };
                            OnShortfallOccurred(rre);
                        }
                    }
                }
            }
            else
            {
                this.Status = ActivityStatus.Warning;
            }
        }
 public Task<Resource> GetInfoAsync(ResourceRequest request, CancellationToken cancellationToken = default(CancellationToken))
 {
     return GetAsync<ResourceRequest, Resource>("resources", request, cancellationToken);
 }
Beispiel #58
0
        public TestSearchKeywordApplicationField() : base()
        {
            List <string> applicationField = new List <string> {
            };
            string resourceName            = string.Empty;

            foreach (var resourceId in Enum.GetValues(typeof(Enums.ResourceType)).Cast <Enums.ResourceType>())
            {
                resourceName = resourceId == Enums.ResourceType.Candidate ? "Person" : resourceId.ToString();
                applicationField.Add(resourceName + "." + AppField);
            }

            readFields = new HrbcFieldReader(applicationField, new[] { FieldProperty.Resource });

            int testUser = 1;

            records = new HrbcRecordCreator(() => ResourceRequest.CreateRecords()
                                            .Append(ResourceId.Client,
                                                    content => content
                                                    .Append("P_Name", "Test Client")
                                                    .Append("P_Owner", testUser),
                                                    "client1")
                                            .Append(ResourceId.Recruiter,
                                                    content => content
                                                    .Append("P_Name", "Test Recruiter")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1")),
                                                    "recruiter1")
                                            .Append(ResourceId.Job,
                                                    content => content
                                                    .Append("P_Position", "Test Job")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1"))
                                                    .Append("P_Recruiter", new CreateRecordRequest.Reference("recruiter1")),
                                                    "job1")
                                            .Append(ResourceId.Job,
                                                    content => content
                                                    .Append("P_Position", "Test Job")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1"))
                                                    .Append("P_Recruiter", new CreateRecordRequest.Reference("recruiter1")),
                                                    "job2")
                                            .Append(ResourceId.Person,
                                                    content => content
                                                    .Append("P_Name", "Test Person")
                                                    .Append("P_Owner", testUser),
                                                    "person1")
                                            .Append(ResourceId.Resume,
                                                    content => content
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Candidate", new CreateRecordRequest.Reference("person1")),
                                                    "resume1")
                                            .Append(ResourceId.Resume,
                                                    content => content
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_Candidate", new CreateRecordRequest.Reference("person1")),
                                                    "resume2")

                                            /* Example of a progress element:
                                             *               .Append(ResourceId.Process,
                                             *                  content => content
                                             *                      .Append("P_Owner", testUser)
                                             *                      .Append("P_Client", new CreateRecordRequest.Reference("client"))
                                             *                      .Append("P_Recruiter", new CreateRecordRequest.Reference("recruiter"))
                                             *                      .Append("P_Job", new CreateRecordRequest.Reference("job"))
                                             *                      .Append("P_Candidate", new CreateRecordRequest.Reference("person"))
                                             *                      .Append("P_Resume", new CreateRecordRequest.Reference("resume")),
                                             *                  "process")
                                             */
                                            .Append(ResourceId.Sales,
                                                    content => content
                                                    //.Append("P_SalesAmount", 5000)
                                                    .Append("P_Owner", testUser),
                                                    "sales1")
                                            .Append(ResourceId.Activity,
                                                    content => content
                                                    .Append("P_Title", "Test Activity")
                                                    .Append("P_Owner", testUser)
                                                    .Append("P_FromDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                                                    "activity1")
                                            .Append(ResourceId.Contract,
                                                    content => content
                                                    .Append("P_Name", "Test Contract")
                                                    //.Append("P_Owner", testUser)
                                                    .Append("P_Client", new CreateRecordRequest.Reference("client1")),
                                                    "contract1"));
        }
Beispiel #59
0
 public ResourceResponse OnRequest(ResourceRequest request)
 {
     var req = request;
     return null;
 }
Beispiel #60
0
    private void OnAssetLoaded(ResourceRequest request)
    {
        GameObject asset = request.asset as GameObject;

        loadCallBack?.Invoke(asset);
    }