////////////////////////////////////////////////////////////////////////////////////////////////
		/*--------------------------------------------------------------------------------------------*/
		internal void UpdateWithCursor(Vector3? pCursorPosition) {
			if ( pCursorPosition == null || vIsAnimating ) {
				HighlightProgress = 0;
				vSelectionStart = null;
				IsSelectionPrevented = false;
				return;
			}

			if ( vCursorDistanceFunc == null ) {
				throw new Exception("No CursorDistanceFunction has been set.");
			}

			if ( !NavItem.IsEnabled ) {
				HighlightDistance = float.MaxValue;
				HighlightProgress = 0;
				return;
			}

			float dist = vCursorDistanceFunc((Vector3)pCursorPosition);
			float prog = Mathf.InverseLerp(vSettings.HighlightDistanceMax,
				vSettings.HighlightDistanceMin, dist);

			HighlightDistance = dist;
			HighlightProgress = prog;
		}
        public DateTime? GetLatestUpdate()
        {
            if (_lastUpdated.HasValue) return _lastUpdated;

            var directory = new DirectoryInfo(BaseDirectory);

            var latest =
                directory.GetFiles("*.*", SearchOption.AllDirectories)
                    .OrderByDescending(f => f.LastWriteTimeUtc)
                    .FirstOrDefault();

            _lastUpdated = latest != null ? (DateTime?)latest.LastWriteTimeUtc : null;
            return _lastUpdated;
            /*
            var directory = new DirectoryInfo(BaseDirectory);

            if (!directory.Exists)
            {
                directory.Create();
                return null;
            }

            var latest =
    directory.GetFiles("*.*", SearchOption.AllDirectories)
        .OrderByDescending(f => f.LastWriteTimeUtc)
        .FirstOrDefault();

            return latest != null ? (DateTime?)latest.LastWriteTimeUtc : null;
             * */
        }
		public override void Copy(ODataObject source, JsonSerializer serializer)
		{
			if(source == null || serializer == null) return;
			base.Copy(source, serializer);

			var typedSource = source as ShareItemHistory;
			if(typedSource != null)
			{
				Title = typedSource.Title;
				Recipient = typedSource.Recipient;
				ActivityType = typedSource.ActivityType;
				DownloadDate = typedSource.DownloadDate;
			}
			else
			{
				JToken token;
				if(source.TryGetProperty("Title", out token) && token.Type != JTokenType.Null)
				{
					Title = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
				}
				if(source.TryGetProperty("Recipient", out token) && token.Type != JTokenType.Null)
				{
					Recipient = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
				}
				if(source.TryGetProperty("ActivityType", out token) && token.Type != JTokenType.Null)
				{
					ActivityType = (SafeEnum<ItemAction>)serializer.Deserialize(token.CreateReader(), typeof(SafeEnum<ItemAction>));
				}
				if(source.TryGetProperty("DownloadDate", out token) && token.Type != JTokenType.Null)
				{
					DownloadDate = (DateTime?)serializer.Deserialize(token.CreateReader(), typeof(DateTime?));
				}
			}
		}
Exemple #4
0
        public Key_CircleSaleMan(
		long iD,
			string name,
			long userID,
			string qQ,
			string phone,
			string companyName,
			string companyAddress,
			string job,
			double positionX,
			double positionY,
			int checkState,
			DateTime modifyTime,
			DateTime createTime,
			string memo
	)
        {
            _ID             = iD;
            _Name           = name;
            _UserID         = userID;
            _QQ             = qQ;
            _Phone          = phone;
            _CompanyName    = companyName;
            _CompanyAddress = companyAddress;
            _Job            = job;
            _PositionX      = positionX;
            _PositionY      = positionY;
            _CheckState     = checkState;
            _ModifyTime     = modifyTime;
            _CreateTime     = createTime;
            _Memo           = memo;
        }
Exemple #5
0
        public void PlayTrack(QueuedTrack trackToPlay)
        {
            logger.Trace("MusicService.PlayTrack");
            logger.Debug("Attempting to play track {0}", trackToPlay.ToLoggerFriendlyTrackName());

            //Reset the paused data
            lastPaused = null;
            totalPausedDuration = 0;

            currentProvider = musicProviderFactory.GetMusicProviderByIdentifier(trackToPlay.Track.MusicProvider.Identifier);

            //Either play the original queued track or the Big Rick if tthe track is rickrolled
            var rickRollTrack = rickRollService.RickRoll(trackToPlay.Track, trackToPlay.User);

            currentProvider.PlayTrack(rickRollTrack);
            trackToPlay.StartedPlayingDateTime = nowHelper.Now;
            queuedTrackDataService.InsertOrUpdate(trackToPlay);
            int total;
            var recentlyPlayed = queuedTrackDataService.GetAll()
                .GetQueuedTracksByUser(null, 1, 5, out total)
                .Select(r => alreadyQueuedHelper.ResetAlreadyQueued(r, trackToPlay.User)).ToList();

            callbackClient.TrackHistoryChanged(new PagedResult<QueuedTrack> { HasMorePages = false, PageData = recentlyPlayed });

            currentlyPlayingTrack = trackToPlay;
            callbackClient.PlayingTrackChanged(CurrentlyPlayingTrack);
            logger.Debug("Playing track {0} queued by {1}", trackToPlay.ToLoggerFriendlyTrackName(), trackToPlay.User);
        }
 public TariffHistory(long phoneID, long tariffID, DateTime startDate, DateTime? endDate)
 {
     _phoneID = phoneID;
     _tariffID = tariffID;
     _startDate = startDate;
     _endDate = endDate;
 }
 public PackageCatalogItem(NupkgMetadata nupkgMetadata, DateTime? createdDate = null, DateTime? lastEditedDate = null, DateTime? publishedDate = null, string licenseNames = null, string licenseReportUrl = null)
 {
     _nupkgMetadata = nupkgMetadata;
     _createdDate = createdDate;
     _lastEditedDate = lastEditedDate;
     _publishedDate = publishedDate;
 }
 public PedidoEntregaHis(PedidoEntregaHisId id, DateTime? fechainicial, DateTime? fechafinal, decimal? cantidad)
 {
     this._id= id;
     this._fechainicial= fechainicial;
     this._fechafinal= fechafinal;
     this._cantidad= cantidad;
 }
 /// <summary>
 /// Instantiates Credentials with the parameterized properties
 /// </summary>
 /// <param name="accessKeyId">The access key ID that identifies the temporary security credentials.</param>
 /// <param name="secretAccessKey">The secret access key that can be used to sign requests.</param>
 /// <param name="sessionToken">The token that users must pass to the service API to use the temporary credentials.</param>
 /// <param name="expiration">The date on which the current credentials expire.</param>
 public Credentials(string accessKeyId, string secretAccessKey, string sessionToken, DateTime expiration)
 {
     _accessKeyId = accessKeyId;
     _secretAccessKey = secretAccessKey;
     _sessionToken = sessionToken;
     _expiration = expiration;
 }
Exemple #10
0
        /// <summary>
        /// Crea una Scadenza valida
        /// </summary>
        public ScadenzaFattura(Spesa spesa, DateTime? scadenza, decimal? importo)
        {
            _spesaRiferimento = spesa;
            _scadenza = scadenza;
            _importo = importo;
            Stato = StatoSpesaEnum.Inserita;

            if (spesa != null && spesa.ImportoRitenuta != 0 && spesa.ImportoLordo != 0)
            {
                var denominatore = spesa.ImportoLordo - spesa.ImportoRitenuta.GetValueOrDefault();
                if(denominatore != 0)
                    ImportoRitenuta = (importo / denominatore) * spesa.ImportoRitenuta;
                else
                    ImportoRitenuta = spesa.ImportoRitenuta;
            }

            if (spesa != null)
            {
                var autorizzata = spesa.Autorizzata;
                if (autorizzata)
                {
                    Stato = StatoSpesaEnum.Autorizzata;
                    _importoAutorizzato = _importo;
                }

                spesa.Scadenze.Add(this);
            }
        }
Exemple #11
0
 public XrdDocument(Uri subject, DateTime? expires, List<Uri> aliases, List<XrdLink> links)
 {
     Subject = subject;
     Expires = expires;
     Aliases = aliases;
     Links = links;
 }
Exemple #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Cookie"/> class with a specific name,
        /// value, domain, path and expiration date.
        /// </summary>
        /// <param name="name">The name of the cookie.</param>
        /// <param name="value">The value of the cookie.</param>
        /// <param name="domain">The domain of the cookie.</param>
        /// <param name="path">The path of the cookie.</param>
        /// <param name="expiry">The expiration date of the cookie.</param>
        /// <exception cref="ArgumentException">If the name is <see langword="null"/> or an empty string,
        /// or if it contains a semi-colon.</exception>
        /// <exception cref="ArgumentNullException">If the value is <see langword="null"/>.</exception>
        public Cookie(string name, string value, string domain, string path, DateTime? expiry)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Cookie name cannot be null or empty string", "name");
            }

            if (value == null)
            {
                throw new ArgumentNullException("value", "Cookie value cannot be null");
            }

            if (name.IndexOf(';') != -1)
            {
                throw new ArgumentException("Cookie names cannot contain a ';': " + name, "name");
            }

            this.cookieName = name;
            this.cookieValue = value;
            if (!string.IsNullOrEmpty(path))
            {
                this.cookiePath = path;
            }

            this.cookieDomain = StripPort(domain);

            if (expiry != null)
            {
                this.cookieExpiry = expiry;
            }
        }
Exemple #13
0
 public void Stop() 
 {
     if (this.IsRunning) 
     { this.IsRunning = false; 
         this.EndUtc = DateTime.UtcNow; 
     }
 }
Exemple #14
0
 public XrdDocument(Uri subject, DateTime? expires)
 {
     Subject = subject;
     Expires = expires;
     Aliases = new List<Uri>();
     Links = new List<XrdLink>();
 }
Exemple #15
0
		/// <summary>
		/// Constructs a new <see cref="SeriesNode"/> using default values.
		/// </summary>
		public SeriesNode()
		{
			_images = new SopInstanceNodeCollection(this);
			_instanceUid = StudyBuilder.NewUid();
			_description = "Untitled Series";
			_dateTime = System.DateTime.Now;
		}
		public void Deserialize(XmlNode node)
		{
			foreach (XmlNode childNode in node.ChildNodes)
			{
				switch (childNode.Name)
				{
					case "Month":
						{
							DateTime tempDateTime;
							if (DateTime.TryParse(childNode.InnerText, out tempDateTime))
								Month = tempDateTime;
						}
						break;
					case "StartDate":
						{
							DateTime tempDateTime;
							if (DateTime.TryParse(childNode.InnerText, out tempDateTime))
								StartDate = tempDateTime;
						}
						break;
					case "EndDate":
						{
							DateTime tempDateTime;
							if (DateTime.TryParse(childNode.InnerText, out tempDateTime))
								EndDate = tempDateTime;
						}
						break;
				}
			}
		}
    private void ReadInvalidUserNames()
    {
      string filename = Configuration.Settings.InvalidUserNameFile;
      if (string.IsNullOrEmpty(filename))
        return;
      filename = FileUtils.MapRelPathToBaseDir(filename);

      FileInfo inf = new FileInfo(filename);
      if (InvalidUserNamesLastRead != null && inf.LastWriteTime <= InvalidUserNamesLastRead.Value)
        return;

      InvalidUserNames = new HashSet<string>();
      FileReloadTimes++;
      using (StreamReader r = new StreamReader(filename))
      {
        string line;
        while ((line = r.ReadLine()) != null)
        {
          line = line.Trim();
          if (line != string.Empty && !line.StartsWith("#"))
          {
            InvalidUserNames.Add(line);
          }
        }
      }

      InvalidUserNamesLastRead = inf.LastWriteTime;
    }
        private void ForeCastInit(int liveid)
        {
                this.live_id = liveid;
                var l = dMatch.liveTables[live_id].First();
                home_team_big = l.Home_team_big;
                away_team_big = l.Away_team_big;
                home_team = l.Home_team;
                away_team = l.Away_team;
                matchtime = l.Match_time;

                //修正把比赛类型搞进去  2011.6.17
                matchtype = l.Match_type;

                var top20h = dMatch.dHome[home_team_big].Union(dMatch.dHome[away_team_big]).
                    Union(dMatch.dAway[home_team_big]).Union(dMatch.dAway[away_team_big]);

                //修正把比赛日期搞进去了 2011.6.14
                var top20hh = top20h.Where(e => e.Match_time.Value.Date < matchtime.Value.Date);

                //修正把比赛类型搞进去  2011.6.17
                Top20 = top20hh.Where(e => e.Match_type == matchtype).OrderByDescending(e => e.Match_time).Take(40).ToList();

                // .ToList();

                //var top20h = matches.result_tb_lib.Where(e => e.home_team_big == l.home_team_big || e.away_team_big == l.away_team_big);
                //var top20a = matches.result_tb_lib.Where(e => e.home_team_big == l.away_team_big || e.away_team_big == l.home_team_big);
                //Top20 = top20h.Union(top20a).Where(e => e.match_time < matchtime).OrderByDescending(e => e.match_time).Take(40).ToList();
                Top20Count = Top20.Count();
            }    
Exemple #19
0
        public void TestNullableViaResultClass2()
        {
            NullableClass clazz = new NullableClass();
            clazz.TestBool = true;
            clazz.TestByte = 155;
            clazz.TestChar = 'a';
            DateTime? date = new DateTime?(DateTime.Now);
            clazz.TestDateTime = date;
            clazz.TestDecimal = 99.53M;
            clazz.TestDouble = 99.5125;
            Guid? guid = new Guid?(Guid.NewGuid());
            clazz.TestGuid = guid;
            clazz.TestInt16 = 45;
            clazz.TestInt32 = 99;
            clazz.TestInt64 = 1234567890123456789;
            clazz.TestSingle = 4578.46445454112f;

            dataMapper.Insert("InsertNullable", clazz);
            clazz = null;
            clazz = dataMapper.QueryForObject<NullableClass>("GetClassNullable", 1);

            Assert.IsNotNull(clazz);
            Assert.AreEqual(1, clazz.Id);
            Assert.IsTrue(clazz.TestBool.Value);
            Assert.AreEqual(155, clazz.TestByte);
            Assert.AreEqual('a', clazz.TestChar);
            Assert.AreEqual(date.Value.ToString(), clazz.TestDateTime.Value.ToString());
            Assert.AreEqual(99.53M, clazz.TestDecimal);
            Assert.AreEqual(99.5125, clazz.TestDouble);
            Assert.AreEqual(guid, clazz.TestGuid);
            Assert.AreEqual(45, clazz.TestInt16);
            Assert.AreEqual(99, clazz.TestInt32);
            Assert.AreEqual(1234567890123456789, clazz.TestInt64);
            Assert.AreEqual(4578.46445454112f, clazz.TestSingle);
        } 
 public UrlItemTableEntity(string shortUrl, string fullUrl)
 {
     this.PartitionKey = shortUrl;
     this.RowKey = UrlItemTableEntity.TableRowKey;
     this.FullUrl = fullUrl;
     this.CreatedDateTime = DateTime.UtcNow;
 }
        /// <summary>
        ///     Starts processing of nmea file using passed delay action.
        ///     Send GeoPosition message to message bus.
        /// </summary>
        public void Start(Action<TimeSpan> delayAction)
        {
            _positionDateTime = null;
            _position = new GeoPosition();
            string line;
            _isStarted = true;
            while ((line = _parser.ReadLine()) != null)
            {
                if (!_isStarted) break;

                if (line.Length <= 0) continue;

                var message = _parser.ParseLine(line);
                if (message == null || !CanSetPositionFromMessage(message) || _position.Date.Year < 2001)
                    continue;

                DateTime currentDateTime = _position.DateTime;
                if (_positionDateTime != null)
                {
                    var sleepTime = currentDateTime - _positionDateTime.Value;
                    delayAction(sleepTime);
                    _messageBus.Send(_position);
                }
                _positionDateTime = currentDateTime;
            }
            _isStarted = false;
            FireDone();
        }
Exemple #22
0
 public override bool isComplete(List<string> additionalDetails = null)
 {
     if (firstRequest.HasValue)
         return (DateTime.Now - firstRequest.Value).TotalSeconds >= time;
     firstRequest = DateTime.Now;
     return false;
 }
        public RelativeOldness(DateTime dateTime)
            : this()
        {
            _dateTime = dateTime;

            RefreshRelativeTime();
        }
Exemple #24
0
 public ApprovalCreated(Guid id, string patientId, string patientName, DateTime? dateOfBirth)
 {
     this.Id = id;
     this.PatientId = patientId;
     this.PatientName = patientName;
     this.DateOfBirth = dateOfBirth;
 }
Exemple #25
0
 public Project(object key, string number, string name)
     : base(key)
 {
     this.number = number;
     this.name = name;
     this.address = null;
     this.owner = null;
     this.constructionAdministrator = null;
     this.principal = null;
     this.contractDate = null;
     this.estimatedStartDate = null;
     this.estimatedCompletionDate = null;
     this.currentCompletionDate = null;
     this.actualCompletionDate = null;
     this.contingencyAllowanceAmount = 0;
     this.testingAllowanceAmount = 0;
     this.utilityAllowanceAmount = 0;
     this.originalConstructionCost = 0;
     this.totalChangeOrderDays = 0;
     this.adjustedConstructionCost = 0;
     this.totalChangeOrdersAmount = 0;
     this.totalSquareFeet = 0;
     this.percentComplete = 0;
     this.remarks = string.Empty;
     this.aeChangeOrderAmount = 0;
     this.contractReason = string.Empty;
     this.agencyApplicationNumber = string.Empty;
     this.agencyFileNumber = string.Empty;
     this.segment = null;
     this.allowances = new List<Allowance>();
 }
 public FrmLichPhatSonNew(object id, string viewIdLPSCt, bool? isAdd, IPhieuFix parentFix)
 {
     _bkGioPhat = null;
     _viewIdLPSCt = viewIdLPSCt;
     _parentFix = parentFix;
     Init(id, isAdd);
 }
        /// <summary>
        /// Turns a RST/ProofKey pair into a GenericXmlSecurityToken.
        /// </summary>
        /// <param name="rstr">The RSTR.</param>
        /// <param name="proofKey">The ProofKey.</param>
        /// <returns>A GenericXmlSecurityToken</returns>
        public static GenericXmlSecurityToken ToGenericXmlSecurityToken(this RequestSecurityTokenResponse rstr, SecurityToken proofKey)
        {
            DateTime? created = null;
            DateTime? expires = null;
            if (rstr.Lifetime != null)
            {
                created = rstr.Lifetime.Created;
                expires = rstr.Lifetime.Expires;
                if (!created.HasValue)
                {
                    created = new DateTime?(DateTime.UtcNow);
                }
                if (!expires.HasValue)
                {
                    expires = new DateTime?(DateTime.UtcNow.AddHours(10.0));
                }
            }
            else
            {
                created = new DateTime?(DateTime.UtcNow);
                expires = new DateTime?(DateTime.UtcNow.AddHours(10.0));
            }

            return new GenericXmlSecurityToken(
                ExtractTokenXml(rstr),
                proofKey,
                created.Value,
                expires.Value,
                rstr.RequestedAttachedReference,
                rstr.RequestedUnattachedReference,
                new ReadOnlyCollection<IAuthorizationPolicy>(new List<IAuthorizationPolicy>()));
        }
Exemple #28
0
 public AccessDenied(uint? blockedID)
 {
     this.blockedID = blockedID;
     this.machineID = null;
     this.blockedSince = null;
     this.blockedUntil = null;
 }
Exemple #29
0
 public AccessDenied(uint? blockedID, string machineID, DateTime? blockedSince, DateTime? blockedUntil)
     : this(blockedID)
 {
     this.machineID = machineID;
     this.blockedSince = blockedSince;
     this.blockedUntil = blockedUntil;
 }
 protected void DoHideSuperLayer(object state)
 {
   _currentSuperLayerName = null;
   _superLayerEndTime = null;
   IScreenManager screenManager = ServiceRegistration.Get<IScreenManager>();
   screenManager.SetSuperLayer(null);
 }
        public IActionResult GetXlsDeliveryDetail(string supplier, DateTime?dateFrom, DateTime?dateTo)
        {
            try
            {
                byte[]         xlsInBytes;
                int            offset   = Convert.ToInt32(Request.Headers["x-timezone-offset"]);
                DateTimeOffset DateFrom = dateFrom == null ? new DateTime(1970, 1, 1) : Convert.ToDateTime(dateFrom);
                DateTimeOffset DateTo   = dateTo == null ? DateTime.Now : Convert.ToDateTime(dateTo);

                var xls = facade.GenerateExcelDeliveryDetail(supplier, dateFrom, dateTo, offset);

                string filename = String.Format($"Monitoring Detail Ketepatan Pengiriman - {DateFrom.ToOffset(new TimeSpan(offset, 0, 0)).ToString("dd MMM yyyy", new CultureInfo("id-ID"))} - {DateTo.ToOffset(new TimeSpan(offset, 0, 0)).ToString("dd MMM yyyy", new CultureInfo("id-ID"))}.xlsx");

                xlsInBytes = xls.ToArray();
                var file = File(xlsInBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename);
                return(file);
            }
            catch (Exception e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.INTERNAL_ERROR_STATUS_CODE, e.Message)
                    .Fail();
                return(StatusCode(General.INTERNAL_ERROR_STATUS_CODE, Result));
            }
        }
Exemple #32
0
        /// <summary>
        /// retorna a diferenca entre datas em meses (modo Fluent)
        /// </summary>
        /// <param name="dataFinal">data Final</param>
        /// <param name="dataInicial">data Inicial</param>
        public static int diferencaMeses(this DateTime?dataFinal, DateTime?dataInicial)
        {
            var valorEmMeses = dataFinal.diferencaDias(dataInicial) / 30;

            return(valorEmMeses);
        }
 public bool ConditionMet(int fundModel, DateTime academicYearStart, DateTime?learnActEndDate, string conRefNumber)
 {
     return(FundModelConditionMet(fundModel) &&
            (!learnActEndDate.HasValue || LearnActEndDateConditionMet(learnActEndDate.Value, academicYearStart)) &&
            FCTFundingConditionMet(conRefNumber));
 }
        public MemberWalletView(int cmid, int?credits, int?points, DateTime?creditsExpiration, DateTime?pointsExpiration)
        {
            if (!credits.HasValue)
            {
                credits = new int?(0);
            }
            if (!points.HasValue)
            {
                points = new int?(0);
            }
            if (!creditsExpiration.HasValue)
            {
                creditsExpiration = new DateTime?(DateTime.MinValue);
            }
            if (!pointsExpiration.HasValue)
            {
                pointsExpiration = new DateTime?(DateTime.MinValue);
            }

            SetMemberWallet(cmid, credits.Value, points.Value, creditsExpiration.Value, pointsExpiration.Value);
        }
Exemple #35
0
        public static async Task <IRestResponse <ResultValue> > UpdateDataCabin(int id, string dataCabinName, int dataCabinTypeId, int clientId, int?userId, int dateTypeId, DateTime?startDate, DateTime?endDate)
        {
            var startDatex = startDate.ToString().Replace('/', '-');
            var endDatex   = endDate.ToString().Replace('/', '-');
            var request    = new RestRequest(String.Format(SystemResource.UpdateDataCabinRequest, id, dataCabinName, dataCabinTypeId, clientId, userId, dateTypeId, startDatex, endDatex), Method.POST);

            return(await Client.ExecutePostTaskAsync <ResultValue>(request));
        }
Exemple #36
0
        /// <summary>
        /// Binds the campus grid.
        /// </summary>
        private void BindCampusGrid()
        {
            if (_eventItem != null)
            {
                pnlEventCalendarCampusItems.Visible = true;

                var rockContext = new RockContext();

                var qry = new EventItemOccurrenceService(rockContext)
                          .Queryable().AsNoTracking()
                          .Where(c => c.EventItemId == _eventItem.Id);

                // Filter by Campus
                List <int> campusIds = cblCampus.SelectedValuesAsInt;
                if (campusIds.Any())
                {
                    qry = qry
                          .Where(i =>
                                 !i.CampusId.HasValue ||
                                 campusIds.Contains(i.CampusId.Value));
                }

                SortProperty sortProperty = gCalendarItemOccurrenceList.SortProperty;

                // Sort and query db
                List <EventItemOccurrence> eventItemOccurrences = null;
                if (sortProperty != null)
                {
                    // If sorting on date, wait until after checking to see if date range was specified
                    if (sortProperty.Property == "Date")
                    {
                        eventItemOccurrences = qry.ToList();
                    }
                    else
                    {
                        eventItemOccurrences = qry.Sort(sortProperty).ToList();
                    }
                }
                else
                {
                    eventItemOccurrences = qry.ToList().OrderBy(a => a.NextStartDateTime).ToList();
                }

                // Contact filter
                if (!string.IsNullOrWhiteSpace(tbContact.Text))
                {
                    eventItemOccurrences = eventItemOccurrences
                                           .Where(i =>
                                                  i.ContactPersonAlias != null &&
                                                  i.ContactPersonAlias.Person != null &&
                                                  i.ContactPersonAlias.Person.FullName.Contains(tbContact.Text))
                                           .ToList();
                }

                // Now that items have been loaded and ordered from db, calculate the next start date for each item
                var eventItemOccurrencesWithDates = eventItemOccurrences
                                                    .Select(i => new EventItemOccurrenceWithDates
                {
                    EventItemOccurrence = i,
                    NextStartDateTime   = i.NextStartDateTime,
                })
                                                    .ToList();

                var dateCol = gCalendarItemOccurrenceList.Columns.OfType <BoundField>().Where(c => c.DataField == "Date").FirstOrDefault();

                // if a date range was specified, need to get all dates for items and filter based on any that have an occurrence withing the date range
                DateTime?lowerDateRange = drpDate.LowerValue;
                DateTime?upperDateRange = drpDate.UpperValue;
                if (lowerDateRange.HasValue || upperDateRange.HasValue)
                {
                    // If only one value was included, default the other to be a years difference
                    lowerDateRange = lowerDateRange ?? upperDateRange.Value.AddYears(-1).AddDays(1);
                    upperDateRange = upperDateRange ?? lowerDateRange.Value.AddYears(1).AddDays(-1);

                    // Get the start datetimes within the selected date range
                    eventItemOccurrencesWithDates.ForEach(i => i.StartDateTimes = i.EventItemOccurrence.GetStartTimes(lowerDateRange.Value, upperDateRange.Value.AddDays(1)));

                    // Filter out calendar items with no dates within range
                    eventItemOccurrencesWithDates = eventItemOccurrencesWithDates.Where(i => i.StartDateTimes.Any()).ToList();

                    // Update the Next Start Date to be the next date in range instead
                    dateCol.HeaderText = "Next Date In Range";
                    eventItemOccurrencesWithDates.ForEach(i => i.NextStartDateTime = i.StartDateTimes.Min());
                }
                else
                {
                    dateCol.HeaderText = "Next Start Date";
                }

                // Now sort on date if that is what was selected
                if (sortProperty != null && sortProperty.Property == "Date")
                {
                    if (sortProperty.Direction == SortDirection.Ascending)
                    {
                        eventItemOccurrencesWithDates = eventItemOccurrencesWithDates.OrderBy(a => a.NextStartDateTime).ToList();
                    }
                    else
                    {
                        eventItemOccurrencesWithDates = eventItemOccurrencesWithDates.OrderByDescending(a => a.NextStartDateTime).ToList();
                    }
                }

                gCalendarItemOccurrenceList.DataSource = eventItemOccurrencesWithDates
                                                         .Select(c => new
                {
                    c.EventItemOccurrence.Id,
                    c.EventItemOccurrence.Guid,
                    Campus   = c.EventItemOccurrence.Campus != null ? c.EventItemOccurrence.Campus.Name : "All Campuses",
                    Date     = c.NextStartDateTime.HasValue ? c.NextStartDateTime.Value.ToShortDateString() : "N/A",
                    Location = c.EventItemOccurrence.Location,
                    RegistrationInstanceId = c.EventItemOccurrence.Linkages.Any() ? c.EventItemOccurrence.Linkages.FirstOrDefault().RegistrationInstanceId : (int?)null,
                    RegistrationInstance   = c.EventItemOccurrence.Linkages.Any() ? c.EventItemOccurrence.Linkages.FirstOrDefault().RegistrationInstance : null,
                    GroupId      = c.EventItemOccurrence.Linkages.Any() ? c.EventItemOccurrence.Linkages.FirstOrDefault().GroupId : (int?)null,
                    Group        = c.EventItemOccurrence.Linkages.Any() ? c.EventItemOccurrence.Linkages.FirstOrDefault().Group : null,
                    ContentItems = FormatContentItems(c.EventItemOccurrence.ContentChannelItems.Select(i => i.ContentChannelItem).ToList()),
                    Contact      = c.EventItemOccurrence.ContactPersonAlias != null ? c.EventItemOccurrence.ContactPersonAlias.Person.FullName : "",
                    Phone        = c.EventItemOccurrence.ContactPhone,
                    Email        = c.EventItemOccurrence.ContactEmail,
                })
                                                         .ToList();
                gCalendarItemOccurrenceList.DataBind();
            }
            else
            {
                pnlEventCalendarCampusItems.Visible = false;
            }
        }
Exemple #37
0
        /// <summary>
        /// retorna a diferenca entre datas em dias (modo procedural)
        /// </summary>
        /// <param name="dataFinal">data Final</param>
        /// <param name="dataInicial">data Inicial</param>
        public static int diffDias(DateTime?dataFinal, DateTime?dataInicial)
        {
            var valorEmDias = ((dataFinal ?? DateTime.Now) - (dataInicial ?? DateTime.Now)).Days;

            return(valorEmDias);
        }
Exemple #38
0
        /// <summary>
        /// retorna a diferenca entre datas em dias (modo Fluent)
        /// </summary>
        /// <param name="dataFinal">data Final</param>
        /// <param name="dataInicial">data Inicial</param>
        public static int diferencaDias(this DateTime?dataFinal, DateTime?dataInicial)
        {
            var valorEmDias = diffDias(dataFinal, dataInicial);

            return(valorEmDias);
        }
 public DataTable StokMalMaliyetRaporu(string subeKodu, string stokKodu, DateTime? startDate, DateTime? finishDate) {
     return StokMalMaliyetRaporu(subeKodu,stokKodu,"",startDate,finishDate);
 }
    public DataTable StokMalMaliyetRaporu(string subeKodu, string stokKodu,string stokGrup, DateTime? startDate, DateTime? finishDate) {
        IDbConnection con = Session.Connection;
        IDbCommand cmd = con.CreateCommand();
        StringBuilder query = new StringBuilder();
        query.AppendFormat(@" SELECT st.STOK_KODU StokKodu,st.STOK_ADI StokIsmi,
sum(case when sh.GCKOD='G' then sh.GCMIK else 0 end) as AlışMiktar,
sum(case when sh.GCKOD='C' then sh.GCMIK else 0 end) as SatişMiktar,
sum(case when sh.GCKOD='G' then (sh.BIRIM_FIYAT*sh.GCMIK)
end)/
sum(case when (sh.GCMIK<>0 and sh.GCKOD='G') then sh.GCMIK  end ) as OrtalamaAlışFiyat
,
sum(case when sh.GCKOD='C' then (sh.BIRIM_FIYAT*sh.GCMIK)
end)/
sum(case when (sh.GCMIK<>0 and sh.GCKOD='C') then sh.GCMIK  end ) as OrtalamaSatışFiyat
FROM  StokHareket sh INNER JOIN
                      Stok st ON sh.STOK_KODU = st.STOK_KODU
where (st.SUBE_KODU='{0}' or st.SubelerdeOrtak=1)
 ", subeKodu);
        if (!string.IsNullOrEmpty(stokGrup)) {
            IStokCategoryManager mng=new StokCategoryManager();
            StokCategory sc=mng.GetById(stokGrup,false);
            StringBuilder qin = new StringBuilder();
            List<string> ary = mng.GetCategoryOfAllSubCategory(sc).Select(x => x.Id).ToList();
            ary.Insert(0,string.Format("{0}" ,stokGrup));
            foreach (var item in ary) {
                qin.AppendFormat("'{0}'",item); qin.Append(",");
            }
            qin.Remove(qin.Length - 1, 1);
            query.AppendFormat(" and (st.Grup1 in({0}) or st.Grup2 in({0}) or st.Grup3 in({0}) or st.Grup4 in({0}) )",qin);

        }
        if (startDate.HasValue && finishDate.HasValue)
            query.AppendFormat(" and {0} between '{1}' and '{2}'  ", SqlTypeHelper.GetDate("sh.TARIH"), startDate.Value.JustDate().ToString("yyyy-MM-dd"), finishDate.Value.JustDate().ToString("yyyy-MM-dd"));
        if (!string.IsNullOrEmpty(stokKodu))
            query.AppendFormat(" and st.STOK_KODU='{0}'", stokKodu);
        query.Append(" group by st.STOK_KODU,st.STOK_ADI");
        cmd.CommandText = query.ToString();
        IDataReader dread = null;
        DataTable dt = new DataTable();
        try {
            dread = cmd.ExecuteReader();
            dt.Columns.AddRange(
                                new DataColumn[]
                          {
                            new DataColumn("StokKodu",typeof(string)),
                             new DataColumn("StokIsmi",typeof(string)),
                            new DataColumn("AlisMiktar",typeof(double)),
                             new DataColumn("SatisMiktar",typeof(double)),
                              new DataColumn("KalanMiktar",typeof(double)),
                            new DataColumn("OrtalamaAlisFiyat",typeof(double)),
                           new DataColumn("OrtalamaSatisFiyat",typeof(double)),
                           new DataColumn("AlisTutar",typeof(double)),
                           new DataColumn("SatisTutar",typeof(double)),
                           new DataColumn("YuzdeKarOranı",typeof(double)),
                           new DataColumn("KalanMalinMaliyeti",typeof(double))
                          }
                               );
            while (dread.Read()) {
                DataRow dr = dt.NewRow();
                dr[0] = dread[0].ToStringOrEmpty();
                dr[1] = dread[1].ToStringOrEmpty();
                dr[2] = dread[2].ToStringOrEmpty("0");
                dr[3] = dread[3].ToStringOrEmpty("0");
                dr[4] = (double.Parse(dread[2].ToStringOrEmpty("0")) - double.Parse(dread[3].ToStringOrEmpty("0"))).ToString("F2");
                dr[5] =double.Parse( dread[4].ToStringOrEmpty("0")).ToString("F2");
                dr[6] =double.Parse(dread[5].ToStringOrEmpty("0")).ToString("F2");
                dr[7] =(double.Parse(dr[2].ToStringOrEmpty("0")) * double.Parse(dr[5].ToStringOrEmpty("0"))).ToString("F2");
                dr[8] = (double.Parse(dr[3].ToStringOrEmpty("0")) * double.Parse(dr[6].ToStringOrEmpty("0"))).ToString("F2");                
                double oa=double.Parse(dr[5].ToStringOrEmpty("0"));
                double os=double.Parse(dr[6].ToStringOrEmpty("0"));
                dr[9] = (((os-oa)/oa)*100).ToString("F2");
                dr[10] = (oa * double.Parse(dr[4].ToString())).ToStringOrEmpty("0");
                dt.Rows.Add(dr);
            }
        } catch (Exception exc) { throw exc; } finally {
            if (dread != null && !dread.IsClosed)
                dread.Close();
        }
        return dt;
    }
    public DataTable StokOrtalamaAlisSatisFiyatlariRaporu(string subeKodu, string GCKod, string stokKodu, DateTime? startDate, DateTime? finishDate) {
        IDbConnection con = Session.Connection;
        IDbCommand cmd = con.CreateCommand();
        StringBuilder query = new StringBuilder();
        query.AppendFormat(@" SELECT st.STOK_KODU StokKodu,st.STOK_ADI StokIsmi,Miktar=sum(sh.GCMIK),OrtalamaFiyat=(
sum(sh.BIRIM_FIYAT*sh.GCMIK)/sum(sh.GCMIK)),
ToplamFiyat=sum(sh.GCMIK)*(
sum(sh.BIRIM_FIYAT*sh.GCMIK)/sum(sh.GCMIK))
FROM  StokHareket sh INNER JOIN
      Stok st ON sh.STOK_KODU = st.STOK_KODU
where (st.SUBE_KODU={0} or st.SubelerdeOrtak=1) and sh.GCKOD='{1}'
group by st.STOK_KODU,st.STOK_ADI ", subeKodu, GCKod);
        if(startDate.HasValue && finishDate.HasValue)
            query.AppendFormat(" {0} between '{1}' and '{2}'  ", SqlTypeHelper.GetDate("sh.TARIH"), startDate.Value.JustDate().ToString("yyyy-MM-dd"), finishDate.Value.JustDate().ToString("yyyy-MM-dd"));
        if (!string.IsNullOrEmpty(stokKodu))
            query.AppendFormat(" and st.STOK_KODU='{0}'",stokKodu);
        cmd.CommandText = query.ToString();
        IDataReader dread = null;
        DataTable dt = new DataTable();
        try {
            dread = cmd.ExecuteReader();
            dt.Columns.AddRange(
                                new DataColumn[]
                          {
                            new DataColumn("StokKodu",typeof(string)),
                             new DataColumn("StokIsmi",typeof(string)),
                            new DataColumn("Miktar",typeof(double)),
                             new DataColumn("OrtalamaFiyat",typeof(double)),
                            new DataColumn("ToplamFiyat",typeof(double))
                          
                          }
                               );
            while (dread.Read()) {
                DataRow dr = dt.NewRow();
                dr[0] = dread[0].ToStringOrEmpty();
                dr[1] = dread[1].ToStringOrEmpty();
                dr[2] = dread[2].ToStringOrEmpty("0");
                dr[3] = dread[3].ToStringOrEmpty("0");
                dr[4] = dread[4].ToStringOrEmpty("0"); 
                dt.Rows.Add(dr);
            }
        } catch (Exception exc) { throw exc; } finally {
            if (dread != null && !dread.IsClosed)
                dread.Close();
        }
        return dt;
    }
 public double OrtalamaAlisFiyatinaGoreStokDegeri(string subeKodu, DateTime? beginDate, DateTime? endDate) {
     DataTable data = StokMalMaliyetRaporu(subeKodu, "", beginDate, endDate);
     double toplam = 0;
     for (int i=0;i<data.Rows.Count;i++) {
         var item = data.Rows[i];
         double oa = double.Parse(item["OrtalamaAlisFiyat"].ToStringOrEmpty("0"));
         double mik = double.Parse(item["KalanMiktar"].ToStringOrEmpty("0"));
         double deger = oa * mik;
         toplam += deger;
     }
     return toplam;
 }
 public List <WarehouseProductAmountDTO> GetWarehousesProductAmounts(int productId, IEnumerable <int> warehousesIds, DateTime?date = null)
 {
     return(GetWarehousesProductsAmounts(new[] { productId }, warehousesIds, date));
 }
        public List <WarehouseProductAmountDTO> GetWarehousesProductsAmounts(IEnumerable <int> productsIds, IEnumerable <int> warehousesIds, DateTime?date = null)
        {
            if (date == null)
            {
                date = DateTime.Now;
            }

            var list = new List <WarehouseProductAmountDTO>();

            var db     = GetDatabaseConnection() as Simple.Data.Database;
            var query  = BuildGetWarehouseAmountQuery(warehousesIds, productsIds);
            var result = db.ToRows(query, new { paramDate = date.Value }).ToList();

            result.ForEach((d) => list.Add(new WarehouseProductAmountDTO
            {
                ProductAmount = d.ProductAmount,
                ProductId     = d.ProductId,
                WarehouseId   = d.WarehouseId
            }));

            return(list);
        }
 public WarehouseProductAmountDTO GetWarehouseProductAmount(int productId, int warehouseId, DateTime?date = null)
 {
     return(GetWarehousesProductsAmounts(new[] { productId }, new[] { warehouseId }, date).FirstOrDefault());
 }
 public List <WarehouseProductAmountDTO> GetWarehouseProductsAmounts(IEnumerable <int> productsIds, int warehouseId, DateTime?date = null)
 {
     return(GetWarehousesProductsAmounts(productsIds, new[] { warehouseId }, date));
 }
Exemple #47
0
        private static void ProcessCsvLine(string strLine, PwDatabase pwStorage,
                                           SortedDictionary <string, PwGroup> dictGroups)
        {
            if (strLine == StrHeader)
            {
                return;                                  // Skip header
            }
            List <string> list = ImportUtil.SplitCsvLine(strLine, ",");

            Debug.Assert(list.Count == 13);
            if (list.Count != 13)
            {
                return;
            }

            string strType      = ParseCsvWord(list[0]);
            string strGroupName = ParseCsvWord(list[12]) + " - " + strType;

            SplashIdMapping mp = null;

            foreach (SplashIdMapping mpFind in SplashIdCsv402.SplashIdMappings)
            {
                if (mpFind.TypeName == strType)
                {
                    mp = mpFind;
                    break;
                }
            }

            PwIcon pwIcon = ((mp != null) ? mp.Icon : PwIcon.Key);

            PwGroup pg = null;

            if (dictGroups.ContainsKey(strGroupName))
            {
                pg = dictGroups[strGroupName];
            }
            else
            {
                PwIcon pwGroupIcon = ((pwIcon == PwIcon.Key) ?
                                      PwIcon.FolderOpen : pwIcon);

                pg = new PwGroup(true, true, strGroupName, pwGroupIcon);
                pwStorage.RootGroup.AddGroup(pg, true);
                dictGroups.Add(strGroupName, pg);
            }

            PwEntry pe = new PwEntry(true, true);

            pg.AddEntry(pe, true);

            pe.IconId = pwIcon;

            for (int iField = 0; iField < 9; ++iField)
            {
                string strData = ParseCsvWord(list[iField + 1]);
                if (strData.Length == 0)
                {
                    continue;
                }

                string strLookup = ((mp != null) ? mp.FieldNames[iField] :
                                    null);
                string strField = (strLookup ?? ("Field " + (iField + 1).ToString()));

                pe.Strings.Set(strField, new ProtectedString(false,
                                                             strData));
            }

            pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
                               pwStorage.MemoryProtection.ProtectNotes,
                               ParseCsvWord(list[11])));

            DateTime?dt = TimeUtil.ParseUSTextDate(ParseCsvWord(list[10]));

            if (dt.HasValue)
            {
                pe.LastAccessTime       = dt.Value;
                pe.LastModificationTime = dt.Value;
            }
        }
Exemple #48
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EdFiStaffLeaveEventCategoryDescriptor" /> class.
 /// </summary>
 /// <param name="Id">Id (required).</param>
 /// <param name="StaffLeaveEventCategoryDescriptorId">A unique identifier used as Primary Key, not derived from business logic, when acting as Foreign Key, references the parent table..</param>
 /// <param name="CodeValue">A code or abbreviation that is used to refer to the descriptor. (required).</param>
 /// <param name="Description">The description of the descriptor..</param>
 /// <param name="EffectiveBeginDate">The beginning date of the period when the descriptor is in effect. If omitted, the default is immediate effectiveness..</param>
 /// <param name="EffectiveEndDate">The end date of the period when the descriptor is in effect..</param>
 /// <param name="_Namespace">A globally unique namespace that identifies this descriptor set. Author is strongly encouraged to use the Universal Resource Identifier (http, ftp, file, etc.) for the source of the descriptor definition. Best practice is for this source to be the descriptor file itself, so that it can be machine-readable and be fetched in real-time, if necessary. (required).</param>
 /// <param name="PriorDescriptorId">A unique identifier used as Primary Key, not derived from business logic, when acting as Foreign Key, references the parent table..</param>
 /// <param name="ShortDescription">A shortened description for the descriptor. (required).</param>
 /// <param name="Etag">A unique system-generated value that identifies the version of the resource..</param>
 public EdFiStaffLeaveEventCategoryDescriptor(string Id = default(string), int? StaffLeaveEventCategoryDescriptorId = default(int?), string CodeValue = default(string), string Description = default(string), DateTime? EffectiveBeginDate = default(DateTime?), DateTime? EffectiveEndDate = default(DateTime?), string _Namespace = default(string), int? PriorDescriptorId = default(int?), string ShortDescription = default(string), string Etag = default(string))
 {
     // to ensure "Id" is required (not null)
     if (Id == null)
     {
         throw new InvalidDataException("Id is a required property for EdFiStaffLeaveEventCategoryDescriptor and cannot be null");
     }
     else
     {
         this.Id = Id;
     }
     // to ensure "CodeValue" is required (not null)
     if (CodeValue == null)
     {
         throw new InvalidDataException("CodeValue is a required property for EdFiStaffLeaveEventCategoryDescriptor and cannot be null");
     }
     else
     {
         this.CodeValue = CodeValue;
     }
     // to ensure "_Namespace" is required (not null)
     if (_Namespace == null)
     {
         throw new InvalidDataException("_Namespace is a required property for EdFiStaffLeaveEventCategoryDescriptor and cannot be null");
     }
     else
     {
         this._Namespace = _Namespace;
     }
     // to ensure "ShortDescription" is required (not null)
     if (ShortDescription == null)
     {
         throw new InvalidDataException("ShortDescription is a required property for EdFiStaffLeaveEventCategoryDescriptor and cannot be null");
     }
     else
     {
         this.ShortDescription = ShortDescription;
     }
     this.StaffLeaveEventCategoryDescriptorId = StaffLeaveEventCategoryDescriptorId;
     this.Description = Description;
     this.EffectiveBeginDate = EffectiveBeginDate;
     this.EffectiveEndDate = EffectiveEndDate;
     this.PriorDescriptorId = PriorDescriptorId;
     this.Etag = Etag;
 }
Exemple #49
0
 partial void OnCreatedDateChanging(DateTime?value);
Exemple #50
0
 partial void OnModifiedDateChanging(DateTime?value);
 /// <summary>
 /// Special handling for nullable value
 /// </summary>
 public void SetNullableDateTime(string key, DateTime?value)
 {
     Set <DateTime>(key, value ?? DateTime.MinValue);
 }
Exemple #52
0
        public async Task <Unit> Handle(ImportApprovalsRequest request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("Commencing approvals import.");

                // 1. Figure out extract start time.

                DateTime?extractStartTime = null;
                _logger.LogInformation($"Calculating Approvals changed date, initially set to null.");
                DateTime?latestApprovalsExtractTimestamp = await _approvalsExtractRepository.GetLatestExtractTimestamp();

                if (null != latestApprovalsExtractTimestamp && latestApprovalsExtractTimestamp.HasValue)
                {
                    extractStartTime = latestApprovalsExtractTimestamp.Value.AddSeconds(-await GetSettingAsInt(TOLERANCE_SETTING_NAME));
                    _logger.LogInformation($"Pulling Approvals changed since: {extractStartTime}");
                }

                // 2. Request the extract in batches.

                int batchSize = await GetSettingAsInt(BATCHSIZE_SETTING_NAME);

                int batchNumber = 0;
                int count       = 0;
                GetAllLearnersResponse learnersBatch = null;

                // 3. Reset Staging Table
                await _approvalsExtractRepository.ClearApprovalsExtractStaging();

                do
                {
                    batchNumber++;
                    learnersBatch = await _outerApiService.GetAllLearners(extractStartTime, batchNumber, batchSize);

                    if (null == learnersBatch || null == learnersBatch.Learners)
                    {
                        throw new Exception($"Failed to get learners batch: sinceTime={extractStartTime?.ToString("o", System.Globalization.CultureInfo.InvariantCulture)} batchNumber={batchNumber} batchSize={batchSize}");
                    }

                    // 4. Upsert Batch to ApprovalsExtract_Staging.
                    _logger.LogInformation($"Approvals batch import loop. Starting batch {batchNumber} of {learnersBatch.TotalNumberOfBatches}");

                    await UpsertApprovalsExtractToStaging(learnersBatch.Learners);

                    count += learnersBatch.Learners.Count;
                    _logger.LogInformation($"Approvals batch import loop. Batch Completed {batchNumber} of {learnersBatch.TotalNumberOfBatches}. Total Inserted: {count}");
                } while (batchNumber < learnersBatch.TotalNumberOfBatches);

                // 5. Run Populate ApprovalsExtract From Staging
                _logger.LogInformation($"Begin Populating Approvals Extract");
                await _approvalsExtractRepository.PopulateApprovalsExtract();

                _logger.LogInformation($"Finished Populating Approvals Extract");

                // 6. Run Populate Learner
                _logger.LogInformation($"Begin Running Populate Learner");
                var learnerCount = await _approvalsExtractRepository.PopulateLearner();

                _logger.LogInformation($"Finished Running Populate Learner");

                // 7. Update providers cache

                await _approvalsExtractRepository.InsertProvidersFromApprovalsExtract();

                _logger.LogInformation($"Approvals import completed successfully. {count} record(s) read from outer api, {learnerCount} records inserted to Learner table.");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Approvals import failed to complete successfully.");
                throw;
            }

            return(Unit.Value);
        }
Exemple #53
0
 /// <summary>
 /// Retrieve the log items for either a given tracked relay or for a client
 /// </summary>
 /// <param name="userKey">User Key of the user who initiates the call.</param>
 /// <param name="trackingId">ID of the tracked relay. If this value is omitted, all log items for the client will be returned</param>
 /// <param name="start">Filter using a start date</param>
 /// <param name="end">Filter using an end date</param>
 /// <param name="limit">Limit the number of resulting log items.</param>
 /// <param name="offset">Offset the beginning of resulting log items.</param>
 /// <param name="clientId">Client ID of the client in which the mailing is located.</param>
 /// <param name="cancellationToken">The cancellation token</param>
 /// <returns>An enumeration of <see cref="RelayLog">log items</see> matching the filter criteria</returns>
 public Task <RelayLog[]> GetSentLogsAsync(string userKey, long?trackingId = null, DateTime?start = null, DateTime?end = null, int?limit = 0, int?offset = 0, long?clientId = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(GetLogsAsync <RelayLog>(userKey, "sent", "sent_logs", trackingId, start, end, limit, offset, clientId, cancellationToken));
 }
        public IActionResult GetXlsDO(string no, string poEksNo, long supplierId, DateTime?dateFrom, DateTime?dateTo)
        {
            try
            {
                byte[]   xlsInBytes;
                int      offset   = Convert.ToInt32(Request.Headers["x-timezone-offset"]);
                DateTime DateFrom = dateFrom == null ? new DateTime(1970, 1, 1) : Convert.ToDateTime(dateFrom);
                DateTime DateTo   = dateTo == null ? DateTime.Now : Convert.ToDateTime(dateTo);

                var xls = facade.GenerateExcelDO(no, poEksNo, supplierId, dateFrom, dateTo, offset);

                string filename = String.Format("Surat Jalan - {0}.xlsx", DateTime.UtcNow.ToString("ddMMyyyy"));

                xlsInBytes = xls.ToArray();
                var file = File(xlsInBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename);
                return(file);
            }
            catch (Exception e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.INTERNAL_ERROR_STATUS_CODE, e.Message)
                    .Fail();
                return(StatusCode(General.INTERNAL_ERROR_STATUS_CODE, Result));
            }
        }
Exemple #55
0
        public virtual async Task SideBySideExecuteAsync(IAsyncDatabaseCommands asyncDatabaseCommands, DocumentConvention documentConvention, Etag minimumEtagBeforeReplace = null, DateTime?replaceTimeUtc = null, CancellationToken token = default(CancellationToken))
        {
            Conventions = documentConvention;
            var indexDefinition = CreateIndexDefinition();
            var serverDef       = await asyncDatabaseCommands.GetIndexAsync(IndexName, token).ConfigureAwait(false);

            if (serverDef != null)
            {
                if (CurrentOrLegacyIndexDefinitionEquals(documentConvention, serverDef, indexDefinition))
                {
                    return;
                }

                var replaceIndexName = "ReplacementOf/" + IndexName;
                await asyncDatabaseCommands.PutIndexAsync(replaceIndexName, indexDefinition, token).ConfigureAwait(false);

                await asyncDatabaseCommands
                .PutAsync(Constants.IndexReplacePrefix + replaceIndexName,
                          null,
                          RavenJObject.FromObject(new IndexReplaceDocument {
                    IndexToReplace = serverDef.Name, MinimumEtagBeforeReplace = minimumEtagBeforeReplace, ReplaceTimeUtc = replaceTimeUtc
                }),
                          new RavenJObject(),
                          token).ConfigureAwait(false);
            }
            else
            {
                // since index doesn't exist yet - create it in normal mode
                await asyncDatabaseCommands.PutIndexAsync(IndexName, indexDefinition, token).ConfigureAwait(false);
            }
        }
Exemple #56
0
 /// <summary>
 /// 新增调用
 /// </summary>
 public override void Create()
 {
     this.CreateDate = DateTime.Now;
 }
Exemple #57
0
 /// <summary>
 /// Executes the index creation against the specified document store in side-by-side mode.
 /// </summary>
 public Task SideBySideExecuteAsync(IDocumentStore store, Etag minimumEtagBeforeReplace = null, DateTime?replaceTimeUtc = null)
 {
     return(store.SideBySideExecuteIndexAsync(this, minimumEtagBeforeReplace, replaceTimeUtc));
 }
        public IActionResult GetReportDetail(string supplier, string category, DateTime?dateFrom, DateTime?dateTo)
        {
            int    offset = Convert.ToInt32(Request.Headers["x-timezone-offset"]);
            string accept = Request.Headers["Accept"];

            var data = facade.GetReportDetailAccuracyofArrival(supplier, category, dateFrom, dateTo, offset);

            return(Ok(new
            {
                apiVersion = ApiVersion,
                data = data.Item1,
                info = new { total = data.Item2 },
                message = General.OK_MESSAGE,
                statusCode = General.OK_STATUS_CODE
            }));
        }
Exemple #59
0
        /// <summary>
        /// Executes the index creation using in side-by-side mode.
        /// </summary>
        /// <param name="databaseCommands"></param>
        /// <param name="documentConvention"></param>
        public virtual void SideBySideExecute(IDatabaseCommands databaseCommands, DocumentConvention documentConvention, Etag minimumEtagBeforeReplace = null, DateTime?replaceTimeUtc = null)
        {
            Conventions = documentConvention;
            var indexDefinition = CreateIndexDefinition();
            var serverDef       = databaseCommands.GetIndex(IndexName);

            if (serverDef != null)
            {
                if (CurrentOrLegacyIndexDefinitionEquals(documentConvention, serverDef, indexDefinition))
                {
                    return;
                }

                var replaceIndexName = "ReplacementOf/" + IndexName;
                databaseCommands.PutIndex(replaceIndexName, indexDefinition);

                databaseCommands
                .Put(Constants.IndexReplacePrefix + replaceIndexName,
                     null,
                     RavenJObject.FromObject(new IndexReplaceDocument {
                    IndexToReplace = serverDef.Name, MinimumEtagBeforeReplace = minimumEtagBeforeReplace, ReplaceTimeUtc = replaceTimeUtc
                }),
                     new RavenJObject());
            }
            else
            {
                // since index doesn't exist yet - create it in normal mode
                databaseCommands.PutIndex(IndexName, indexDefinition);
            }
        }
 public static DateCFConstraint Date(DateTime?min = null, DateTime?max = null, string?message = null)
 => new DateCFConstraint(min: min, max: max, message: message);