//Initializes, attaches it to archive internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd) { _archive = archive; _originallyInArchive = true; _diskNumberStart = cd.DiskNumberStart; _versionToExtract = (ZipVersionNeededValues)cd.VersionNeededToExtract; _generalPurposeBitFlag = (BitFlagValues)cd.GeneralPurposeBitFlag; CompressionMethod = (CompressionMethodValues)cd.CompressionMethod; _lastModified = new DateTimeOffset(ZipHelper.DosTimeToDateTime(cd.LastModified)); _compressedSize = cd.CompressedSize; _uncompressedSize = cd.UncompressedSize; _offsetOfLocalHeader = cd.RelativeOffsetOfLocalHeader; /* we don't know this yet: should be _offsetOfLocalHeader + 30 + _storedEntryNameBytes.Length + extrafieldlength * but entryname/extra length could be different in LH */ _storedOffsetOfCompressedData = null; _crc32 = cd.Crc32; _compressedBytes = null; _storedUncompressedData = null; _currentlyOpenForWrite = false; _everOpenedForWrite = false; _outstandingWriteStream = null; FullName = DecodeEntryName(cd.Filename); _lhUnknownExtraFields = null; //the cd should have these as null if we aren't in Update mode _cdUnknownExtraFields = cd.ExtraFields; _fileComment = cd.FileComment; _compressionLevel = null; }
public Document( Int16 _TypeId, Int64 _Serial, Int32 _SignedUser, DateTime _Date, Boolean _Printed, String _DocumentShortName, String _DocumentFullName, String _MedexDataTable, String _DocumentBody, String _DocumentHeader, Boolean _SetDeleted ) { TypeId = _TypeId; Serial = _Serial; SignedUser = _SignedUser; Date = _Date; Printed = _Printed; DocumentShortName = _DocumentShortName; DocumentFullName = _DocumentFullName; MedexDataTable = _MedexDataTable; DocumentBody = _DocumentBody; DocumentHeader = _DocumentHeader; SetDeleted = _SetDeleted; }
/// <summary> /// Converts a <see cref="Int64"/> to little endian notation. /// </summary> /// <param name="input">The <see cref="Int64"/> to convert.</param> /// <returns>The converted <see cref="Int64"/>.</returns> public static Int64 LittleEndian(Int64 input) { if (BitConverter.IsLittleEndian) return input; return Swap(input); }
internal static IsolatedStorageSecurityState CreateStateToIncreaseQuotaForApplication(Int64 newQuota, Int64 usedSize) { IsolatedStorageSecurityState state = new IsolatedStorageSecurityState(); state.m_Options = IsolatedStorageSecurityOptions.IncreaseQuotaForApplication; state.m_Quota = newQuota; state.m_UsedSize = usedSize; return state; }
private static Boolean HexNumberToInt64(ref NumberBuffer number, ref Int64 value) { UInt64 passedValue = 0; Boolean returnValue = HexNumberToUInt64(ref number, ref passedValue); value = (Int64)passedValue; return returnValue; }
public override void Initialize() { _data = new byte[64]; _dataSize = 0; _totalLength = 0; _abcd = new ABCDStruct { A = 0x67452301, B = 0xefcdab89, C = 0x98badcfe, D = 0x10325476 }; }
public override void Write(Int64 val) { val = Utilities.SwapBytes(val); base.Write(val); if (AutoFlush) Flush(); }
public MessageAttemptInfo(Message message, Int64 sequenceNumber, int retryCount, object state) { this.message = message; this.sequenceNumber = sequenceNumber; this.retryCount = retryCount; this.state = state; }
private unsafe MemoryMappedView(SafeMemoryMappedViewHandle viewHandle, Int64 pointerOffset, Int64 size, MemoryMappedFileAccess access) { m_viewHandle = viewHandle; m_pointerOffset = pointerOffset; m_size = size; m_access = access; }
internal static IsolatedStorageSecurityState CreateStateToIncreaseQuotaForGroup(String group, Int64 newQuota, Int64 usedSize) { IsolatedStorageSecurityState state = new IsolatedStorageSecurityState(); state.m_Options = IsolatedStorageSecurityOptions.IncreaseQuotaForGroup; state.m_Group = group; state.m_Quota = newQuota; state.m_UsedSize = usedSize; return state; }
public static byte[] Int64(Int64 i, Endianness e = Endianness.Machine) { byte[] bytes = BitConverter.GetBytes(i); if (NeedsFlipping(e)) Array.Reverse(bytes); return bytes; }
// Returns true if merging the number will not increase the number of ranges past MaxSequenceRanges. public static bool CanMerge(Int64 sequenceNumber, SequenceRangeCollection ranges) { if (ranges.Count < ReliableMessagingConstants.MaxSequenceRanges) { return true; } ranges = ranges.MergeWith(sequenceNumber); return ranges.Count <= ReliableMessagingConstants.MaxSequenceRanges; }
public static bool UserExist(Int64 id) { String where = String.Format("id = {0}", id); DataRow userData = Db.Instance.dSet.users.FindByid(id); if (userData != null) { return true; } return false; }
public static void Write(this BinaryWriter writer, Int64 value, bool invertEndian = false) { if (invertEndian) { writer.WriteInvertedBytes(BitConverter.GetBytes(value)); } else { writer.Write(value); } }
public override void Initialize() { _data = new byte[64]; _dataSize = 0; _totalLength = 0; _abcd = new ABCDStruct(); //Intitial values as defined in RFC 1321 _abcd.A = 0x67452301; _abcd.B = 0xefcdab89; _abcd.C = 0x98badcfe; _abcd.D = 0x10325476; }
public void OnHandshake(IPeerWireClient peerWireClient, byte[] handshake) { BDict dict = (BDict)BencodingUtils.Decode(handshake); if (dict.ContainsKey("metadata_size")) { BInt size = (BInt)dict["metadata_size"]; _metadataSize = size; _pieceCount = (Int64)Math.Ceiling((double)_metadataSize / 16384); } RequestMetaData(peerWireClient); }
private static void TestList() { var random = new Random(DateTime.UtcNow.Millisecond); var inputItems = new Int64[itemsCount]; for (var index = 0; index < itemsCount; index++) { inputItems[index] = random.Next(); } var result = CollectionLoadTestHelper.RunAllAsync(inputItems, concurrentWritersCount).Result; PrintResults(result); }
public SequenceRange(Int64 lower, Int64 upper) { if (lower < 0) { throw Fx.AssertAndThrow("Argument lower cannot be negative."); } if (lower > upper) { throw Fx.AssertAndThrow("Argument upper cannot be less than argument lower."); } this.lower = lower; this.upper = upper; }
unsafe public UniqueId(byte[] guid, int offset) { if (guid == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("guid")); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative))); if (offset > guid.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, guid.Length))); if (guidLength > guid.Length - offset) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlArrayTooSmallInput, guidLength), "guid")); fixed (byte* pb = &guid[offset]) { this.idLow = UnsafeGetInt64(pb); this.idHigh = UnsafeGetInt64(&pb[8]); } }
//shouldn't ever read the byte at position endExtraField //assumes we are positioned at the beginning of an extra field subfield public static Boolean TryReadBlock(BinaryReader reader, Int64 endExtraField, out ZipGenericExtraField field) { field = new ZipGenericExtraField(); //not enough bytes to read tag + size if (endExtraField - reader.BaseStream.Position < 4) return false; field._tag = reader.ReadUInt16(); field._size = reader.ReadUInt16(); //not enough bytes to read the data if (endExtraField - reader.BaseStream.Position < field._size) return false; field._data = reader.ReadBytes(field._size); return true; }
internal sealed override void Invoke( FrameworkElement fe, FrameworkContentElement fce, Style targetStyle, FrameworkTemplate frameworkTemplate, Int64 layer ) { Debug.Assert( fe != null || fce != null, "Caller of internal function failed to verify that we have a FE or FCE - we have neither." ); Debug.Assert( targetStyle != null || frameworkTemplate != null, "This function expects to be called when the associated action is inside a Style/Template. But it was not given a reference to anything." ); INameScope nameScope = null; if( targetStyle != null ) { nameScope = targetStyle; } else { Debug.Assert( frameworkTemplate != null ); nameScope = frameworkTemplate; } Invoke( fe, fce, GetStoryboard( fe, fce, nameScope ) ); }
public void OnExtendedMessage(IPeerWireClient peerWireClient, byte[] bytes) { Int32 startAt = 0; BencodingUtils.Decode(bytes, ref startAt); _piecesReceived += 1; if (_pieceCount >= _piecesReceived) { _metadataBuffer = _metadataBuffer.Concat(bytes.Skip(startAt)).ToArray(); } if (_pieceCount == _piecesReceived) { BDict metadata = (BDict)BencodingUtils.Decode(_metadataBuffer); if (MetaDataReceived != null) { MetaDataReceived(peerWireClient, this, metadata); } } }
protected internal StreamOperationAsyncResult(IAsyncInfo asyncStreamOperation, AsyncCallback userCompletionCallback, Object userAsyncStateInfo, bool processCompletedOperationInCallback) { if (asyncStreamOperation == null) throw new ArgumentNullException("asyncReadOperation"); _userCompletionCallback = userCompletionCallback; _userAsyncStateInfo = userAsyncStateInfo; _asyncStreamOperation = asyncStreamOperation; _completed = false; _callbackInvoked = false; _bytesCompleted = 0; _errorInfo = null; _processCompletedOperationInCallback = processCompletedOperationInCallback; }
internal Byte[] Com_PrepareFrameGPS(double yawx, double pitchx, double rollx, double lonx, double latx, int statex) { Int16 yaw = (Int16)(yawx * 10.0); Int16 pitch = (Int16)(pitchx * 10.0); Int16 roll = (Int16)(rollx * 10.0); Int64 lon = (Int64)(lonx * 10000000.0); Int64 lat = (Int64)(latx * 10000000.0); int state = 0; if (statex == 0) { state = 0; } if (statex == 1) { state = 245; } if (statex == 2) { state = 246; } if (statex == 3) { state = 247; } if (statex == 4) { state = 248; } if (statex == 5) { state = 249; } if (statex == 6) { state = 250; } if (statex == 7) { state = 251; } Byte[] buf = new Byte[21]; buf[0] = 155; buf[1] = 9; buf[2] = (Byte)(yaw >> 8); buf[3] = (Byte)yaw; buf[4] = (Byte)(pitch >> 8); buf[5] = (Byte)pitch; buf[6] = (Byte)(roll >> 8); buf[7] = (Byte)roll; buf[8] = (Byte)((UInt64)lon >> 32); buf[9] = (Byte)((UInt64)lon >> 24); buf[10] = (Byte)((UInt64)lon >> 16); buf[11] = (Byte)((UInt64)lon >> 8); buf[12] = (Byte)(UInt64)lon; buf[13] = (Byte)(lat >> 32); buf[14] = (Byte)(lat >> 24); buf[15] = (Byte)(lat >> 16); buf[16] = (Byte)(lat >> 8); buf[17] = (Byte)lat; buf[18] = (Byte)state; Int16 crc = (Int16)(crc16(buf, 19)); buf[19] = (Byte)(crc >> 8); buf[20] = (Byte)crc; return(buf); }
/// <summary> /// Determines the 'Primary' and/or 'Within Organisation' setting(s) for a Partner. /// </summary> /// <param name="APartnerKey">PartnerKey of the Partner.</param> /// <param name="AOverallContSettingKind">Specify the kind of Overall Contact Setting(s) that you want returned. /// Combine multiple ones with the binary OR operator ( | ).</param> /// <param name="APartnerAttributeDT">Contains the Partners' p_partner_attribute records. The ones that are /// 'Contact Details' have 'true' in the Column /// <see cref="Calculations.PARTNERATTRIBUTE_PARTNERCONTACTDETAIL_COLUMN"/>!</param> /// <returns>An instance of <see cref="Calculations.TPartnersOverallContactSettings"/> that holds the /// <see cref="Calculations.TPartnersOverallContactSettings"/> for the Partner. However, it returns null /// in case the Partner hasn't got any p_partner_attribute records, or when the Partner has no p_partner_attribute /// records that constitute Contact Detail records, or when the Partner has got only one p_partner_attribute record /// but this records' Current flag is false. It also returns null if no record was found that met what was asked for /// with <paramref name="AOverallContSettingKind"/>!</returns> public static Calculations.TPartnersOverallContactSettings GetPartnersOverallCS(Int64 APartnerKey, Calculations.TOverallContSettingKind AOverallContSettingKind, out PPartnerAttributeTable APartnerAttributeDT) { Calculations.TPartnersOverallContactSettings PrimaryContactAttributes = null; TDBTransaction ReadTransaction = null; PPartnerAttributeTable PartnerAttributeDT = null; DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref ReadTransaction, delegate { // Load all PPartnerAttribute records of the Partner and put them into a DataTable PartnerAttributeDT = PPartnerAttributeAccess.LoadViaPPartner(APartnerKey, ReadTransaction); if (PartnerAttributeDT.Rows.Count > 0) { Calculations.DeterminePartnerContactDetailAttributes(PartnerAttributeDT); PrimaryContactAttributes = Calculations.DeterminePrimaryOrWithinOrgSettingsForPartner( PartnerAttributeDT, AOverallContSettingKind); if (((AOverallContSettingKind & Calculations.TOverallContSettingKind.ocskPrimaryContactMethod) == Calculations.TOverallContSettingKind.ocskPrimaryContactMethod) || ((AOverallContSettingKind & Calculations.TOverallContSettingKind.ocskSecondaryEmailAddress) == Calculations.TOverallContSettingKind.ocskSecondaryEmailAddress)) { if (PrimaryContactAttributes == null) { PrimaryContactAttributes = new Calculations.TPartnersOverallContactSettings(); } Calculations.DeterminePartnerSystemCategorySettings( PartnerAttributeDT, ref PrimaryContactAttributes, AOverallContSettingKind); } } }); APartnerAttributeDT = PartnerAttributeDT; return(PrimaryContactAttributes); }
eldbus_message_arguments_append(IntPtr msg, string signature, Int64 value);
private void ValidateResult(Vector128 <Double> firstOp, Int64 result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As <Double, byte>(ref inArray[0]), firstOp); ValidateResult(inArray, result, method); }
private HREmployeeLoanApplicationEntity BuildHREmployeeLoanApplicationEntity() { HREmployeeLoanApplicationEntity hREmployeeLoanApplicationEntity = CurrentHREmployeeLoanApplicationEntity; hREmployeeLoanApplicationEntity.EmployeeID = OverviewEmployeeID; if (ddlLoanCategoryID.Items.Count > 0) { if (ddlLoanCategoryID.SelectedValue == "0") { } else { hREmployeeLoanApplicationEntity.LoanCategoryID = Int64.Parse(ddlLoanCategoryID.SelectedValue); } } if (!txtAppliedLoanAmount.Text.Trim().IsNullOrEmpty()) { hREmployeeLoanApplicationEntity.AppliedLoanAmount = Decimal.Parse(txtAppliedLoanAmount.Text.Trim()); } if (ddlCurrencyID.Items.Count > 0) { if (ddlCurrencyID.SelectedValue == "0") { } else { hREmployeeLoanApplicationEntity.CurrencyID = Int64.Parse(ddlCurrencyID.SelectedValue); } } if (txtLoanPaymentStartDate.Text.Trim().IsNotNullOrEmpty()) { hREmployeeLoanApplicationEntity.LoanPaymentStartDate = MiscUtil.ParseToDateTime(txtLoanPaymentStartDate.Text); } else { hREmployeeLoanApplicationEntity.LoanPaymentStartDate = null; } if (txtLoanPaymentEndDate.Text.Trim().IsNotNullOrEmpty()) { hREmployeeLoanApplicationEntity.LoanPaymentEndDate = MiscUtil.ParseToDateTime(txtLoanPaymentEndDate.Text); } else { hREmployeeLoanApplicationEntity.LoanPaymentEndDate = null; } if (!txtNumberOfInstallment.Text.Trim().IsNullOrEmpty()) { hREmployeeLoanApplicationEntity.NumberOfInstallment = Decimal.Parse(txtNumberOfInstallment.Text.Trim()); } else { hREmployeeLoanApplicationEntity.NumberOfInstallment = null; } hREmployeeLoanApplicationEntity.Description = txtDescription.Text.Trim(); if (ddlEmployeeLoanApprovalStatusID.Items.Count > 0) { if (ddlEmployeeLoanApprovalStatusID.SelectedValue == "0") { } else { hREmployeeLoanApplicationEntity.EmployeeLoanApprovalStatusID = Int64.Parse(ddlEmployeeLoanApprovalStatusID.SelectedValue); } } hREmployeeLoanApplicationEntity.Remarks = txtRemarks.Text.Trim(); return(hREmployeeLoanApplicationEntity); }
private void ValidateResult(void *firstOp, Int64 result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As <Double, byte>(ref inArray[0]), ref Unsafe.AsRef <byte>(firstOp), (uint)Unsafe.SizeOf <Vector128 <Double> >()); ValidateResult(inArray, result, method); }
public Int64 Insert(AccessUserDetails Details) { try { Int64 iID = 0; MySqlCommand cmd = new MySqlCommand(); cmd.CommandType = System.Data.CommandType.Text; string SQLUser = "******"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("UserName", Details.UserName); cmd.CommandText = SQLUser; string strDataTableName = "tbl" + this.GetType().FullName.Split(new Char[] { '.' })[this.GetType().FullName.Split(new Char[] { '.' }).Length - 1]; System.Data.DataTable dt = new System.Data.DataTable(strDataTableName); base.MySqlDataAdapterFill(cmd, dt); if (dt.Rows.Count == 0) { SQLUser = "******"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("UserName", Details.UserName); cmd.Parameters.AddWithValue("Password", Details.Password); Details.DateCreated = DateTime.Now; cmd.Parameters.AddWithValue("DateCreated", Details.DateCreated.ToString("yyyy-MM-dd HH:mm:ss")); cmd.Parameters.AddWithValue("CreatedOn", Details.DateCreated.ToString("yyyy-MM-dd HH:mm:ss")); cmd.Parameters.AddWithValue("LastModified", Details.DateCreated.ToString("yyyy-MM-dd HH:mm:ss")); cmd.CommandText = SQLUser; base.ExecuteNonQuery(cmd); iID = Int64.Parse(base.getLAST_INSERT_ID(this)); } else { iID = Int64.Parse(dt.Rows[0]["UID"].ToString()); SQLUser = "******"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("UID", iID); cmd.Parameters.AddWithValue("Password", Details.Password); cmd.CommandText = SQLUser; base.ExecuteNonQuery(cmd); } Details.UID = iID; SQLUser = "******"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("UID", iID); cmd.CommandText = SQLUser; base.MySqlDataAdapterFill(cmd, dt); if (dt.Rows.Count != 0) { SQLUser = "******" + "Name = @Name, "+ "Address1 = @Address1, "+ "Address2 = @Address2, "+ "City = @City, "+ "State = @State, "+ "CountryID = @CountryID, "+ "OfficePhone = @OfficePhone, "+ "DirectPhone = @DirectPhone, "+ "HomePhone = @HomePhone, "+ "FaxPhone = @FaxPhone, "+ "MobilePhone = @MobilePhone, "+ "EmailAddress = @EmailAddress, "+ "GroupID = @GroupID, "+ "PageSize = @PageSize "+ "WHERE UID = @UID;"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("Name", Details.Name); cmd.Parameters.AddWithValue("Address1", Details.Address1); cmd.Parameters.AddWithValue("Address2", Details.Address2); cmd.Parameters.AddWithValue("City", Details.City); cmd.Parameters.AddWithValue("State", Details.State); cmd.Parameters.AddWithValue("CountryID", Details.CountryID); cmd.Parameters.AddWithValue("OfficePhone", Details.OfficePhone); cmd.Parameters.AddWithValue("DirectPhone", Details.DirectPhone); cmd.Parameters.AddWithValue("HomePhone", Details.HomePhone); cmd.Parameters.AddWithValue("FaxPhone", Details.FaxPhone); cmd.Parameters.AddWithValue("MobilePhone", Details.MobilePhone); cmd.Parameters.AddWithValue("EmailAddress", Details.EmailAddress); cmd.Parameters.AddWithValue("GroupID", Details.GroupID); if (Details.PageSize == 0) { Details.PageSize = 10; } cmd.Parameters.AddWithValue("PageSize", Details.PageSize); cmd.Parameters.AddWithValue("UID", Details.UID); cmd.CommandText = SQLUser; base.ExecuteNonQuery(cmd); } else { cmd = new MySqlCommand(); cmd.CommandType = System.Data.CommandType.Text; SQLUser = "******" + "UID," + "Name," + "Address1," + "Address2," + "City," + "State," + "CountryID," + "OfficePhone," + "DirectPhone," + "HomePhone," + "FaxPhone," + "MobilePhone," + "EmailAddress," + "GroupID, CreatedOn, LastModified) VALUES ( " + "@UID," + "@Name," + "@Address1," + "@Address2," + "@City," + "@State," + "@CountryID," + "@OfficePhone," + "@DirectPhone," + "@HomePhone," + "@FaxPhone," + "@MobilePhone," + "@EmailAddress," + "@GroupID, @CreatedOn, @LastModified);"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("UID", iID); cmd.Parameters.AddWithValue("Name", Details.Name); cmd.Parameters.AddWithValue("Address1", Details.Address1); cmd.Parameters.AddWithValue("Address2", Details.Address2); cmd.Parameters.AddWithValue("City", Details.City); cmd.Parameters.AddWithValue("State", Details.State); cmd.Parameters.AddWithValue("CountryID", Details.CountryID); cmd.Parameters.AddWithValue("OfficePhone", Details.OfficePhone); cmd.Parameters.AddWithValue("DirectPhone", Details.DirectPhone); cmd.Parameters.AddWithValue("HomePhone", Details.HomePhone); cmd.Parameters.AddWithValue("FaxPhone", Details.FaxPhone); cmd.Parameters.AddWithValue("MobilePhone", Details.MobilePhone); cmd.Parameters.AddWithValue("EmailAddress", Details.EmailAddress); cmd.Parameters.AddWithValue("GroupID", Details.GroupID); cmd.Parameters.AddWithValue("CreatedOn", Details.DateCreated.ToString("yyyy-MM-dd HH:mm:ss")); cmd.Parameters.AddWithValue("LastModified", Details.DateCreated.ToString("yyyy-MM-dd HH:mm:ss")); cmd.CommandText = SQLUser; base.ExecuteNonQuery(cmd); } InsertAccessRights(iID, Details.GroupID); return(iID); } catch (Exception ex) { throw base.ThrowException(ex); } }
public static Int64 LeastCommonMultiple(Int64 num1, Int64 num2) { return((num1 * num2) / GreatestCommonDivisor(num1, num2)); }
private void OpenSqlFileStream ( string path, byte[] transactionContext, System.IO.FileAccess access, System.IO.FileOptions options, Int64 allocationSize ) { //----------------------------------------------------------------- // precondition validation // these should be checked by any caller of this method // ensure we have validated and normalized the path before Debug.Assert(path != null); Debug.Assert(transactionContext != null); if (access != FileAccess.Read && access != FileAccess.Write && access != FileAccess.ReadWrite) { throw ADP.ArgumentOutOfRange("access"); } // FileOptions is a set of flags, so AND the given value against the set of values we do not support if ((options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.SequentialScan)) != 0) { throw ADP.ArgumentOutOfRange("options"); } //----------------------------------------------------------------- // normalize the provided path // * compress path to remove any occurrences of '.' or '..' // * trim whitespace from the beginning and end of the path // * ensure that the path starts with '\\' // * ensure that the path does not start with '\\.\' // * ensure that the path is not longer than Int16.MaxValue path = GetFullPathInternal(path); // ensure the running code has permission to read/write the file DemandAccessPermission(path, access); FileFullEaInformation eaBuffer = null; SecurityQualityOfService qos = null; UnicodeString objectName = null; Microsoft.Win32.SafeHandles.SafeFileHandle hFile = null; int nDesiredAccess = UnsafeNativeMethods.FILE_READ_ATTRIBUTES | UnsafeNativeMethods.SYNCHRONIZE; UInt32 dwCreateOptions = 0; UInt32 dwCreateDisposition = 0; System.IO.FileShare shareAccess = System.IO.FileShare.None; switch (access) { case System.IO.FileAccess.Read: nDesiredAccess |= UnsafeNativeMethods.FILE_READ_DATA; shareAccess = System.IO.FileShare.Delete | System.IO.FileShare.ReadWrite; dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OPEN; break; case System.IO.FileAccess.Write: nDesiredAccess |= UnsafeNativeMethods.FILE_WRITE_DATA; shareAccess = System.IO.FileShare.Delete | System.IO.FileShare.Read; dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OVERWRITE; break; case System.IO.FileAccess.ReadWrite: default: // we validate the value of 'access' parameter in the beginning of this method Debug.Assert(access == System.IO.FileAccess.ReadWrite); nDesiredAccess |= UnsafeNativeMethods.FILE_READ_DATA | UnsafeNativeMethods.FILE_WRITE_DATA; shareAccess = System.IO.FileShare.Delete | System.IO.FileShare.Read; dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OVERWRITE; break; } if ((options & System.IO.FileOptions.WriteThrough) != 0) { dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_WRITE_THROUGH; } if ((options & System.IO.FileOptions.Asynchronous) == 0) { dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_SYNCHRONOUS_IO_NONALERT; } if ((options & System.IO.FileOptions.SequentialScan) != 0) { dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_SEQUENTIAL_ONLY; } if ((options & System.IO.FileOptions.RandomAccess) != 0) { dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_RANDOM_ACCESS; } try { eaBuffer = new FileFullEaInformation(transactionContext); qos = new SecurityQualityOfService(UnsafeNativeMethods.SecurityImpersonationLevel.SecurityAnonymous, false, false); // NOTE: the Name property is intended to reveal the publicly available moniker for the // FILESTREAM attributed column data. We will not surface the internal processing that // takes place to create the mappedPath. string mappedPath = InitializeNtPath(path); objectName = new UnicodeString(mappedPath); UnsafeNativeMethods.OBJECT_ATTRIBUTES oa; oa.length = Marshal.SizeOf(typeof(UnsafeNativeMethods.OBJECT_ATTRIBUTES)); oa.rootDirectory = IntPtr.Zero; oa.attributes = (int)UnsafeNativeMethods.Attributes.CaseInsensitive; oa.securityDescriptor = IntPtr.Zero; oa.securityQualityOfService = qos; oa.objectName = objectName; UnsafeNativeMethods.IO_STATUS_BLOCK ioStatusBlock; uint oldMode; uint retval = 0; UnsafeNativeMethods.SetErrorModeWrapper(UnsafeNativeMethods.SEM_FAILCRITICALERRORS, out oldMode); try { SqlClientEventSource.Log.TryAdvancedTraceEvent("<sc.SqlFileStream.OpenSqlFileStream|ADV> {0}, desiredAccess=0x{1}, allocationSize={2}, " + "fileAttributes=0x{3}, shareAccess=0x{4}, dwCreateDisposition=0x{5}, createOptions=0x{ dwCreateOptions}", ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)shareAccess, dwCreateDisposition); retval = UnsafeNativeMethods.NtCreateFile(out hFile, nDesiredAccess, ref oa, out ioStatusBlock, ref allocationSize, 0, shareAccess, dwCreateDisposition, dwCreateOptions, eaBuffer, (uint)eaBuffer.Length); } finally { UnsafeNativeMethods.SetErrorModeWrapper(oldMode, out oldMode); } switch (retval) { case 0: break; case UnsafeNativeMethods.STATUS_SHARING_VIOLATION: throw ADP.InvalidOperation(StringsHelper.GetString(StringsHelper.SqlFileStream_FileAlreadyInTransaction)); case UnsafeNativeMethods.STATUS_INVALID_PARAMETER: throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_InvalidParameter)); case UnsafeNativeMethods.STATUS_OBJECT_NAME_NOT_FOUND: { System.IO.DirectoryNotFoundException e = new System.IO.DirectoryNotFoundException(); ADP.TraceExceptionAsReturnValue(e); throw e; } default: { uint error = UnsafeNativeMethods.RtlNtStatusToDosError(retval); if (error == UnsafeNativeMethods.ERROR_MR_MID_NOT_FOUND) { // status code could not be mapped to a Win32 error code error = retval; } System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(unchecked ((int)error)); ADP.TraceExceptionAsReturnValue(e); throw e; } } if (hFile.IsInvalid) { System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(UnsafeNativeMethods.ERROR_INVALID_HANDLE); ADP.TraceExceptionAsReturnValue(e); throw e; } UnsafeNativeMethods.FileType fileType = UnsafeNativeMethods.GetFileType(hFile); if (fileType != UnsafeNativeMethods.FileType.Disk) { hFile.Dispose(); throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_PathNotValidDiskResource)); } // if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan // through current data and then append new data to the end, so we need to tell SQL Server to preserve // the existing file contents. if (access == System.IO.FileAccess.ReadWrite) { uint ioControlCode = UnsafeNativeMethods.CTL_CODE(UnsafeNativeMethods.FILE_DEVICE_FILE_SYSTEM, IoControlCodeFunctionCode, (byte)UnsafeNativeMethods.Method.METHOD_BUFFERED, (byte)UnsafeNativeMethods.Access.FILE_ANY_ACCESS); uint cbBytesReturned = 0; if (!UnsafeNativeMethods.DeviceIoControl(hFile, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out cbBytesReturned, IntPtr.Zero)) { System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); ADP.TraceExceptionAsReturnValue(e); throw e; } } // now that we've successfully opened a handle on the path and verified that it is a file, // use the SafeFileHandle to initialize our internal System.IO.FileStream instance // NOTE: need to assert UnmanagedCode permissions for this constructor. This is relatively benign // in that we've done much the same validation as in the FileStream(string path, ...) ctor case // most notably, validating that the handle type corresponds to an on-disk file. bool bRevertAssert = false; try { SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); sp.Assert(); bRevertAssert = true; System.Diagnostics.Debug.Assert(m_fs == null); m_fs = new System.IO.FileStream(hFile, access, DefaultBufferSize, ((options & System.IO.FileOptions.Asynchronous) != 0)); } finally { if (bRevertAssert) { SecurityPermission.RevertAssert(); } } } catch { if (hFile != null && !hFile.IsInvalid) { hFile.Dispose(); } throw; } finally { if (eaBuffer != null) { eaBuffer.Dispose(); eaBuffer = null; } if (qos != null) { qos.Dispose(); qos = null; } if (objectName != null) { objectName.Dispose(); objectName = null; } } }
/// <summary> /// return a list of all applicants for a given event, /// but if AConferenceOrganisingOffice is false, /// consider only the registration office that the user has permissions for, ie. Module REG-00xx0000000 /// </summary> /// <param name="AMainDS"></param> /// <param name="AEventPartnerKey">The ConferenceKey</param> /// <param name="AEventCode">The OutreachPrefix</param> /// <param name="AApplicationStatus"></param> /// <param name="ARegistrationOffice">if -1, then show all offices that the user has permission for</param> /// <param name="AConferenceOrganisingOffice">if true, all offices are considered</param> /// <param name="ARole"></param> /// <param name="AClearJSONData"></param> /// <returns></returns> public static bool GetApplications( ref ConferenceApplicationTDS AMainDS, Int64 AEventPartnerKey, string AEventCode, string AApplicationStatus, Int64 ARegistrationOffice, bool AConferenceOrganisingOffice, string ARole, bool AClearJSONData) { Boolean NewTransaction; TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction( IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, out NewTransaction); try { // load all attendees of this conference. // only load once: GetApplications might be called for several application stati if (AMainDS.PcAttendee.Rows.Count == 0) { PcAttendeeRow templateAttendeeRow = AMainDS.PcAttendee.NewRowTyped(false); templateAttendeeRow.ConferenceKey = AEventPartnerKey; PcAttendeeAccess.LoadUsingTemplate(AMainDS, templateAttendeeRow, Transaction); AMainDS.PcAttendee.DefaultView.Sort = PcAttendeeTable.GetPartnerKeyDBName(); } if (AConferenceOrganisingOffice && (ARegistrationOffice == -1)) { // avoid duplicates, who are registered by one office, but charged to another office GetApplications(ref AMainDS, AEventCode, -1, AApplicationStatus, ARole, AClearJSONData, Transaction); } else { List <Int64> AllowedRegistrationOffices = GetRegistrationOfficeKeysOfUser(Transaction); foreach (Int64 RegistrationOffice in AllowedRegistrationOffices) { if ((ARegistrationOffice == RegistrationOffice) || (ARegistrationOffice == -1)) { GetApplications(ref AMainDS, AEventCode, RegistrationOffice, AApplicationStatus, ARole, AClearJSONData, Transaction); } } } // required for DefaultView.Find AMainDS.PmShortTermApplication.DefaultView.Sort = PmShortTermApplicationTable.GetStConfirmedOptionDBName() + "," + PmShortTermApplicationTable.GetPartnerKeyDBName(); AMainDS.PmGeneralApplication.DefaultView.Sort = PmGeneralApplicationTable.GetPartnerKeyDBName() + "," + PmGeneralApplicationTable.GetApplicationKeyDBName() + "," + PmGeneralApplicationTable.GetRegistrationOfficeDBName(); AMainDS.PDataLabelValuePartner.DefaultView.Sort = PDataLabelValuePartnerTable.GetDataLabelKeyDBName() + "," + PDataLabelValuePartnerTable.GetPartnerKeyDBName(); AMainDS.PDataLabel.DefaultView.Sort = PDataLabelTable.GetTextDBName(); } finally { DBAccess.GDBAccessObj.RollbackTransaction(); } if (AMainDS.HasChanges()) { AMainDS.EnforceConstraints = false; AMainDS.AcceptChanges(); } return(true); }
internal static PNObjectApiEventResult GetObject(List <object> listObject) { PNObjectApiEventResult result = null; Dictionary <string, object> objectEventDicObj = JsonDataParseInternalUtil.ConvertToDictionaryObject(listObject[0]); if (objectEventDicObj != null) { if (result == null) { result = new PNObjectApiEventResult(); } if (objectEventDicObj.ContainsKey("event") && objectEventDicObj["event"] != null) { result.Event = objectEventDicObj["event"].ToString(); } if (listObject.Count > 2) { long objectApiEventTimeStamp; if (Int64.TryParse(listObject[2].ToString(), out objectApiEventTimeStamp)) { result.Timestamp = objectApiEventTimeStamp; } } if (objectEventDicObj.ContainsKey("type") && objectEventDicObj["type"] != null) { result.Type = objectEventDicObj["type"].ToString(); } if (objectEventDicObj.ContainsKey("data") && objectEventDicObj["data"] != null) { Dictionary <string, object> dataDic = objectEventDicObj["data"] as Dictionary <string, object>; if (dataDic != null) { if (result.Type.ToLowerInvariant() == "user" && dataDic.ContainsKey("id")) { result.UserId = dataDic["id"] != null ? dataDic["id"].ToString() : null; result.User = new PNUserResult { Id = dataDic["id"] != null ? dataDic["id"].ToString() : null, Name = (dataDic.ContainsKey("name") && dataDic["name"] != null) ? dataDic["name"].ToString() : null, ExternalId = (dataDic.ContainsKey("externalId") && dataDic["externalId"] != null) ? dataDic["externalId"].ToString() : null, ProfileUrl = (dataDic.ContainsKey("profileUrl") && dataDic["profileUrl"] != null) ? dataDic["profileUrl"].ToString() : null, Email = (dataDic.ContainsKey("email") && dataDic["email"] != null) ? dataDic["email"].ToString() : null, Custom = (dataDic.ContainsKey("custom") && dataDic["custom"] != null) ? JsonDataParseInternalUtil.ConvertToDictionaryObject(dataDic["custom"]) : null, Created = (dataDic.ContainsKey("created") && dataDic["created"] != null) ? dataDic["created"].ToString() : null, Updated = (dataDic.ContainsKey("updated") && dataDic["updated"] != null) ? dataDic["updated"].ToString() : null }; } else if (result.Type.ToLowerInvariant() == "space" && dataDic.ContainsKey("id")) { result.SpaceId = dataDic["id"] != null ? dataDic["id"].ToString() : null; result.Space = new PNSpaceResult { Id = dataDic["id"] != null ? dataDic["id"].ToString() : null, Name = (dataDic.ContainsKey("name") && dataDic["name"] != null) ? dataDic["name"].ToString() : null, Description = (dataDic.ContainsKey("description") && dataDic["description"] != null) ? dataDic["description"].ToString() : null, Custom = (dataDic.ContainsKey("custom") && dataDic["custom"] != null) ? JsonDataParseInternalUtil.ConvertToDictionaryObject(dataDic["custom"]) : null, Created = (dataDic.ContainsKey("created") && dataDic["created"] != null) ? dataDic["created"].ToString() : null, Updated = (dataDic.ContainsKey("updated") && dataDic["updated"] != null) ? dataDic["updated"].ToString() : null }; } else if (result.Type.ToLowerInvariant() == "membership" && dataDic.ContainsKey("userId") && dataDic.ContainsKey("spaceId")) { result.UserId = dataDic["userId"] != null ? dataDic["userId"].ToString() : null; result.SpaceId = dataDic["spaceId"] != null ? dataDic["spaceId"].ToString() : null; } } } result.Channel = (listObject.Count == 6) ? listObject[5].ToString() : listObject[4].ToString(); } return(result); }
static void ParseNestedType(Asn1Reader asn1Reader) { // processing rules (assuming zero-based bits): // if bit 5 is set to "1", or the type is SEQUENCE/SET -- the type is constructed. Unroll nested types. // if bit 5 is set to "0", attempt to resolve nested types only for UNIVERSAL tags. Logger.writeLog("ParseNestedType-1"); if (asn1Reader.excludedTags.HasKey(asn1Reader.Tag) || asn1Reader.PayloadLength < 2) { Logger.writeLog("ParseNestedType-2"); return; } Logger.writeLog("ParseNestedType-3"); Int64 pstart = asn1Reader.PayloadStartOffset; Int32 plength = asn1Reader.PayloadLength; Storage.Put(Storage.CurrentContext, "asn1Reader.Tag", asn1Reader.Tag); Storage.Put(Storage.CurrentContext, "pstart", pstart); Storage.Put(Storage.CurrentContext, "plength", plength); if (asn1Reader.Tag == 3) { Logger.writeLog("ParseNestedType-4"); pstart = asn1Reader.PayloadStartOffset + 1; plength = asn1Reader.PayloadLength - 1; Logger.writeLog("ParseNestedType-5"); } if (asn1Reader.multiNestedTypes.HasKey(asn1Reader.Tag) || (asn1Reader.Tag & (Byte)Asn1Class.CONSTRUCTED) > 0) { Logger.writeLog("ParseNestedType-6"); asn1Reader.IsConstructed = true; if (!asn1Reader.offsetMap.HasKey(pstart)) { Logger.writeLog("ParseNestedType-7"); PredictResult predictResult = Predict(asn1Reader, pstart, plength, true); asn1Reader.childCount = predictResult.estimatedChildCount; Logger.writeLog("ParseNestedType-8"); } Logger.writeLog("ParseNestedType-9"); asn1Reader.isTaggedConstructed = false; return; } Logger.writeLog("ParseNestedType-10"); if (asn1Reader.Tag > 0 && asn1Reader.Tag < (Byte)Asn1Type.TAG_MASK) { Logger.writeLog("ParseNestedType-11"); PredictResult predictResult = Predict(asn1Reader, pstart, plength, false); Logger.writeLog("ParseNestedType-12"); asn1Reader.childCount = predictResult.estimatedChildCount; asn1Reader.IsConstructed = predictResult.result; Logger.writeLog("ParseNestedType-13"); // reiterate again and build map for children if (asn1Reader.IsConstructed && !asn1Reader.offsetMap.HasKey(pstart)) { Logger.writeLog("ParseNestedType-14"); PredictResult predictResultOther = Predict(asn1Reader, pstart, plength, false); asn1Reader.childCount = predictResultOther.estimatedChildCount; Logger.writeLog("ParseNestedType-15"); } Logger.writeLog("ParseNestedType-16"); } Logger.writeLog("ParseNestedType-17"); asn1Reader.isTaggedConstructed = false; }
public IntraZoneFare(Int64 id, Zone zone, decimal peakHours, decimal offPeakHours) : base(id, peakHours, offPeakHours) => Zone = zone;
// Ширина столбца public void SetColumnWidth(Int64 col, int colWidth) { ((Range)Wsheet.Columns[col, Type.Missing]).EntireColumn.ColumnWidth = colWidth; }
static extern bool WriteProcessMemory(int hProcess, Int64 lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesWritten);
private void SaveHREmployeeLoanApplicationEntity() { if (IsValid) { try { HREmployeeLoanApplicationEntity hREmployeeLoanApplicationEntity = BuildHREmployeeLoanApplicationEntity(); Int64 result = -1; if (hREmployeeLoanApplicationEntity.IsNew) { result = FCCHREmployeeLoanApplication.GetFacadeCreate().Add(hREmployeeLoanApplicationEntity, DatabaseOperationType.Add, TransactionRequired.No); } else { String filterExpression = SqlExpressionBuilder.PrepareFilterExpression(HREmployeeLoanApplicationEntity.FLD_NAME_EmployeeLoanApplicationID, hREmployeeLoanApplicationEntity.EmployeeLoanApplicationID.ToString(), SQLMatchType.Equal); result = FCCHREmployeeLoanApplication.GetFacadeCreate().Update(hREmployeeLoanApplicationEntity, filterExpression, DatabaseOperationType.Update, TransactionRequired.No); } if (result > 0) { if (hREmployeeLoanApplicationEntity.IsNew) { #region Approval Process if (ddlAPPanelID != null && ddlAPPanelID.SelectedValue != "0") { Boolean apResult = APRobot.CreateApprovalProcessForNewLoanApplication(result, Int64.Parse(ddlAPPanelID.SelectedValue.ToString())); if (apResult == true) { MiscUtil.ShowMessage(lblMessage, "Approval Process Submited successfully.", UIConstants.MessageType.GREEN); } else { MiscUtil.ShowMessage(lblMessage, "Failed to Submit Approval Process.", UIConstants.MessageType.RED); } } } #endregion _EmployeeLoanApplicationID = 0; _HREmployeeLoanApplicationEntity = new HREmployeeLoanApplicationEntity(); PrepareInitialView(); BindHREmployeeLoanApplicationList(); if (hREmployeeLoanApplicationEntity.IsNew) { MiscUtil.ShowMessage(lblMessage, "Employee Loan Application Information has been added successfully.", false); } else { MiscUtil.ShowMessage(lblMessage, "Employee Loan Application Information has been updated successfully.", false); } } else { if (hREmployeeLoanApplicationEntity.IsNew) { MiscUtil.ShowMessage(lblMessage, "Failed to add Employee Loan Application Information.", false); } else { MiscUtil.ShowMessage(lblMessage, "Failed to update Employee Loan Application Information.", false); } } } catch (Exception ex) { MiscUtil.ShowMessage(lblMessage, ex.Message, true); } } }
public static bool IsPrime(Int64 value) { return(MathHelper.GetFactors(value).Count == 2); }
// Contiene las 10 funciones para cada tipo de variable public String getSumaPositivos(int Nint, Int64 Nint64, float Nfloat, double Ndouble, int limite) { if (Nint == 1) { Tiempo contador = new Tiempo(); contador.iniciaContador(); // Comienza int numero = 1; int resultado = 0; int auxiliar = 0; while (numero <= limite) { resultado = resultado + auxiliar; auxiliar = numero * 5; numero += 1; } contador.terminaContador(); // Finaliza Console.WriteLine(numero.GetType()); Console.WriteLine("Total suma : " + resultado); Console.WriteLine("Tiempo : " + contador.getTiempoTotal().TotalMilliseconds + " ms "); } else if (Nint64 == 1) { Tiempo contador = new Tiempo(); contador.iniciaContador(); // Comienza Int64 numero = 1; Int64 resultado = 0; Int64 auxiliar = 0; while (numero <= limite) { resultado = resultado + auxiliar; auxiliar = numero * 5; numero += 1; } contador.terminaContador(); // Finaliza Console.WriteLine(numero.GetType()); Console.WriteLine("Total suma : " + resultado); Console.WriteLine("Tiempo : " + contador.getTiempoTotal().TotalMilliseconds + " ms "); } else if (Nfloat == 1) { Tiempo contador = new Tiempo(); contador.iniciaContador(); // Comienza float numero = 1; float resultado = 0; float auxiliar = 0; while (numero <= limite) { resultado = resultado + auxiliar; auxiliar = numero * 5; numero += 1; } contador.terminaContador(); // Finaliza Console.WriteLine(numero.GetType()); Console.WriteLine("Total suma : " + resultado); Console.WriteLine("Tiempo : " + contador.getTiempoTotal().TotalMilliseconds + " ms "); } else if (Ndouble == 1) { Tiempo contador = new Tiempo(); contador.iniciaContador(); // Comienza double numero = 1; double resultado = 0; double auxiliar = 0; while (numero <= limite) { resultado = resultado + auxiliar; auxiliar = numero * 5; numero += 1; } contador.terminaContador(); // Finaliza Console.WriteLine(numero.GetType()); Console.WriteLine("Total suma : " + resultado); Console.WriteLine("Tiempo : " + contador.getTiempoTotal().TotalMilliseconds + " ms "); } return("true"); }
public override void Write(Byte[] buffer, Int32 offset, Int32 count) { //we can't pass the argument checking down a level if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0) throw new ArgumentOutOfRangeException("offset", SR.ArgumentNeedNonNegative); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentNeedNonNegative); if ((buffer.Length - offset) < count) throw new ArgumentException(SR.OffsetLengthInvalid); Contract.EndContractBlock(); //if we're not actually writing anything, we don't want to trigger as if we did write something ThrowIfDisposed(); Debug.Assert(CanWrite); if (count == 0) return; if (!_everWritten) { _initialPosition = _baseBaseStream.Position; _everWritten = true; } _checksum = Crc32Helper.UpdateCrc32(_checksum, buffer, offset, count); _baseStream.Write(buffer, offset, count); _position += count; }
PRMSupplierItemMapHistoryEntity IPRMSupplierItemMapHistoryFacade.GetByID(Int64 iD) { String fe = SqlExpressionBuilder.PrepareFilterExpression(PRMSupplierItemMapHistoryEntity.FLD_NAME_SupplierItemMapHistoryID, iD.ToString(), SQLMatchType.Equal); return(DataAccessFactory.CreatePRMSupplierItemMapHistoryDataAccess().GetIL(null, null, String.Empty, fe, DatabaseOperationType.LoadWithFilterExpression)[0]); }
private unsafe int ReadArray(Int64[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (Int64* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; }
public void Get(out Int64 val) { CheckHandle(); eldbus_message_iter_basic_get(Handle, out val); }
public void ProcessTransferred(Int64 transferred, SequenceRangeCollection ranges, int quotaRemaining) { if (transferred < 0) { throw Fx.AssertAndThrow("Argument transferred must be a valid sequence number or 0 for protocol messages."); } bool invalidAck; // ignored, TransmissionStrategy is being used to keep track of what must be re-sent. // In the Request-Reply case this state may not align with acks. bool inconsistentAck; this.strategy.ProcessAcknowledgement(ranges, out invalidAck, out inconsistentAck); invalidAck = (invalidAck || ((transferred != 0) && !ranges.Contains(transferred))); if (!invalidAck) { if ((transferred > 0) && this.strategy.ProcessTransferred(transferred, quotaRemaining)) { ActionItem.Schedule(sendRetries, this); } else { this.OnTransferComplete(); } } else { WsrmFault fault = new InvalidAcknowledgementFault(this.id, ranges); RaiseFault(fault.CreateException(), fault); } }
protected override void Execute(CodeActivityContext executionContext) { #region "Load CRM Service from context" objCommon = new Common(executionContext); objCommon.tracingService.Trace("CreateContact activity:Load CRM Service from context --- OK"); #endregion #region "Read Parameters" string jsonPayload = Payload.Get(executionContext); DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Contact)); //Contact contactPayload = JsonConvert.DeserializeObject<Contact>(jsonPayload); //EntityReference _Contact; Boolean _IsRecordCreated = false; Int64 ErrorCode = 400; //Bad Request String _ErrorMessage = string.Empty; String _ErrorMessageDetail = string.Empty; Guid ContactId = Guid.Empty; #endregion #region "Create Execution" try { using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonPayload))) { Contact contactPayload = (Contact)deserializer.ReadObject(ms); Entity contact = new Entity("contact");//,"defra_upn", _UPN); if (string.IsNullOrEmpty(contactPayload.b2cobjectid) || string.IsNullOrWhiteSpace(contactPayload.b2cobjectid)) { _ErrorMessage = "B2C Object Id can not be empty"; } if (string.IsNullOrEmpty(contactPayload.firstname) || string.IsNullOrWhiteSpace(contactPayload.firstname)) { _ErrorMessage = "First Name can not empty"; } if (string.IsNullOrEmpty(contactPayload.lastname) || string.IsNullOrWhiteSpace(contactPayload.lastname)) { _ErrorMessage = "Last Name can not empty"; } if (!string.IsNullOrEmpty(contactPayload.b2cobjectid) && !string.IsNullOrWhiteSpace(contactPayload.b2cobjectid) && contactPayload.b2cobjectid.Length > 50) { _ErrorMessage = "B2C Object Id is invalid/exceed the max length(50)"; } if (!string.IsNullOrEmpty(contactPayload.firstname) && contactPayload.firstname.Length > 50) { _ErrorMessage = "Firstname exceeded the max length(50)"; } if (!string.IsNullOrEmpty(contactPayload.lastname) && contactPayload.lastname.Length > 50) { _ErrorMessage = "Lastname exceeded the max length(50)"; } if (!string.IsNullOrEmpty(contactPayload.lastname) && contactPayload.lastname.Length > 100) { _ErrorMessage = "Email exceeded the max length(100)"; } if (_ErrorMessage == string.Empty) { //search contact record based on UPN OrganizationServiceContext orgSvcContext = new OrganizationServiceContext(objCommon.service); var ContactWithUPN = from c in orgSvcContext.CreateQuery("contact") where ((string)c["defra_b2cobjectid"]).Equals((contactPayload.b2cobjectid.Trim())) select new { ContactId = c.Id, UniqueReference = c["defra_uniquereference"] }; var contactRecordWithUPN = ContactWithUPN.FirstOrDefault() == null ? null : ContactWithUPN.FirstOrDefault(); Guid ContactRecordGuidWithUPN = contactRecordWithUPN == null ? Guid.Empty : contactRecordWithUPN.ContactId; if (ContactRecordGuidWithUPN == Guid.Empty) { objCommon.tracingService.Trace("CreateContact activity:ContactRecordGuidWithUPN is empty started, Creating Contact.."); ErrorCode = 200;//Success if (contactPayload.title != null) { contact["defra_title"] = contactPayload.title; } contact["firstname"] = contactPayload.firstname; contact["lastname"] = contactPayload.lastname; if (contactPayload.middlename != null) { contact["middlename"] = contactPayload.middlename; } if (contactPayload.middlename != null) { contact["emailaddress1"] = contactPayload.email; } if (contactPayload.b2cobjectid != null) { contact["defra_b2cobjectid"] = contactPayload.b2cobjectid; } if (contactPayload.tacsacceptedversion != null) { contact["defra_tacsacceptedversion"] = contactPayload.tacsacceptedversion; } if (contact["telephone1"] != null) { contact["telephone1"] = contactPayload.telephone; } objCommon.tracingService.Trace("setting contact date params:started.."); if (!string.IsNullOrEmpty(contactPayload.tacsacceptedon) && !string.IsNullOrWhiteSpace(contactPayload.tacsacceptedon)) { DateTime resultDate; if (DateTime.TryParse(contactPayload.tacsacceptedon, out resultDate)) { contact["defra_tandcagreedon"] = resultDate; } } //set birthdate if (!string.IsNullOrEmpty(contactPayload.dob) && !string.IsNullOrWhiteSpace(contactPayload.dob)) { DateTime resultDob; if (DateTime.TryParse(contactPayload.dob, out resultDob)) { contact["birthdate"] = resultDob; } } if (!string.IsNullOrEmpty(contactPayload.gender) && !string.IsNullOrWhiteSpace(contactPayload.gender)) { int genderCode; if (int.TryParse(contactPayload.gender, out genderCode)) { contact["gendercode"] = new OptionSetValue(genderCode); } } objCommon.tracingService.Trace("CreateContact activity:started.."); ContactId = objCommon.service.Create(contact); objCommon.tracingService.Trace("CreateContact activity:ended. " + ContactId); //var CreatedContacts = from c in orgSvcContext.CreateQuery("contact") // where ((Guid)c["contactid"]).Equals((ContactId)) // select new { ContactUID = c["defra_uniquereference"] }; //var CreatedContact = CreatedContacts.FirstOrDefault() == null ? null : CreatedContacts.FirstOrDefault(); //if (CreatedContact != null) // UID.Set(executionContext, CreatedContact.ContactUID); this.CrmGuid.Set(executionContext, ContactId.ToString()); // Entity ContactRecord = objCommon.service.Retrieve("contact", ContactId, new Microsoft.Xrm.Sdk.Query.ColumnSet("defra_uniquereference")); // this.UniqueReference.Set(executionContext, ContactRecord["defra_uniquereference"]); // _Contact = new EntityReference("contact", ContactId); // this.Individual.Set(executionContext, _Contact); _IsRecordCreated = true; if (contactPayload.address != null) { //CreateAddress(contactPayload.address, ContactId); objCommon.CreateAddress(contactPayload.address, new EntityReference("contact", ContactId)); } } else { this.CrmGuid.Set(executionContext, ContactRecordGuidWithUPN.ToString()); objCommon.tracingService.Trace("CreateContact activity:ContactRecordGuidWithUPN is found/duplicate started.."); ErrorCode = 412;//Duplicate UPN _ErrorMessage = "Duplicate Record"; } } objCommon.tracingService.Trace("CreateContact activity:setting output params like error code etc.. started"); this.IsRecordCreated.Set(executionContext, _IsRecordCreated); this.Code.Set(executionContext, ErrorCode.ToString()); this.Message.Set(executionContext, _ErrorMessage); this.MessageDetail.Set(executionContext, _ErrorMessageDetail); objCommon.tracingService.Trace("CreateContact activity:setting output params like error code etc.. ended"); } } catch (FaultException <OrganizationServiceFault> ex) { ErrorCode = 500;//Internal Error _ErrorMessage = "Error occured while processing request"; _ErrorMessageDetail = ex.Message; //throw ex; this.Code.Set(executionContext, ErrorCode.ToString()); this.Message.Set(executionContext, _ErrorMessage); this.MessageDetail.Set(executionContext, _ErrorMessageDetail); } #endregion }
/// <summary> /// Logs remoting fragment data to verbose channel. /// </summary> /// <param name="id"></param> /// <param name="opcode"></param> /// <param name="task"></param> /// <param name="keyword"></param> /// <param name="objectId"></param> /// <param name="fragmentId"></param> /// <param name="isStartFragment"></param> /// <param name="isEndFragment"></param> /// <param name="fragmentLength"></param> /// <param name="fragmentData"></param> internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, Int64 objectId, Int64 fragmentId, int isStartFragment, int isEndFragment, UInt32 fragmentLength, PSETWBinaryBlob fragmentData) { if (provider.IsEnabled(PSLevel.Verbose, keyword)) { string payLoadData = BitConverter.ToString(fragmentData.blob, fragmentData.offset, fragmentData.length); payLoadData = string.Format(CultureInfo.InvariantCulture, "0x{0}", payLoadData.Replace("-", "")); provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, objectId, fragmentId, isStartFragment, isEndFragment, fragmentLength, payLoadData); } }
public static extern bool ReadProcessMemory(int hProcess, Int64 lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead);
/// <summary> /// Determines the 'Primary' and/or 'Within Organisation' setting(s) for a Partner. /// </summary> /// <param name="APartnerKey">PartnerKey of the Partner.</param> /// <param name="AOverallContSettingKind">Specify the kind of Overall Contact Setting(s) that you want returned. /// Combine multiple ones with the binary OR operator ( | ).</param> /// <returns>An instance of <see cref="Calculations.TPartnersOverallContactSettings"/> that holds the /// <see cref="Calculations.TPartnersOverallContactSettings"/> for the Partner. However, it returns null /// in case the Partner hasn't got any p_partner_attribute records, or when the Partner has no p_partner_attribute /// records that constitute Contact Detail records, or when the Partner has got only one p_partner_attribute record /// but this records' Current flag is false. It also returns null if no record was found that met what was asked for /// with <paramref name="AOverallContSettingKind"/>!</returns> public static Calculations.TPartnersOverallContactSettings GetPartnersOverallCS(Int64 APartnerKey, Calculations.TOverallContSettingKind AOverallContSettingKind) { PPartnerAttributeTable PartnerAttributeDT; return(GetPartnersOverallCS(APartnerKey, AOverallContSettingKind, out PartnerAttributeDT)); }
public override dynamic ValueToData(ValueElement element, string value) { return(Int64.Parse(value)); }
protected void lnkbtnSave_OnClick(object sender, EventArgs e) { DtTemp = (DataTable)ViewState["dt"]; if (DtTemp == null || DtTemp.Rows.Count <= 0) { ShowMessage("Please enter details"); drpItemType.Focus(); return; } if (Convert.ToInt32(drpBaseCity.SelectedValue) == Convert.ToInt32(drpDeliveryPlace.SelectedValue)) { //ShowMessage("Issuing Location and Receiving Location can't be same"); Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "Comparecity()", true); drpDeliveryPlace.Focus(); return; } if (drpBaseCity.SelectedIndex == 0) { this.ShowMessage("Please select Issuing Location"); drpBaseCity.Focus(); return; } if (drpDeliveryPlace.SelectedIndex == 0) { this.ShowMessage("Please select Receiving Location"); drpDeliveryPlace.Focus(); return; } //StockTransferDAL objstck = new StockTransferDAL(); tblStckTrans_Head objtblStck = new tblStckTrans_Head(); objtblStck.StckTrans_No = Convert.ToInt32(txtIssueNo.Text.Trim()); objtblStck.StckTrans_Date = Convert.ToDateTime(ApplicationFunction.mmddyyyy(txtDate.Text.Trim())); objtblStck.IssLoc_Idno = Convert.ToInt32(drpBaseCity.SelectedValue); objtblStck.RecLoc_Idno = Convert.ToInt32(drpDeliveryPlace.SelectedValue); objtblStck.Year_Idno = Convert.ToInt32(ddlDateRange.SelectedValue); objtblStck.Remark = txtRemark.Text.Trim(); objtblStck.User_Idno = Convert.ToInt32(Session["UserIdno"]); objtblStck.Net_Amnt = Convert.ToDouble(txtNetAmnt.Text.Trim()); objtblStck.Date_Created = DateTime.Now; objtblStck.Date_Modified = DateTime.Now; List <tblStckTrans_Detl> objstckTrDetl = new List <tblStckTrans_Detl>(); if (DtTemp != null) { foreach (DataRow dtrow in DtTemp.Rows) { tblStckTrans_Detl objDetl = new tblStckTrans_Detl(); objDetl.ItemType_Idno = Convert.ToInt64(dtrow["ITEM_TYPEID"]); objDetl.SerialNo_Idno = Convert.ToInt64(Convert.ToString(dtrow["ITEM_SERIALID"]) == "" ? "0" : dtrow["ITEM_SERIALID"]); objDetl.Item_Serial_No = Convert.ToString(dtrow["ITEM_SERIAL"]); objDetl.TyreType_Idno = Convert.ToInt64(Convert.ToString(dtrow["TYRE_TYPEID"]) == "" ? "0" : dtrow["TYRE_TYPEID"]); objDetl.Item_Idno = Convert.ToInt64(Convert.ToString(dtrow["ITEM_ID"]) == "" ? "0" : dtrow["ITEM_ID"]); objDetl.Qty = Convert.ToDouble(dtrow["ITEM_QTY"]); objDetl.Rate = Convert.ToDouble(dtrow["ITEM_RATE"]); objDetl.Tot_Amnt = Convert.ToDouble(dtrow["ITEM_QTY"]) * Convert.ToDouble(dtrow["ITEM_RATE"]); objstckTrDetl.Add(objDetl); } } else { DtTemp = CreateDt(); } if (objstckTrDetl.Count <= 0) { ShowMessage("Please enter details"); return; } Int64 InsertId = 0; Int64 UpdateId = 0; StockTransferDAL obj = new StockTransferDAL(); if (Convert.ToInt32(hidStckid.Value) > 0) { objtblStck.StckTrans_Idno = Convert.ToInt32(hidStckid.Value); UpdateId = obj.Update(objtblStck, objstckTrDetl); } else { InsertId = obj.Insert(objtblStck, objstckTrDetl); } obj = null; if (InsertId > 0) { strMsg = "Record save successfully"; } else if (UpdateId > 0) { strMsg = "Record Update successfully"; } else if (InsertId < 0) { strMsg = "Receipt No already exists"; } else if (UpdateId < 0) { strMsg = "Record not Update successfully"; } else { strMsg = "Record not saved successfully"; } //ScriptManager.RegisterStartupScript(this, this.GetType(), "alertstrMsg", "PassMessage('" + strMsg + "')", true); // ShowMessage(strMsg); this.ClearAll(); }
protected override void Dispose(Boolean disposing) { if (disposing && !_isDisposed) { // if we never wrote through here, save the position if (!_everWritten) _initialPosition = _baseBaseStream.Position; if (!_leaveOpenOnClose) _baseStream.Dispose(); // Close my super-stream (flushes the last data) if (_saveCrcAndSizes != null) _saveCrcAndSizes(_initialPosition, Position, _checksum, _baseBaseStream, _zipArchiveEntry, _onClose); _isDisposed = true; } base.Dispose(disposing); }
static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 MacAddr, ref Int32 PhyAddrLen);
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int64[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); }
public ActionResult GetGrid(JqGridRequest request, string key, string value, string viewModel, string field, long? id_master) { string fieldMain = String.Empty; long ID_master; bool result = Int64.TryParse(id_master.ToString(), out ID_master); if (String.IsNullOrEmpty(field)) { fieldMain = "ID_Lokacija"; } else { fieldMain = field; } viewModel = gridModelNamespace + viewModel; string filterExpression = String.Empty; if (request.Searching) { if (request.SearchingFilter != null) filterExpression = GetFilter(request.SearchingFilter.SearchingName, request.SearchingFilter.SearchingOperator, request.SearchingFilter.SearchingValue); else if (request.SearchingFilters != null) { StringBuilder filterExpressionBuilder = new StringBuilder(); string groupingOperatorToString = request.SearchingFilters.GroupingOperator.ToString(); foreach (JqGridRequestSearchingFilter searchingFilter in request.SearchingFilters.Filters) { filterExpressionBuilder.Append(GetFilter(searchingFilter.SearchingName, searchingFilter.SearchingOperator, searchingFilter.SearchingValue)); filterExpressionBuilder.Append(String.Format(KeyWord.FormaterRazno.StringFormat.Prvi, groupingOperatorToString)); } if (filterExpressionBuilder.Length > 0) filterExpressionBuilder.Remove(filterExpressionBuilder.Length - groupingOperatorToString.Length - 2, groupingOperatorToString.Length + 2); filterExpression = filterExpressionBuilder.ToString(); } } string sortingName = request.SortingName; long totalRecordsCount = GetCount(filterExpression, key, value); JqGridResponse response = new JqGridResponse() { TotalPagesCount = (int)Math.Ceiling((float)totalRecordsCount / (float)request.RecordsCount), PageIndex = request.PageIndex, TotalRecordsCount = totalRecordsCount, }; response.Records.AddRange ( from item in GetGridData(filterExpression, key, value, String.Format(KeyWord.FormaterRazno.StringFormat.PrviDrugi, sortingName, request.SortingOrder), request.PageIndex * request.RecordsCount, (request.PagesCount.HasValue ? request.PagesCount.Value : 1) * request.RecordsCount) select new JqGridRecord(Convert.ToString(item.GetType().GetProperty(fieldMain).GetValue(item, null)), Activator.CreateInstance(Type.GetType(viewModel), new[] { item })) ); return new JqGridJsonResult() { Data = response }; }
/// <summary> /// Sets the value of a field in a record /// </summary> /// <param name="ordinal">The ordinal of the field</param> /// <param name="value">The new field value</param> public void SetInt64(int ordinal, Int64 value) { SetValue(ordinal, value); }
public static void Encode(IByteWriter stream, PaymentOp encodedPaymentOp) { AccountID.Encode(stream, encodedPaymentOp.Destination); Asset.Encode(stream, encodedPaymentOp.Asset); Int64.Encode(stream, encodedPaymentOp.Amount); }
/// <summary> /// Builds the results for later output to the console window /// </summary> /// <param name="Distance">The distance that the starship needs to travel</param> private static void CalculateReturnValues(long Distance) { string ShipName = ""; try { if (Results.Count > 0) { Results.Clear(); } foreach (Starships starship in StarshipsData) { ResultData rd = new ResultData { name = starship.name, SupplyStops = (starship.MGLT == "unknown" || starship.consumables == "unknown" ? -1 : ReturnSupplyStopCount(Distance, Int64.Parse(starship.MGLT), ConvertToHours(starship.consumables))) }; Results.Add(rd); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ShipName); throw ex; } }
private void btnCreateLicense_Click(object sender, EventArgs e) { if (txtClientName.Text.Trim().Equals(string.Empty)) { MessageBox.Show("Client Name must be filled", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((cmbApplicationName.SelectedItem == null) || (cmbApplicationName.SelectedItem.ToString().Trim().Equals(string.Empty))) { MessageBox.Show("Application Name must be filled", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (lvComputername.Items.Count == 0) { MessageBox.Show("Licensed Computers must be filled", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (dtExpireDate.Value < DateTime.Now) { MessageBox.Show("License expire date is in the past", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string[] servers = new string[lvComputername.Items.Count]; for (int i = 0; i < lvComputername.Items.Count; i++) { servers[i] = lvComputername.Items[i].Text; } string key = string.Empty; try { key = LicenseGenerator.GenerateLicenseKeyV1(txtClientName.Text, cmbApplicationName.SelectedItem.ToString(), servers, Int64.Parse(cbLicenseCount.SelectedItem.ToString()), dtExpireDate.Value, chkServer.Checked, new string[0]); } catch (Exception ex) { MessageBox.Show("Error while creating license key\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { LicenseHandler lh = new LicenseHandler(key); } catch { MessageBox.Show("Key generation failed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string filename = string.Empty; SaveFileDialog sDialog = new SaveFileDialog(); sDialog.Filter = "OCG License File|*.lic"; try { sDialog.FileName = string.Format("{0}.{1}", txtClientName.Text, cmbApplicationName.SelectedItem.ToString()); } catch { } if (sDialog.ShowDialog() == DialogResult.OK) { try { StreamWriter licWriter = new StreamWriter(sDialog.FileName, false); licWriter.WriteLine(key); licWriter.Flush(); licWriter.Close(); } catch (Exception ex) { MessageBox.Show("Error while creating keyfile\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } }