public static string Decrypt(byte[] cipherText, byte[] IV) { // Check arguments. if (cipherText == null || cipherText.Length <= 0) { throw new ArgumentNullException("cipherText"); } if (IV == null || IV.Length <= 0) { throw new ArgumentNullException("IV"); } // Declare the string used to hold the decrypted text. string plaintext = null; // Create an Aes object with the specified key and IV. using (Aes aesAlg = Aes.Create()) { aesAlg.Key = Convert.FromBase64String(_key); aesAlg.IV = IV; // Create a decryptor to perform the stream transform. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for decryption. using (MemoryStream msDecrypt = new MemoryStream(cipherText)) using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream and place them in a string. plaintext = srDecrypt.ReadToEnd(); } } return(plaintext); }
public bool SaveItem(ITreeNodeContent node, ItemChanges changes) { if (!changes.HasFieldsChanged) { return(false); } var catalog = ProductCatalog.Get(Convert.ToInt32(node.ItemId)); if (catalog == null) { var message = string.Format("Product Catalog with id: {0} not found for ITreeNodeContent. ", node.ItemId); _loggingService.Log <ProductCatalogTemplateBuilder>(message); throw new InvalidDataException(message); } foreach (FieldChange change in changes.FieldChanges) { UpdateCatalogValuesFor(change, catalog); } ObjectFactory.Instance.Resolve <IPipeline <ProductCatalog> >("SaveProductCatalog").Execute(catalog); return(true); }
public PatientAppointmentDisplay GetExistingPatientAppointment(string patientId, DateTime appointmentDate, int serviceAreaId, int reasonId) { PatientAppointmentDisplay appointmentDisplay = new PatientAppointmentDisplay(); PatientAppointment appointment = new PatientAppointment(); try { var patientAppointment = new PatientAppointmentManager(); int id = Convert.ToInt32(patientId); appointment = patientAppointment.GetByPatientId(id).FirstOrDefault(n => n.AppointmentDate.Date == appointmentDate.Date && n.ServiceAreaId == serviceAreaId && n.ReasonId == reasonId); if (appointment != null) { appointmentDisplay = Mapappointments(appointment); } else { return(null); } } catch (Exception e) { Msg = e.Message; } return(appointmentDisplay); }
/// <summary> /// Converts the specified search criterion dto. /// </summary> /// <param name="searchCriterionDto">The search criterion dto.</param> /// <returns>ICriterion.</returns> /// <exception cref="ArgumentException">Input has to have at least 3 arguments</exception> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <exception cref="Exception">change this</exception> public ICriterion Convert(SearchCriterionDto searchCriterionDto) { var terminal = (TerminalSearchCriterionDto)searchCriterionDto; var args = terminal.Args; if (args.Length < 3) { throw new ArgumentException("Input has to have at least 3 arguments"); } var reg = Register.Lookup(args[0]); if (reg == null) { throw new ArgumentOutOfRangeException(); } switch (args[1]) { case "-eq": return(new RegisterEqualsCriterion(reg, Conv.ToUInt64(args[2]).ToHexString())); case "-between": var low = Conv.ToUInt64(args[2]); var hi = Conv.ToUInt64(args[3]); // todo: check before return(new RegisterBetweenCriterion(reg, low.ToHexString(), hi.ToHexString())); default: throw new Exception("change this"); } }
private SolidFramework.Converters.Plumbing.ReconstructionMode Translate(Convert.ReconstructionMode mode) { switch (mode) { case Convert.ReconstructionMode.Continuous: { return SolidFramework.Converters.Plumbing.ReconstructionMode.Continuous; } case Convert.ReconstructionMode.Exact: { return SolidFramework.Converters.Plumbing.ReconstructionMode.Exact; } case Convert.ReconstructionMode.Flowing: { return SolidFramework.Converters.Plumbing.ReconstructionMode.Flowing; } case Convert.ReconstructionMode.PlainText: { return SolidFramework.Converters.Plumbing.ReconstructionMode.Plaintext; } default: { throw new Exception("Invalid type."); } } }
public static string Encrypt(this string plainText) { if (IsEncrypted(plainText)) { return(plainText); } var plainTextBytes = UTF8.GetBytes(plainText); var keyBytes = new Rfc2898DeriveBytes(PASSWORD_HASH, ASCII.GetBytes(SALT_KEY)).GetBytes(256 / 8); var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros }; var encryptor = symmetricKey.CreateEncryptor(keyBytes, ASCII.GetBytes(VI_KEY)); using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); return(ENCRYPTION_INDICATOR + Convert.ToBase64String(memoryStream.ToArray())); } } }
public static string Decrypt(this string encryptedText) { if (!IsEncrypted(encryptedText)) { return(encryptedText); } var cipherTextBytes = Convert.FromBase64String(encryptedText.Substring(ENCRYPTION_INDICATOR.Length)); var keyBytes = new Rfc2898DeriveBytes(PASSWORD_HASH, ASCII.GetBytes(SALT_KEY)).GetBytes(256 / 8); var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None }; var decryptor = symmetricKey.CreateDecryptor(keyBytes, ASCII.GetBytes(VI_KEY)); using (var memoryStream = new MemoryStream(cipherTextBytes)) { var plainTextBytes = new byte[cipherTextBytes.Length]; using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); return(UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray())); } } }
public static string EncryptString(string stringToEncrypt) { var b = ASCII.GetBytes(stringToEncrypt); var encrypted = Convert.ToBase64String(b); return(encrypted); }
private IEnumerable <InternalBulkMeasurements> Decompress(string data) { var bytes = Convert.FromBase64String(data); using var to = new MemoryStream(); using var from = new MemoryStream(bytes); using var gzip = new GZipStream(@from, CompressionMode.Decompress); gzip.CopyTo(to); var final = to.ToArray(); var protoMeasurements = MeasurementData.Parser.ParseFrom(final); var measurements = from measurement in protoMeasurements.Measurements group measurement by measurement.SensorID into g select new InternalBulkMeasurements { SensorID = ObjectId.Parse(g.Key), Measurements = g.Select(m => new SingleMeasurement { Data = m.Datapoints.ToDictionary(p => p.Key, p => new DataPoint { Accuracy = p.Accuracy, Precision = p.Precision, Unit = p.Unit, Value = Convert.ToDecimal(p.Value), }), Location = new GeoJsonPoint <GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(m.Longitude, m.Latitude)), PlatformTime = m.PlatformTime.ToDateTime(), Timestamp = m.Timestamp.ToDateTime() }).ToList() }; this.logger.LogInformation("Received {count} measurements.", protoMeasurements.Measurements.Count); return(measurements); }
private void XUserDataBlockForm_Load(object sender, EventArgs e) { try { txtDeviceName.Text = dv.DeviceName; gpDataBlock.Text = ch.ChannelName; txtChannelId.Text = ch.ChannelId.ToString(); txtDeviceId.Text = dv.DeviceId.ToString(); txtOPCServerPath.Text = ch.Mode; txtOPCServer.Text = ch.CPU; txtOPCServerPath.Enabled = false; if (db == null) { Text = "Add DataBlock"; txtDataBlockId.Text = Convert.ToString(dv.DataBlocks.Count + 1); txtDataBlock.Text = "DataBlock" + Convert.ToString(dv.DataBlocks.Count + 1); } else { Text = "Edit DataBlock"; txtChannelId.Text = db.ChannelId.ToString(); txtDeviceId.Text = db.DeviceId.ToString(); txtDataBlock.Text = db.DataBlockName; //CboxTypeOfRead.Text = db.TypeOfRead; //txtOPCServerPath.Text = ch.Mode; //txtOPCServer.Text = ch.CPU; txtDataBlockId.Text = $"{db.DataBlockId}"; } } catch (Exception ex) { EventscadaException?.Invoke(GetType().Name, ex.Message); } }
/// <summary> /// 获取s the name of the HTML. /// </summary> /// <param name="value">The value.</param> public static string GetHtmlName(this Enum value) { // 获取枚举值类型和名称 var type = value.GetType(); var name = Enum.GetName(type, value); if (name == null) { return(Convert.ToInt32(value).ToString()); } // 获取Display属性 var field = type.GetField(Enum.GetName(type, value)); var displayAttribute = field.GetAttributes <DisplayAttribute>().FirstOrDefault(); if (displayAttribute != null) { name = displayAttribute.GetName() ?? displayAttribute.GetShortName(); var cssAttribute = field.GetAttributes <LabelCssClassAttribute>().FirstOrDefault(); if (cssAttribute != null) { name = $@"<span class='m-badge m-badge--wide {cssAttribute.CssClass}'>{name}</span>"; } } // 返回默认名称 return(name); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void okButton_Click(object sender, EventArgs e) { int[] indicies = this.columnTable.SelectedIndicies; if (indicies.Length > 0) { if (this.widthTextBox.Text.Length == 0) { this.columnTable.TableModel[indicies[0], 0].Tag = Column.MinimumWidth; } else { int width = Convert.ToInt32(this.widthTextBox.Text); if (width < Column.MinimumWidth) { this.columnTable.TableModel[indicies[0], 0].Tag = Column.MinimumWidth; } else { this.columnTable.TableModel[indicies[0], 0].Tag = width; } } } for (int i = 0; i < this.columnTable.TableModel.Rows.Count; i++) { this.model.Columns[i].Visible = this.columnTable.TableModel[i, 0].Checked; this.model.Columns[i].Width = (int)this.columnTable.TableModel[i, 0].Tag; } this.Close(); }
protected override void CustomSort(int ColumnIndex) { if (OldColumnIndex != ColumnIndex) { SortDirection = SortDirection.Asc; } if (SortDirection == SortDirection.Desc) { SortDirection = SortDirection.Asc; } else { SortDirection = SortDirection.Desc; } var resultList = new List <Directive>(); var list = radGridView1.Rows.Select(i => i).ToList(); list.Sort(new DirectiveGridViewDataRowInfoComparer(ColumnIndex, Convert.ToInt32(SortDirection))); foreach (var item in list) { resultList.Add(item.Tag as Directive); } SetItemsArray(resultList.ToArray()); OldColumnIndex = ColumnIndex; }
/// <summary> /// Modifies the source data before passing it to the target for display in the UI. /// </summary> /// <param name="value">The source data being passed to the target.</param> /// <param name="targetType">The <see cref="T:System.Type"/> of data expected by the target dependency property.</param> /// <param name="parameter">An optional parameter to be used in the converter logic.</param> /// <param name="language">The culture of the conversion.</param> /// <returns> /// The value to be passed to the target dependency property. /// </returns> public object Convert(object value, Type targetType, object parameter, string language) { var result = 0; var offset = 0; if (parameter is int) { offset = (int)parameter; } else if (parameter is string) { int.TryParse((string)parameter, NumberStyles.Any, CultureInfo.InvariantCulture, out offset); } if (value != null) { result = (int)Converter.ChangeType(value, typeof(int), CultureInfo.InvariantCulture); var typeInfo = value.GetType().GetTypeInfo(); if (typeInfo.IsClass || (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Nullable <>))) { result++; } result += offset; } return(result); }
///// <summary> ///// 变更类型 ///// </summary> ///// <param name="value">值</param> ///// <param name="type">类型</param> //public static object ChangeType(string value, Type type) //{ // object obj = null; // var nullableType = Nullable.GetUnderlyingType(type); // try // { // if (nullableType != null) // { // if (value == null) // obj = null; // else // obj = OtherChangeType(value, type); // } // else if (typeof(Enum).IsAssignableFrom(type)) // { // obj = Enum.Parse(type, value); // } // else // { // obj = Convert.ChangeType(value, type); // } // return obj; // } // catch // { // return default; // } //} /// <summary> /// 变更类型 /// </summary> /// <param name="value">值</param> /// <param name="type">类型</param> /// <param name="cell">单元格</param> public static object ChangeType(object value, Type type, ICell cell) { try { if (value == null && type.IsGenericType) { return(Activator.CreateInstance(type)); } if (value == null || string.IsNullOrWhiteSpace(value.ToString())) { return(null); } if (type == value.GetType()) { return(value); } if (type.IsEnum) { if (value is string) { return(Enum.Parse(type, value as string)); } else { return(Enum.ToObject(type, value)); } } if (!type.IsInterface && type.IsGenericType) { Type innerType = type.GetGenericArguments()[0]; object innerValue = ChangeType(value, innerType, cell); return(Activator.CreateInstance(type, new object[] { innerValue })); } if (value is string && type == typeof(Guid)) { return(new Guid(value as string)); } if (value is string && type == typeof(Version)) { return(new Version(value as string)); } if (!(value is IConvertible)) { return(value); } return(Convert.ChangeType(value, type)); } catch (Exception ex) { throw new OfficeDataConvertException($"值转换失败。输入值为: {value}, 目标类型为: {type.FullName}", ex) { PrimitiveType = value.GetType(), TargetType = type, Value = value, RowIndex = cell.RowIndex + 1, ColumnIndex = cell.ColumnIndex + 1, Name = cell.Name, }; } }
private void ItemCatalogForDaHour(ConsoleSystem.Arg arg) { var player = arg.Connection.player as BasePlayer; int hour = Convert.ToInt32(arg.Args[0]); ItemCatalogForDaHour(player, hour); }
public WkHtmlToPdfConverter() { bool useX11 = false; try { useX11 = SysConvert.ToBoolean(ConfigurationManager.AppSettings["WkHtmlToXSharp.UseX11"]); } catch (Exception ex) { _Log.Error("Unable to parse 'WkHtmlToXSharp.UseX11' app. setting.", ex); } // Try to deploy native libraries bundles. WkHtmlToXLibrariesManager.InitializeNativeLibrary(); var version = NativeCalls.WkHtmlToPdfVersion(); if (NativeCalls.wkhtmltopdf_init(useX11 ? 1 : 0) == 0) { throw new InvalidOperationException(string.Format("wkhtmltopdf_init failed! (version: {0}, useX11 = {1})", version, useX11)); } _Log.DebugFormat("Initialized new converter instance (Version: {0}, UseX11 = {1})", version, useX11); }
public bool SaveItem(ITreeNodeContent node, ItemChanges changes) { if (!changes.HasFieldsChanged) { return(false); } var productVariant = Product.Get(Convert.ToInt32(node.ItemId)); if (productVariant == null) { var message = string.Format("Product with id: {0} not found for ITreeNodeContent. ", node.ItemId); _loggingService.Debug <ProductCatalogTemplateBuilder>(message); throw new InvalidDataException(message); } foreach (FieldChange fieldChange in changes.FieldChanges) { UpdateVariantValue(fieldChange, productVariant, changes.Item); } ObjectFactory.Instance.Resolve <IPipeline <Product> >("SaveProduct").Execute(productVariant.ParentProduct); return(true); }
public UserMap Add(UserMap userMap) { if (userMap == null) { throw new ArgumentNullException("userMap"); } var sql = @"INSERT INTO [dbo].[User_UserMap] ([UserId] ,[LevelNumber],[TeamNumber] ,[ChildNode] ,[ParentMap]) VALUES (@UserId ,@LevelNumber,@TeamNumber ,@ChildNode ,@ParentMap)"; var parameters = new[] { RepositoryContext.CreateParameter("@LevelNumber", userMap.LevelNumber), RepositoryContext.CreateParameter("@TeamNumber", userMap.TeamNumber), RepositoryContext.CreateParameter("@ChildNode", userMap.ChildNode), RepositoryContext.CreateParameter("@ParentMap", userMap.ParentMap) }; var result = RepositoryContext.ExecuteScalar(sql, parameters); if (result != null && result != DBNull.Value) { userMap.Id = Convert.ToInt64(result); } return(userMap); }
/// <summary> /// Converts an attribute to the required type if possible /// </summary> /// <param name="attributeValue"></param> /// <typeparam name="TType"></typeparam> /// <returns></returns> public TType ConvertTo <TType>(AttributeValue attributeValue) { var decimalType = attributeValue as DecimalAttributeValue; if (decimalType != null && decimalType.Value.HasValue) { return((TType)SystemConvert.ChangeType(decimalType.Value.Value, typeof(TType))); } var stringType = attributeValue as StringAttributeValue; if (stringType != null && !string.IsNullOrWhiteSpace(stringType.Value)) { return((TType)SystemConvert.ChangeType(stringType.Value, typeof(TType))); } var integerType = attributeValue as IntegerAttributeValue; if (integerType != null) { return((TType)SystemConvert.ChangeType(integerType.Value, typeof(TType))); } var booleanType = attributeValue as BooleanAttributeValue; if (booleanType != null) { return((TType)SystemConvert.ChangeType(booleanType.Value, typeof(TType))); } return(default(TType)); }
/// <summary> /// Returns the base-64 encoded, {username}:{password} formatted string of this `<see cref="Credential"/>. /// </summary> public string ToBase64String() { string basicAuthValue = string.Format(CultureInfo.InvariantCulture, "{0}:{1}", _username, _password); byte[] authBytes = UTF8.GetBytes(basicAuthValue); return(Convert.ToBase64String(authBytes)); }
public void Edit([FromBody] List <NhapHangEntity> entity) { var th = new List <NhapHang>(); for (int i = 0; i < entity.Count - 1; i++) { var t = entity[i].MapTo <NhapHang>(); //t.MaDonHang = entity[i].MaDonHang; t.IdNv = IdCty(); t.TenNcc = entity[entity.Count - 1].TenNcc; t.TenNv = _user.Users.SingleOrDefault(j => j.Id.Equals(_user.AbpSession.UserId)).FullName; t.NgayGhi = Convert.ToDateTime(entity[i].NgayGhi); th.Add(t); } //_nhap.CreatesOrUpdates(th); var t1 = entity[entity.Count - 1]; if (t1 != null) { var h = _qlNx.GetAll(IdCty()).FirstOrDefault(); if (h != null) { h.IsActive = true; h.ThanhTien = t1.SoLuong; h.ThanhToan = t1.DonGiaMua; h.Conlai = (t1.SoLuong - t1.DonGiaMua); _qlNx.Update(h); } } }
public override InheritanceMappingAttribute[] GetInheritanceMapping(Type type, TypeExtension typeExtension) { var extList = typeExtension.Attributes["InheritanceMapping"]; if (extList == AttributeExtensionCollection.Null) { return(Array <InheritanceMappingAttribute> .Empty); } var attrs = new InheritanceMappingAttribute[extList.Count]; for (var i = 0; i < extList.Count; i++) { var ext = extList[i]; attrs[i] = new InheritanceMappingAttribute { Code = ext["Code"], IsDefault = TypeExtension.ToBoolean(ext["IsDefault", "False"], false), Type = Type.GetType(Convert.ToString(ext["Type"])) }; } return(attrs); }
/// <summary> /// Выполняет группировку элементов /// </summary> protected override void SetGroupsToItems() { itemsListView.Groups.Clear(); if (OldColumnIndex != 9) { foreach (var item in ListViewItemList) { var temp = ListViewGroupHelper.GetGroupString(item.Tag); itemsListView.Groups.Add(temp, temp); item.Group = itemsListView.Groups[temp]; } } else { //Группировка элементов по датам выполнения var groupedItems = ListViewItemList.Where(lvi => lvi.Tag != null && lvi.Tag is NextPerformance) .GroupBy(lvi => Convert.ToDateTime(((NextPerformance)lvi.Tag).PerformanceDate).Date); foreach (var groupedItem in groupedItems) { //Собрание всех выполнений на данную дату в одну коллекцию var performances = groupedItem.Select(lvi => lvi.Tag as NextPerformance).ToList(); var temp = ListViewGroupHelper.GetGroupStringByPerformanceDate(performances, groupedItem.Key.Date); itemsListView.Groups.Add(temp, temp); foreach (var item in groupedItem) { item.Group = itemsListView.Groups[temp]; } } } }
public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) { Object res = new Object(); String[] xpr = SysConvert.ToString(parameter).Split('|'); switch (xpr[0]) { case "+": res = SysConvert.ToDouble(value) + SysConvert.ToDouble(xpr[1]); break; case "-": res = SysConvert.ToDouble(value) - SysConvert.ToDouble(xpr[1]); break; case "*": res = SysConvert.ToDouble(value) * SysConvert.ToDouble(xpr[1]); break; case "/": res = SysConvert.ToDouble(value) / SysConvert.ToDouble(xpr[1]); break; } return(res); }
protected void CalculateButton_Click(object sender, EventArgs e) { if (TextBox1.Text == "") { return; } var watch = new Stopwatch(); watch.Start(); if (DropDownList1.SelectedIndex == 0) { ResultLabel.Text = Check.IsPositive(Convert.ToInt64(TextBox1.Text)) ? "True!" : "False!"; } if (DropDownList1.SelectedIndex == 1) { ResultLabel.Text = Check.IsNegative(Convert.ToInt64(TextBox1.Text)) ? "True!" : "False!"; } if (DropDownList1.SelectedIndex == 2) { ResultLabel.Text = Check.IsEven(Convert.ToInt64(TextBox1.Text)) ? "True!" : "False!"; } if (DropDownList1.SelectedIndex == 3) { ResultLabel.Text = Check.IsOdd(Convert.ToInt64(TextBox1.Text)) ? "True!" : "False!"; } if (DropDownList1.SelectedIndex == 4) { ResultLabel.Text = Check.IsPrime(Convert.ToInt64(TextBox1.Text)) ? "True!" : "False!"; } watch.Stop(); ElapsedTimeLabel.Text = string.Format("Elapsed time: {0} ms", watch.Elapsed.TotalMilliseconds); }
/// <summary> /// Самое последние выполнение в этой группе /// </summary> /// <returns>hours</returns> public int MaxCompliance() { List <int?> list; if (Schedule) { list = (from check in Checks where check.LastPerformance != null orderby check.LastPerformance.OnLifelength.Hours descending select check.LastPerformance.OnLifelength.Hours).ToList(); } else { list = (from check in Checks where check.LastPerformance != null orderby check.LastPerformance.OnLifelength.Days descending select check.LastPerformance.OnLifelength.Days).ToList(); } if (list.Count > 0 && list[0] != null) { return(Convert.ToInt32(list[0])); } return(-1); }
public IEnumerable <PatientAppointmentDisplay> GetPatientAppointments(string patientId) { List <PatientAppointmentDisplay> appointmentsDisplay = new List <PatientAppointmentDisplay>(); IEnumerable <PatientAppointmentDisplay> listAppointments = new List <PatientAppointmentDisplay>(); var appointments = new List <PatientAppointment>(); var bluecardAppointments = new List <BlueCardAppointment>(); try { var patientAppointment = new PatientAppointmentManager(); int id = Convert.ToInt32(patientId); appointments = patientAppointment.GetByPatientId(id); bluecardAppointments = patientAppointment.GetBluecardAppointmentsByPatientId(id); foreach (var appointment in appointments) { PatientAppointmentDisplay appointmentDisplay = Mapappointments(appointment); appointmentsDisplay.Add(appointmentDisplay); } foreach (var appointment in bluecardAppointments) { PatientAppointmentDisplay appointmentDisplay = MapBluecardappointments(appointment); appointmentsDisplay.Add(appointmentDisplay); } listAppointments = appointmentsDisplay.OrderByDescending(n => n.AppointmentDate); } catch (Exception e) { Msg = e.Message; } return(listAppointments); }
public ActionResult AddToBasket(AddToBasketButtonAddToBasketViewModel viewModel) { var cartServiceProvider = new CartServiceProvider(); var contactFactory = new ContactFactory(); string userId = contactFactory.GetContact(); var createCartRequest = new CreateOrResumeCartRequest(Context.GetSiteName(), userId); var cart = cartServiceProvider.CreateOrResumeCart(createCartRequest).Cart; var cartProduct = new CartProduct { ProductId = viewModel.ProductSku, Price = new Price(Convert.ToDecimal(viewModel.Price), cart.CurrencyCode) }; cartProduct.Properties.Add("VariantSku", viewModel.VariantSku); var cartLines = new ReadOnlyCollection <CartLine>( new Collection <CartLine> { new CartLine { Product = cartProduct, Quantity = (uint)viewModel.Quantity } } ); var request = new AddCartLinesRequest(cart, cartLines); cartServiceProvider.AddCartLines(request); return(Json(_miniBasketService.Refresh(), JsonRequestBehavior.AllowGet)); }
private IfcValue ConvertToIfcValue(AttributeValue valueBaseType) { var decimalType = valueBaseType as DecimalAttributeValue; if (decimalType != null && decimalType.Value.HasValue) { return(new IfcReal((double)SystemConvert.ChangeType(decimalType.Value.Value, typeof(double)))); } var stringType = valueBaseType as StringAttributeValue; if (stringType != null && !string.IsNullOrEmpty(stringType.Value)) { return(new IfcText((string)SystemConvert.ChangeType(stringType.Value, typeof(string)))); } var integerType = valueBaseType as IntegerAttributeValue; if (integerType != null) { return(new IfcInteger((int)SystemConvert.ChangeType(integerType.Value, typeof(int)))); } var booleanType = valueBaseType as BooleanAttributeValue; if (booleanType != null) { return(new IfcBoolean((bool)SystemConvert.ChangeType(booleanType.Value, typeof(bool)))); } return(default(IfcText)); }
/// <summary> /// Loads a matrix from a file to a double[][] array. /// </summary> /// <param name="fileName">Name of the file.</param> /// <returns></returns> public static double[][] LoadMatrix(string fileName) { string[] allLines = System.IO.File.ReadAllLines(fileName); double[][] matrix = new double[allLines.Length][]; for (int i = 0; i < allLines.Length; i++) { string[] values = allLines[i].Split(','); matrix[i] = new double[values.Length]; for (int j = 0; j < values.Length; j++) { if (values[j] != "") { matrix[i][j] = Convert.ToDouble(values[j]); } else { matrix[i][j] = Double.NaN; } } } return(matrix); }
private void Register(Type fromType, Convert conversion) { conversions.Add(new KeyValuePair<Type, Convert>(fromType, conversion)); }
/// <summary> /// Takes the inverse square root of x using Newton-Raphson /// approximation with 1 pass after clever inital guess using /// bitshifting. /// See http://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/ for more information. /// </summary> /// <param name="x">The value.</param> /// <param name="iterations">The number of iterations to make. Higher means more precision.</param> /// <returns>The inverse square root of x</returns> public static float InvSqrt(float x, int iterations = 0) { Convert convert = new Convert(); convert.x = x; float xhalf = 0.5f * x; convert.i = 0x5f3759df - (convert.i >> 1); x = convert.x; x = x * (1.5f - xhalf * x * x); for (int i = 0; i < iterations; i++) { x = x * (1.5f - xhalf * x * x); } return x; }
// inflect according to the given conversion public string InflectVerb(string verb, Convert convert) { if (plugenv != null) { return (string)plugenv.ImmediateConvertTo(new KeyValuePair<string, Convert>(verb, convert), ConjugationResultType, 2, 1000); } return verb; }