public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) { string userName = (string)context["UserName"]; if (!string.IsNullOrEmpty(userName)) repository[userName] = collection.Cast<SettingsPropertyValue>() .ToDictionary(pv => pv.Name, pv => pv.PropertyValue); }
/// <summary> /// The set property values. /// </summary> /// <param name="context"> /// The context. /// </param> /// <param name="collection"> /// The collection. /// </param> public static void SetPropertyValues(int boardId, string appname, int userId, SettingsPropertyValueCollection collection, bool dirtyOnly = true) { if (userId == 0 || collection.Count < 1) { return; } bool itemsToSave = true; if (dirtyOnly) { itemsToSave = collection.Cast<SettingsPropertyValue>().Any(pp => pp.IsDirty); } // First make sure we have at least one item to save if (!itemsToSave) { return; } // load the data for the configuration List<SettingsPropertyColumn> spc = LoadFromPropertyValueCollection(collection); if (spc != null && spc.Count > 0) { // start saving... LegacyDb.SetProfileProperties(boardId, appname, userId, collection, spc, dirtyOnly); } }
/// <summary> /// The set property values. /// </summary> /// <param name="context"> /// The context. /// </param> /// <param name="collection"> /// The collection. /// </param> public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) { var username = (string)context["UserName"]; if (string.IsNullOrEmpty(username) || collection.Count < 1) { return; } // this provider doesn't support anonymous users if (!Convert.ToBoolean(context["IsAuthenticated"])) { ExceptionReporter.ThrowArgument("PROFILE", "NOANONYMOUS"); } // First make sure we have at least one item to save if (!collection.Cast<SettingsPropertyValue>().Any(pp => pp.IsDirty)) { return; } // load the data for the configuration this.LoadFromPropertyValueCollection(collection); object userID = DB.Current.GetProviderUserKey(this.ApplicationName, username); if (userID != null) { // start saving... DB.Current.SetProfileProperties(this.ApplicationName, userID, collection, this._settingsColumnsList); // erase from the cache this.DeleteFromProfileCacheIfExists(username.ToLower()); } }
/// <summary> /// Returns a sorted enumeration of the serializable <see cref="SettingsPropertyValue"/>s. /// </summary> /// <param name="collection">A <see cref="SettingsPropertyValueCollection"/> representing the group of property /// settings to set.</param> /// <returns>A sorted enumeration of the serializable <see cref="SettingsPropertyValue"/>s.</returns> private static IEnumerable<SettingsPropertyValue> GetSerializableSettingsPropertyValues(SettingsPropertyValueCollection collection) { return collection .Cast<SettingsPropertyValue>() .Where(v => v.Property.SerializeAs == SettingsSerializeAs.String || v.Property.SerializeAs == SettingsSerializeAs.Xml) .OrderBy(v => v.Name, StringComparer.Create(CultureInfo.InvariantCulture, false /* ignoreCase */)); }
public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) { string userName = (string)context["UserName"]; if (!string.IsNullOrEmpty(userName)) { data[userName] = collection .Cast<SettingsPropertyValue>() .ToDictionary(x => x.Name, x => x.PropertyValue); } }
/// <summary> /// The set property values. /// </summary> /// <param name="mid"> /// The mid. /// </param> /// <param name="boardId"> /// The board id. /// </param> /// <param name="appname"> /// The appname. /// </param> /// <param name="tableName"> /// The table name. /// </param> /// <param name="userId"> /// The user id. /// </param> /// <param name="userName"> /// The user name. /// </param> /// <param name="collection"> /// The collection. /// </param> /// <param name="dirtyOnly"> /// The dirty only. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// </exception> public static void SetPropertyValues( int? mid, int boardId, string appname, string tableName, int userId, string userName, SettingsPropertyValueCollection collection, bool dirtyOnly = true) { string dataEngine; string connectionString; string namePattern = string.Empty; SqlDbAccess.GetConnectionData(mid, namePattern, out dataEngine, out connectionString); // guest should not be in profile int? userIdG = user_guest(mid, boardId); if (userId <= 0 || userIdG == userId || collection.Count < 1) { return; } bool itemsToSave = true; if (dirtyOnly) { itemsToSave = collection.Cast<SettingsPropertyValue>().Any(pp => pp.IsDirty); } // First make sure we have at least one item to save if (!itemsToSave) { return; } // load the data for the configuration List<SettingsPropertyColumn> spc = LoadFromPropertyValueCollection(mid, collection, tableName); // Save properties to database. if (spc == null || spc.Count <= 0 || !userName.IsSet()) { return; } if (userName.IsNotSet()) { return; } // check if profile exits to select insert or update bool profileExists; string profileExistsSql; switch (dataEngine) { case SqlDbAccess.MsSql: profileExistsSql = MsProfile.ProfileExists; break; case SqlDbAccess.Npgsql: profileExistsSql = PgProfile.ProfileExists; break; case SqlDbAccess.MySql: profileExistsSql = MySqlProfile.ProfileExists; break; case SqlDbAccess.Firebird: profileExistsSql = FbProfile.ProfileExists; break; default: throw new ArgumentOutOfRangeException(dataEngine); } using (var sc = new VzfSqlCommand(mid)) { sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_UserID", userId)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appname)); sc.CommandText.AppendQuery(profileExistsSql.FormatWith(SqlDbAccess.GetVzfObjectName(tableName, mid))); profileExists = Convert.ToInt32(sc.ExecuteScalar(CommandType.Text, true)) > 0; } // create data for saving profile properties string sql; var paramData = new List<Tuple<DbType, string, object>>(); // Build up strings used in the query var columnStr = new StringBuilder(); var valueStr = new StringBuilder(); var setStr = new StringBuilder(); spc.ForEach( column => { if (!collection[column.Settings.Name].IsDirty) return; var nameParam = collection[column.Settings.Name].Name; var valParam = collection[column.Settings.Name].PropertyValue; nameParam = "@i_" + nameParam; paramData.Add(new Tuple<DbType, string, object>(column.DataType, nameParam, valParam)); valueStr.Append(nameParam); valueStr.Append(","); columnStr.Append(column.Settings.Name); columnStr.Append(","); setStr.Append(column.Settings.Name); setStr.Append("="); setStr.Append(nameParam); setStr.Append(","); }); // first predefined parameter without separator columnStr.Append("LastUpdatedDate "); valueStr.Append("@i_LastUpdatedDate"); setStr.Append("LastUpdatedDate=@i_LastUpdatedDate"); paramData.Add(new Tuple<DbType, string, object>(DbType.DateTime, "@i_LastUpdatedDate", DateTime.UtcNow)); columnStr.Append(",LastActivity "); valueStr.Append(",@i_LastActivity"); setStr.Append(",LastActivity=@i_LastActivity"); paramData.Add(new Tuple<DbType, string, object>(DbType.DateTime, "@i_LastActivity", DateTime.UtcNow)); columnStr.Append(",ApplicationName "); valueStr.Append(",@i_ApplicationName"); setStr.Append(",ApplicationName=@i_ApplicationName"); columnStr.Append(",IsAnonymous "); valueStr.Append(",@i_IsAnonymous"); setStr.Append(",IsAnonymous=@i_IsAnonymous"); paramData.Add(new Tuple<DbType, string, object>(DbType.Boolean, "@i_IsAnonymous", false)); columnStr.Append(",UserName "); valueStr.Append(",@i_UserName"); setStr.Append(",UserName=@i_UserName"); paramData.Add(new Tuple<DbType, string, object>(DbType.String, "@i_UserName", userName)); paramData.Add(new Tuple<DbType, string, object>(DbType.Int32, "@i_UserID", userId)); paramData.Add(new Tuple<DbType, string, object>(DbType.String, "@i_ApplicationName", appname)); // start saving... switch (dataEngine) { case SqlDbAccess.MsSql: sql = MsProfile.SetProfileProperties( setStr.ToString(), columnStr.ToString(), valueStr.ToString(), profileExists); break; case SqlDbAccess.Npgsql: sql = PgProfile.SetProfileProperties( setStr.ToString(), columnStr.ToString(), valueStr.ToString(), profileExists); break; case SqlDbAccess.MySql: sql = MySqlProfile.SetProfileProperties( setStr.ToString(), columnStr.ToString(), valueStr.ToString(), profileExists); break; case SqlDbAccess.Firebird: sql = FbProfile.SetProfileProperties( setStr.ToString(), columnStr.ToString(), valueStr.ToString(), profileExists); break; default: throw new ArgumentOutOfRangeException(dataEngine); } using (var sc = new VzfSqlCommand(mid)) { // add parameters in a loop paramData.ForEach( parameter => sc.Parameters.Add(sc.CreateParameter(parameter.Item1, parameter.Item2, parameter.Item3))); sc.CommandText.AppendQuery(sql.FormatWith(SqlDbAccess.GetVzfObjectName(tableName, mid))); sc.ExecuteNonQuery(CommandType.Text, true); } }
/// <summary> /// The encode profile data. /// </summary> /// <param name="collection"> /// The collection. /// </param> /// <param name="isAuthenticated"> /// The is authenticated. /// </param> /// <param name="index"> /// The index. /// </param> /// <param name="stringData"> /// The string data. /// </param> /// <param name="binaryData"> /// The binary data. /// </param> /// <returns> /// The <see cref="int"/>. /// </returns> private static int EncodeProfileData( SettingsPropertyValueCollection collection, bool isAuthenticated, ref string index, ref string stringData, ref byte[] binaryData) { bool itemsToSave = collection.Cast<SettingsPropertyValue>().Where(value => value.IsDirty) .Any(value => !value.Property.Attributes["AllowAnonymous"].Equals(false) || isAuthenticated); // first we need to determine if there are any items that need saving // this is an optimization if (!itemsToSave) { return 0; } var indexBuilder = new StringBuilder(); var stringDataBuilder = new StringBuilder(); var binaryBuilder = new MemoryStream(); int count = 0; // ok, we have some values that need to be saved so we go back through foreach (SettingsPropertyValue value in collection) { // if the value has not been written to and is still using the default value // no need to save it if (value.UsingDefaultValue && !value.IsDirty) { continue; } // we don't save properties that require the user to be authenticated when the // current user is not authenticated. if (value.Property.Attributes["AllowAnonymous"].Equals(false) && !isAuthenticated) { continue; } count++; object propValue = value.SerializedValue; if ((value.Deserialized && value.PropertyValue == null) || value.SerializedValue == null) { indexBuilder.AppendFormat("{0}//0/-1:", value.Name); } else if (propValue is string) { indexBuilder.AppendFormat( "{0}/0/{1}/{2}:", value.Name, stringDataBuilder.Length, (propValue as string).Length); stringDataBuilder.Append(propValue); } else { var binaryValue = (byte[])propValue; indexBuilder.AppendFormat("{0}/1/{1}/{2}:", value.Name, binaryBuilder.Position, binaryValue.Length); binaryBuilder.Write(binaryValue, 0, binaryValue.Length); } } index = indexBuilder.ToString(); stringData = stringDataBuilder.ToString(); binaryData = binaryBuilder.ToArray(); return count; }
public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) { Condition.Requires(context, "context").IsNotNull(); Condition.Requires(collection, "collection").IsNotNull(); var userName = context[UserNameKey] as string; if (string.IsNullOrWhiteSpace(userName)) { return; } this.EnsureSupportedColumns(); var ignoreValues = collection.Cast<SettingsPropertyValue>() .Where(value => !this.databaseColumns.Contains(value.Name)) .Where( value => string.Compare( value.Name, this.membershipProvider.UserEmailColumn, StringComparison.OrdinalIgnoreCase) != 0 && string.Compare( value.Name, this.membershipProvider.UserIdColumn, StringComparison.OrdinalIgnoreCase) != 0) .ToList(); if (ignoreValues.Count > 0) { throw new NotSupportedException("invalid profile property, no matching database column defined."); } if (this.databaseColumns.Count == 0) { return; } var updateValues = collection.Cast<SettingsPropertyValue>() .Where(value => this.databaseColumns.Contains(value.Name)) .ToList(); if (updateValues.Count == 0) { return; } using (var db = this.ConnectToDatabase()) { object[] values; db.Execute(this.sqlQueryBuilder.UpdateUserProfile(updateValues, userName, out values), values); } }
private static void PrepareDataForSaving(ref string propertiesNames, ref string propertiesValuesSerialized, ref byte[] propertiesValuesBinary, SettingsPropertyValueCollection properties, bool userIsAuthenticated) { StringBuilder propertiesNamesBuilder = new StringBuilder(); StringBuilder propertiesValuesSerializedBuilder = new StringBuilder(); MemoryStream propertiesValuesBinarySerialized = new MemoryStream(); try { try { List<SettingsPropertyValue> relevantValues = properties.Cast<SettingsPropertyValue>() .Where(v => v.IsDirty && (userIsAuthenticated || (bool) v.Property.Attributes["AllowAnonymous"])) .ToList(); if (relevantValues.Count == 0) { return; } foreach (SettingsPropertyValue value in relevantValues) { int length; int startPosition = 0; string stringValue = null; if (value.Deserialized && value.PropertyValue == null) { length = -1; } else { if (value.SerializedValue == null) { length = -1; } else { if (value.SerializedValue is string) { stringValue = (string)value.SerializedValue; length = stringValue.Length; startPosition = propertiesValuesSerializedBuilder.Length; } else { byte[] serializedBinary = (byte[])value.SerializedValue; startPosition = (int)propertiesValuesBinarySerialized.Position; propertiesValuesBinarySerialized.Write(serializedBinary, 0, serializedBinary.Length); propertiesValuesBinarySerialized.Position = startPosition + serializedBinary.Length; length = serializedBinary.Length; } } } propertiesNamesBuilder.Append(value.Name + ":"); propertiesNamesBuilder.Append(stringValue != null ? "S" : "B" + ":"); propertiesNamesBuilder.Append(startPosition.ToString(CultureInfo.InvariantCulture) + ":"); propertiesNamesBuilder.Append(length.ToString(CultureInfo.InvariantCulture) + ":"); if (stringValue != null) { propertiesValuesSerializedBuilder.Append(stringValue); } } propertiesValuesBinary = propertiesValuesBinarySerialized.ToArray(); } finally { propertiesValuesBinarySerialized.Close(); } } catch (Exception ex) { throw new ProviderException("Error while prepare data for saving.", ex); } propertiesNames = propertiesNamesBuilder.ToString(); propertiesValuesSerialized = propertiesValuesSerializedBuilder.ToString(); }