Here are the examples of the csharp api System.Collections.IEnumerable.OfType() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3608 Examples
19
View Source File : InterfaceImplementation.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static Type CreateType(Type interfaceType)
{
try
{
TypeBuilder typeBuilder = Impreplacedembly.DefineInterfaceImpType(interfaceType);
List<MemberInfo> allMembers = interfaceType.GetAllInterfaceMembers();
List<MethodInfo> propertyInfos = new List<MethodInfo>();
foreach (PropertyInfo prop in allMembers.OfType<PropertyInfo>())
{
Type propType = prop.PropertyType;
PropertyBuilder propBuilder = typeBuilder.DefineProperty(prop.Name, prop.Attributes, propType, Type.EmptyTypes);
MethodInfo iGetter = prop.GetMethod;
MethodInfo iSetter = prop.SetMethod;
if (iGetter != null)
{
propertyInfos.Add(iGetter);
}
if (iSetter != null)
{
propertyInfos.Add(iSetter);
}
if (prop.Name == "Item")
{
if (iGetter != null)
{
MethodAttributes accessor = iGetter.Attributes;
accessor &= ~MethodAttributes.Abstract;
MethodBuilder methBuilder = typeBuilder.DefineMethod(iGetter.Name, accessor, iGetter.ReturnType, iGetter.GetParameters().Select(e => e.ParameterType).ToArray());
ILGenerator il = methBuilder.GetILGenerator();
il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
il.Emit(OpCodes.Throw);
propBuilder.SetGetMethod(methBuilder);
}
if (iSetter != null)
{
MethodAttributes accessor = iSetter.Attributes;
accessor &= ~MethodAttributes.Abstract;
MethodBuilder methBuilder = typeBuilder.DefineMethod(iSetter.Name, accessor, iSetter.ReturnType, iSetter.GetParameters().Select(e => e.ParameterType).ToArray());
ILGenerator il = methBuilder.GetILGenerator();
il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
il.Emit(OpCodes.Throw);
propBuilder.SetSetMethod(methBuilder);
}
continue;
}
Func<FieldInfo> getBackingField;
{
FieldInfo backingField = null;
getBackingField =
() =>
{
if (backingField == null)
{
backingField = typeBuilder.DefineField("_" + prop.Name + "_" + Guid.NewGuid(), propType, FieldAttributes.Private);
}
return backingField;
};
}
if (iGetter != null)
{
MethodAttributes accessor = iGetter.Attributes;
accessor &= ~MethodAttributes.Abstract;
MethodBuilder methBuilder = typeBuilder.DefineMethod(iGetter.Name, accessor, propType, Type.EmptyTypes);
ILGenerator il = methBuilder.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, getBackingField());
il.Emit(OpCodes.Ret);
propBuilder.SetGetMethod(methBuilder);
}
if (iGetter != null || iSetter != null)
{
MethodAttributes accessor = iSetter != null ? iSetter.Attributes : MethodAttributes.Private;
string name = iSetter != null ? iSetter.Name : "set_" + prop.Name;
accessor &= ~MethodAttributes.Abstract;
MethodBuilder methBuilder = typeBuilder.DefineMethod(name, accessor, typeof(void), new[] { propType });
ILGenerator il = methBuilder.GetILGenerator();
if (iGetter != null)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Stfld, getBackingField());
il.Emit(OpCodes.Ret);
}
else
{
il.Emit(OpCodes.Ret);
}
propBuilder.SetSetMethod(methBuilder);
}
}
foreach (MethodInfo method in allMembers.OfType<MethodInfo>().Except(propertyInfos))
{
MethodBuilder methBuilder = typeBuilder.DefineMethod(method.Name, MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final, method.ReturnType, method.GetParameters().Select(e => e.ParameterType).ToArray());
if (method.IsGenericMethod)
{
methBuilder.DefineGenericParameters(method.GetGenericArguments().Select(e => e.Name).ToArray());
}
ILGenerator il = methBuilder.GetILGenerator();
il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
il.Emit(OpCodes.Throw);
typeBuilder.DefineMethodOverride(methBuilder, method);
}
return typeBuilder.CreateTypeInfo();
}
catch
{
throw BssomSerializationTypeFormatterException.UnsupportedType(interfaceType);
}
}
19
View Source File : FauxDeployCMAgent.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne
License : GNU General Public License v3.0
Project Creator : 1RedOne
public static void SendDiscovery(string CMServerName, string clientName, string domainName, string SiteCode,
string CertPath, SecureString preplaced, SmsClientId clientId, ILog log, bool enumerateAndAddCustomDdr = false)
{
using (MessageCertificateX509Volatile certificate = new MessageCertificateX509Volatile(CertPath, preplaced))
{
//X509Certificate2 thisCert = new X509Certificate2(CertPath, preplaced);
log.Info($"Got SMSID from registration of: {clientId}");
// create base DDR Message
ConfigMgrDataDiscoveryRecordMessage ddrMessage = new ConfigMgrDataDiscoveryRecordMessage
{
// Add necessary discovery data
SmsId = clientId,
ADSiteName = "Default-First-Site-Name", //Changed from 'My-AD-SiteName
SiteCode = SiteCode,
DomainName = domainName,
NetBiosName = clientName
};
ddrMessage.Discover();
// Add our certificate for message signing
ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing);
ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Encryption);
ddrMessage.Settings.HostName = CMServerName;
ddrMessage.Settings.Compression = MessageCompression.Zlib;
ddrMessage.Settings.ReplyCompression = MessageCompression.Zlib;
Debug.WriteLine("Sending [" + ddrMessage.DdrInstances.Count + "] instances of Discovery data to CM");
if (enumerateAndAddCustomDdr)
{
//see current value for the DDR message
var OSSetting = ddrMessage.DdrInstances.OfType<InventoryInstance>().Where(m => m.Clreplaced == "CCM_DiscoveryData");
////retrieve actual setting
string osCaption = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>()
select x.GetPropertyValue("Caption")).FirstOrDefault().ToString();
XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
////retrieve reported value
xmlDoc.LoadXml(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData")?.InstanceDataXml.ToString());
////Set OS to correct setting
xmlDoc.SelectSingleNode("/CCM_DiscoveryData/PlatformID").InnerText = "Microsoft Windows NT Server 10.0";
////Remove the instance
ddrMessage.DdrInstances.Remove(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData"));
CMFauxStatusViewClreplacedesFixedOSRecord FixedOSRecord = new CMFauxStatusViewClreplacedesFixedOSRecord
{
PlatformId = osCaption
};
InventoryInstance instance = new InventoryInstance(FixedOSRecord);
////Add new instance
ddrMessage.DdrInstances.Add(instance);
}
ddrMessage.SendMessage(Sender);
ConfigMgrHardwareInventoryMessage hinvMessage = new ConfigMgrHardwareInventoryMessage();
hinvMessage.Settings.HostName = CMServerName;
hinvMessage.SmsId = clientId;
hinvMessage.Settings.Compression = MessageCompression.Zlib;
hinvMessage.Settings.ReplyCompression = MessageCompression.Zlib;
//hinvMessage.Settings.Security.EncryptMessage = true;
hinvMessage.Discover();
var Clreplacedes = CMFauxStatusViewClreplacedes.GetWMIClreplacedes();
foreach (string Clreplaced in Clreplacedes)
{
try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2", Clreplaced)); }
catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
}
var SMSClreplacedes = new List<string> { "SMS_Processor", "CCM_System", "SMS_LogicalDisk" };
foreach (string Clreplaced in SMSClreplacedes)
{
log.Info($"---Adding clreplaced : [{Clreplaced}]");
try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2\sms", Clreplaced)); }
catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
}
hinvMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing | CertificatePurposes.Encryption);
hinvMessage.Validate(Sender);
hinvMessage.SendMessage(Sender);
};
}
19
View Source File : ObjectManager.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public static void RegisterBehaviour<T>()
{
var behaviours = typeof(T).GetNestedTypes(BindingFlags.Public).Where(x => x.IsSubclreplacedOf(typeof(CustomDecoration)));
var items = typeof(ItemDef).GetNestedTypes(BindingFlags.Public | BindingFlags.Instance).Where(x => x.IsSubclreplacedOf(typeof(Item)));
foreach (Type b in behaviours)
{
DecorationAttribute attr = b.GetCustomAttributes(typeof(DecorationAttribute), false).OfType<DecorationAttribute>().FirstOrDefault();
if (attr == null)
continue;
string poolname = attr.Name;
Type DataStruct = null;
foreach (Type i in items) // Search Item Defination in ItemDef
{
DecorationAttribute[] i_attr = i.GetCustomAttributes(typeof(DecorationAttribute), false).OfType<DecorationAttribute>().ToArray();
if (i_attr == null || i_attr.Length == 0)
continue;
if(i_attr.Contains(attr))
{
DataStruct = i;
break;
}
}
if(DataStruct == null) // Search Item Defination in Behaviour
{
DataStruct = b.GetNestedTypes(BindingFlags.Public).Where(x => x.IsSubclreplacedOf(typeof(Item))).FirstOrDefault();
}
if (DataStruct == null) // Search Item Defination in T
{
DataStruct = typeof(T).GetNestedTypes(BindingFlags.Public).Where(x => x.IsSubclreplacedOf(typeof(Item))).FirstOrDefault();
}
if (DataStruct == null) // Fill with defatult Item
{
Logger.LogWarn($"Could Not Found an Item that match {b.FullName},Attr:{attr.Name},will use default item instance");
DataStruct = typeof(ItemDef.Defaulreplacedem);
}
Register(poolname, b, DataStruct);
}
}
19
View Source File : Inspector.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
private static void _reflectProps(Type t, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance)
{
if (cache_prop.ContainsKey(t))
return;
var propInfos =t.GetProperties(flags)
.Where(x =>
{
var handlers = x.GetCustomAttributes(typeof(HandleAttribute), true).OfType<HandleAttribute>();
bool handflag = handlers.Any();
bool ignoreflag = x.GetCustomAttributes(typeof(InspectIgnoreAttribute), true).OfType<InspectIgnoreAttribute>().Any();
if(handflag && (!ignoreflag))
{
if(!handler.ContainsKey(x))
handler.Add(x, handlers.FirstOrDefault().handleType);
}
return handflag && (!ignoreflag);
});
foreach(var p in propInfos)
{
if(cache_prop.TryGetValue(t,out var npair))
{
npair.Add(p.Name, p);
}
else
{
var d = new Dictionary<string, PropertyInfo>();
d.Add(p.Name, p);
cache_prop.Add(t, d);
}
//Logger.LogDebug($"Cache PropInfo:T:{t},name:{p.Name}");
}
//Logger.LogDebug($"_reflectProp_resutl:{propInfos.ToArray().Length}");
}
19
View Source File : Inspector.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public static void Show()
{
OpLock.Apply();
try
{
Item item = ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().item;
if (!cache_prop.ContainsKey(item.GetType()))
{
_reflectProps(item.GetType());
}
if (cache_prop.TryGetValue(item.GetType(), out var itemProps))
{
var insp = new InspectPanel();
currentEdit = insp;
int idx = 0;
foreach (var kv in itemProps)
{
string name = kv.Key;
Type propType = kv.Value.PropertyType;
object value = kv.Value.GetValue(item, null);
value = Convert.ToSingle(value);
ConstraintAttribute con = kv.Value.GetCustomAttributes(typeof(ConstraintAttribute), true).OfType<ConstraintAttribute>().FirstOrDefault();
LogProp(propType, name, value);
if(idx == 0)
{
insp.UpdateName(idx,name);
if(con is IntConstraint)
{
//Logger.LogDebug($"Check1 {con.Min}-{con.Max}");
insp.UpdateSliderConstrain(name,idx, (float)Convert.ChangeType(con.Min, typeof(float)), Convert.ToInt32(con.Max), true);
}
else if(con is FloatConstraint)
{
//Logger.LogDebug($"Check2 {con.Min}-{con.Max}");
insp.UpdateSliderConstrain(name,idx, (float)(con.Min), (float)(con.Max), false);
}
else
{
throw new ArgumentException();
}
//Logger.LogDebug($"Check3 {value}-{value.GetType()}");
insp.UpdateValue(idx, (float)value);
}
else
{
insp.AppendPropPanel(name);
if (con is IntConstraint)
{
insp.UpdateSliderConstrain(name,idx, (int)con.Min, (int)con.Max, true);
}
else if (con is FloatConstraint)
{
insp.UpdateSliderConstrain(name,idx, (float)con.Min, (float)con.Max, false);
}
else
{
throw new ArgumentException();
}
insp.UpdateValue(idx, (float)value);
insp.UpdateTextDelegate(idx);//insp.AddListener(idx, insp.UpdateTextDelegate(idx));
}
//insp.AddListener(idx, (v) => { kv.Value.SetValue(item, Convert.ChangeType(v, kv.Value.PropertyType), null); });
insp.AddListener(idx, (v) => {
if (ItemManager.Instance.currentSelect == null)
return;
object val;
try
{
if (kv.Value.PropertyType.IsSubclreplacedOf(typeof(Enum)))
{
val = Enum.Parse(kv.Value.PropertyType, v.ToString("0"));
}
else
val = Convert.ChangeType(v, kv.Value.PropertyType);
ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().Setup(handler[kv.Value], val);
}
catch
{
Logger.LogError("Error occour at Inspect OnValue Chnaged");
Hide();
}
});
idx++;
}
}
else
{
Logger.LogError($"KeyNotFount at cache_prop,{item.GetType()}");
}
}
catch(NullReferenceException e)
{
Logger.LogError($"NulRef Error at Inspector.Show:{e}");
OpLock.Undo();
}
}
19
View Source File : ObjectManager.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public static void RegisterSharedBehaviour<T>() where T : CustomDecoration
{
var shareAttr = typeof(T).GetCustomAttributes(typeof(DecorationAttribute), false).OfType<DecorationAttribute>();
foreach(var attr in shareAttr)
{
if (attr == null)
continue;
string poolname = attr.Name;
var ti = typeof(T).GetNestedTypes(BindingFlags.Public).Where(x => x.IsSubclreplacedOf(typeof(Item))).FirstOrDefault();
Register<T>(poolname, ti);
}
}
19
View Source File : SerialBusManager.cs
License : GNU General Public License v3.0
Project Creator : a4004
License : GNU General Public License v3.0
Project Creator : a4004
private static string GetDeviceName(string comPort)
{
try
{
string result = new ManagementObjectSearcher("Select * from Win32_SerialPort")
.Get().OfType<ManagementObject>()
.Where(o => comPort.Equals(o["DeviceID"]))
.First().Properties.OfType<PropertyData>()
.Where(t => t.Name.Equals("Description"))
.First().Value as string;
return result;
}
catch
{
return $"Unknown device ({comPort})";
}
}
19
View Source File : WindowManager.cs
License : GNU General Public License v3.0
Project Creator : a4004
License : GNU General Public License v3.0
Project Creator : a4004
public static void UnmountWindow(Control.ControlCollection parent, Form window)
{
if (window.InvokeRequired)
{
Program.Debug("windowmgr", $"Request to unmount {window.Name} into {parent.Owner.Name} requires control invokation.");
Program.Debug("windowmgr", "Invoking the request on the UI thread.");
window.Invoke(new Action(() => UnmountWindow(parent, window)));
return;
}
foreach (Form w in parent.OfType<Form>().Where(a => a.Handle == window.Handle))
{
Program.Debug("windowmgr", $"Removing window {window.Name} from {parent.Owner.Name}");
parent.Remove(w);
w.Close();
w.Dispose();
}
}
19
View Source File : BitfinexSocketApi.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
private IEnumerable<T> GetRegistrationsOfType<T>()
{
lock(eventListLock)
return eventRegistrations.OfType<T>();
}
19
View Source File : LogManagerTests.cs
License : MIT License
Project Creator : Abc-Arbitrage
License : MIT License
Project Creator : Abc-Arbitrage
[Test]
public void should_return_special_log_event_when_no_more_log_event_are_available()
{
var log = LogManager.GetLogger(typeof(LogManagerTests));
var actualLogEvents = new List<ILogEvent>();
for (var i = 0; i < 10; i++)
{
actualLogEvents.Add(log.Debug());
}
var unavailableEvent = log.Debug();
Check.That(actualLogEvents.OfType<LogEvent>().Count()).Equals(actualLogEvents.Count);
Check.That(unavailableEvent).IsInstanceOf<ForwardingLogEvent>();
var signal = _testAppender.SetMessageCountTarget(actualLogEvents.Count);
for (var i = 0; i < actualLogEvents.Count; i++)
{
var actualLogEvent = actualLogEvents[i];
actualLogEvent.Append(i).Log();
}
signal.Wait(TimeSpan.FromMilliseconds(100));
Check.That(log.Debug()).IsInstanceOf<LogEvent>();
}
19
View Source File : TextArea.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
void leftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null) {
foreach (ITextViewConnect c in e.OldItems.OfType<ITextViewConnect>()) {
c.RemoveFromTextView(textView);
}
}
if (e.NewItems != null) {
foreach (ITextViewConnect c in e.NewItems.OfType<ITextViewConnect>()) {
c.AddToTextView(textView);
}
}
}
19
View Source File : NetworkingTests.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
static void replacedertOneError(List<object> responses, string match = null) {
replacedert.AreEqual(1, responses.Count);
replacedert.IsInstanceOf<IOException>(responses.First());
if (match != null) {
var msg= responses.OfType<IOException>().First().Message;
Stringreplacedert.Contains(match, msg);
}
}
19
View Source File : RichTextBoxHelper.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static void SubscribeToAllHyperlinks(FlowDoreplacedent doc)
{
var hyperlinks = GetVisuals(doc).OfType<Hyperlink>();
foreach (var link in hyperlinks)
{
link.TargetName = null;
link.RequestNavigate += LinkOnClick;
}
}
19
View Source File : RichTextBoxHelper.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static IEnumerable<DependencyObject> GetVisuals(DependencyObject root)
{
foreach (var child in LogicalTreeHelper.GetChildren(root).OfType<DependencyObject>())
{
yield return child;
foreach (var descendants in GetVisuals(child))
{
yield return descendants;
}
}
}
19
View Source File : SystemInfo.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
private static IReadOnlyDictionary<string, string> GetManagementInfo(string query, Regex regex)
{
try
{
var result = new ManagementObjectSearcher(new ObjectQuery(query));
var infoString = string.Empty;
using (var collection = result.Get())
{
foreach (var item in collection)
{
var managementObject = item as ManagementObject;
infoString = managementObject?.GetText(TextFormat.Mof);
if (!string.IsNullOrEmpty(infoString)) break;
}
}
if (string.IsNullOrEmpty(infoString)) return null;
return regex.Matches(infoString).OfType<Match>()
.Where(item => item.Success)
.ToDictionary(item => item.Groups[1].Value, item => item.Groups[2].Value);
}
catch (Exception e)
{
Logger.Error("An unexpected exception occured while getting management info. ", e);
return null;
}
}
19
View Source File : AssessmentProperties.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static HashSet<TResult> GetValues<T, TResult>()
{
var list = typeof(T).GetFields().Select(x => new
{
att = x.GetCustomAttributes(false).OfType<replacedessmentPropertyAttribute>().FirstOrDefault(),
member = x
}).Where(x => x.att != null && x.member.Name != "value__").Select(x => (TResult)x.member.GetValue(null)).ToList();
return new HashSet<TResult>(list);
}
19
View Source File : ClientProperties.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static HashSet<TResult> GetValues<T, TResult>()
{
var list =typeof(T).GetFields().Select(x => new
{
att = x.GetCustomAttributes(false).OfType<ServerOnlyAttribute>().FirstOrDefault(),
member = x
}).Where(x => x.att == null && x.member.Name != "value__").Select(x => (TResult)x.member.GetValue(null)).ToList();
return new HashSet<TResult>(list);
}
19
View Source File : EphemeralProperties.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static HashSet<T> GetValues<T>()
{
var list = typeof(T).GetFields().Select(x => new
{
att = x.GetCustomAttributes(false).OfType<EphemeralAttribute>().FirstOrDefault(),
member = x
}).Where(x => x.att != null && x.member.Name != "value__").Select(x => (T)x.member.GetValue(null)).ToList();
return new HashSet<T>(list);
}
19
View Source File : SendOnLoginProperties.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static HashSet<TResult> GetValues<T, TResult>()
{
var list = typeof(T).GetFields().Select(x => new
{
att = x.GetCustomAttributes(false).OfType<SendOnLoginAttribute>().FirstOrDefault(),
member = x
}).Where(x => x.att != null && x.member.Name != "value__").Select(x => (TResult)x.member.GetValue(null)).ToList();
return new HashSet<TResult>(list);
}
19
View Source File : ServerOnlyProperties.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static HashSet<TResult> GetValues<T, TResult>()
{
var list = typeof(T).GetFields().Select(x => new
{
att = x.GetCustomAttributes(false).OfType<ServerOnlyAttribute>().FirstOrDefault(),
member = x
}).Where(x => x.att != null && x.member.Name != "value__").Select(x => (TResult)x.member.GetValue(null)).ToList();
return new HashSet<TResult>(list);
}
19
View Source File : ObjectMaint.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public List<Creature> GetVisibleObjectsValuesOfTypeCreature()
{
rwLock.EnterReadLock();
try
{
return VisibleObjects.Values.Select(v => v.WeenieObj.WorldObject).OfType<Creature>().ToList();
}
finally
{
rwLock.ExitReadLock();
}
}
19
View Source File : ObjectMaint.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public List<Player> GetKnownPlayersValuesAsPlayer()
{
rwLock.EnterReadLock();
try
{
return KnownPlayers.Values.Select(v => v.WeenieObj.WorldObject).OfType<Player>().ToList();
}
finally
{
rwLock.ExitReadLock();
}
}
19
View Source File : ObjectMaint.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public List<Creature> GetKnownObjectsValuesAsCreature()
{
rwLock.EnterReadLock();
try
{
return KnownObjects.Values.Select(v => v.WeenieObj.WorldObject).OfType<Creature>().ToList();
}
finally
{
rwLock.ExitReadLock();
}
}
19
View Source File : ObjectMaint.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public List<Creature> GetVisibleTargetsValuesOfTypeCreature()
{
rwLock.EnterReadLock();
try
{
return VisibleTargets.Values.Select(v => v.WeenieObj.WorldObject).OfType<Creature>().ToList();
}
finally
{
rwLock.ExitReadLock();
}
}
19
View Source File : Container.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public int GetFreeInventorySlots(bool includeSidePacks = true)
{
int freeSlots = (ItemCapacity ?? 0) - CountPackItems();
if (includeSidePacks)
{
foreach (var sidePack in Inventory.Values.OfType<Container>())
freeSlots += (sidePack.ItemCapacity ?? 0) - sidePack.CountPackItems();
}
return freeSlots;
}
19
View Source File : Container.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public bool TryAddToInventory(WorldObject worldObject, out Container container, int placementPosition = 0, bool limitToMainPackOnly = false, bool burdenCheck = true)
{
// bug: should be root owner
if (this is Player player && burdenCheck)
{
if (!player.HasEnoughBurdenToAddToInventory(worldObject))
{
container = null;
return false;
}
}
IList<WorldObject> containerItems;
if (worldObject.UseBackpackSlot)
{
containerItems = Inventory.Values.Where(i => i.UseBackpackSlot).ToList();
if ((ContainerCapacity ?? 0) <= containerItems.Count)
{
container = null;
return false;
}
}
else
{
containerItems = Inventory.Values.Where(i => !i.UseBackpackSlot).ToList();
if ((ItemCapacity ?? 0) <= containerItems.Count)
{
// Can we add this to any side pack?
if (!limitToMainPackOnly)
{
var containers = Inventory.Values.OfType<Container>().ToList();
containers.Sort((a, b) => (a.Placement ?? 0).CompareTo(b.Placement ?? 0));
foreach (var sidePack in containers)
{
if (sidePack.TryAddToInventory(worldObject, out container, placementPosition, true))
{
EnreplacedbranceVal += (worldObject.EnreplacedbranceVal ?? 0);
Value += (worldObject.Value ?? 0);
return true;
}
}
}
container = null;
return false;
}
}
if (Inventory.ContainsKey(worldObject.Guid))
{
container = null;
return false;
}
worldObject.Location = null;
worldObject.Placement = ACE.Enreplacedy.Enum.Placement.Resting;
worldObject.OwnerId = Guid.Full;
worldObject.ContainerId = Guid.Full;
worldObject.Container = this;
worldObject.PlacementPosition = placementPosition; // Server only variable that we use to remember/restore the order in which items exist in a container
// Move all the existing items PlacementPosition over.
if (!worldObject.UseBackpackSlot)
containerItems.Where(i => !i.UseBackpackSlot && i.PlacementPosition >= placementPosition).ToList().ForEach(i => i.PlacementPosition++);
else
containerItems.Where(i => i.UseBackpackSlot && i.PlacementPosition >= placementPosition).ToList().ForEach(i => i.PlacementPosition++);
Inventory.Add(worldObject.Guid, worldObject);
EnreplacedbranceVal += (worldObject.EnreplacedbranceVal ?? 0);
Value += (worldObject.Value ?? 0);
container = this;
OnAddItem();
return true;
}
19
View Source File : TemplateTokenExtensions.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static bool CheckHasRequiredContext(
this TemplateToken token,
IReadOnlyObject expressionValues,
IList<IFunctionInfo> expressionFunctions)
{
var expressionTokens = token.Traverse()
.OfType<BasicExpressionToken>()
.ToArray();
var parser = new ExpressionParser();
foreach (var expressionToken in expressionTokens)
{
var tree = parser.ValidateSyntax(expressionToken.Expression, null);
foreach (var node in tree.Traverse())
{
if (node is NamedValue namedValue)
{
if (expressionValues?.Keys.Any(x => string.Equals(x, namedValue.Name, StringComparison.OrdinalIgnoreCase)) != true)
{
return false;
}
}
else if (node is Function function &&
!ExpressionConstants.WellKnownFunctions.ContainsKey(function.Name) &&
expressionFunctions?.Any(x => string.Equals(x.Name, function.Name, StringComparison.OrdinalIgnoreCase)) != true)
{
return false;
}
}
}
return true;
}
19
View Source File : CustomTreeListBoxItemAdapter.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : Actipro
public override void OnDrop(DragEventArgs e, TreeListBox targetControl, object targereplacedem, TreeItemDropArea dropArea) {
var originalEffects = e.Effects;
e.Effects = DragDropEffects.None;
// If the drag is over an item and there is item data present...
var targetModel = targereplacedem as ToolboxTreeNodeModel;
if ((targetModel != null) && (dropArea != TreeItemDropArea.None) && (e.Data.GetDataPresent(TreeListBox.ItemDataFormat))) {
// Resolve the real target item (in case the drop area is above or below the target item)
var targetDropIndex = targetModel.Children.Count;
switch (dropArea) {
case TreeItemDropArea.Before:
case TreeItemDropArea.After:
// When dropping before or after, a new node will be inserted as a child to the parent of the target
var nav = targetControl.GereplacedemNavigator(targereplacedem);
if (nav != null) {
// Cache the original target
var targetChildModel = targetModel;
// Quit if unable to move to navigate to the parent
if (!nav.GoToParent())
return;
// Update the target item to be the parent of the original target
targereplacedem = nav.Currenreplacedem;
targetModel = targereplacedem as ToolboxTreeNodeModel;
// Quit if the new target is not the expected model
if (targetModel == null)
return;
// Resolve index of the new node based on whether it should be before
// or after the original target.
var index = targetModel.Children.IndexOf(targetChildModel);
if (index != -1)
targetDropIndex = index + (dropArea == TreeItemDropArea.After ? 1 : 0);
}
break;
}
// Resolve the category for the drop target
if (!TryGetCategory(targetControl, targetModel, out var targetCategoryModel)) {
MessageBox.Show("Unable to determine the drop category.", "Drag and Drop", MessageBoxButton.OK);
return;
}
// Get the dragged controls (only control nodes are currently supported)
List<ControlTreeNodeModel> sourceControlModels = GetDraggedModels(e.Data, targetControl)
.OfType<ControlTreeNodeModel>()
.ToList();
if (sourceControlModels.Count > 0) {
// Check each item and validate that various drop operations are allowed before actually executing the drop
foreach (var sourceModel in sourceControlModels) {
if (sourceModel == targetModel) {
MessageBox.Show("Cannot drop an item on itself.", "Drag and Drop", MessageBoxButton.OK);
return;
}
else {
var nav = targetControl.GereplacedemNavigator(sourceModel);
if (nav == null) {
MessageBox.Show("Cannot drop from a different control.", "Drag and Drop", MessageBoxButton.OK);
return;
}
else {
if (nav.GoToCommonAncestor(targereplacedem)) {
if (nav.Currenreplacedem == sourceModel) {
MessageBox.Show("Cannot drop onto a descendant item.", "Drag and Drop", MessageBoxButton.OK);
return;
}
}
}
}
}
// Only support a single effect (you could add support for other effects like Copy if the Ctrl key is down here)
if ((originalEffects & DragDropEffects.Move) == DragDropEffects.Move) {
e.Effects = DragDropEffects.Move;
e.Handled = true;
}
else if ((originalEffects & DragDropEffects.Copy) == DragDropEffects.Copy) {
e.Effects = DragDropEffects.Copy;
e.Handled = true;
}
if (IsFavoritesCategory(targetCategoryModel)) {
// Controls dragged into favorites category will not actually be moved. They will be added as favorites.
foreach (var sourceControlModel in sourceControlModels)
sourceControlModel.IsFavorite = true;
}
else {
// Complete operation
bool isMove = e.Effects == DragDropEffects.Move;
foreach (var sourceControlModel in sourceControlModels) {
// Resolve the source category of the dragged control
if (!TryGetCategory(targetControl, sourceControlModel, out var sourceCategoryModel))
break;
if (isMove) {
// Remove the control from the original category
var index = sourceCategoryModel.Children.IndexOf(sourceControlModel);
if (index != -1) {
if ((sourceCategoryModel == targetCategoryModel) && (index < targetDropIndex))
targetDropIndex--;
sourceCategoryModel.Children.RemoveAt(index);
}
else {
// Quit processing if any source cannot be located
break;
}
// Add the control to the new category (may be the same as the source if it was repositioned)
int resolvedTargetDropIndex = Math.Max(0, Math.Min(targetCategoryModel.Children.Count, targetDropIndex++));
targetCategoryModel.Children.Insert(resolvedTargetDropIndex, sourceControlModel);
targetCategoryModel.IsExpanded = true;
// Focus the last item that was moved
if (sourceControlModels[sourceControlModels.Count - 1] == sourceControlModel) {
// Must dispatch the focus changes to allow the view to update based on changes in the models
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => {
targetControl.FocusItem(sourceControlModel);
}), DispatcherPriority.Normal);
}
}
}
}
}
}
}
19
View Source File : EmployeeModel.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : Actipro
private void UpdateTotalTaskHours() {
this.TotalTaskHours = tasks.OfType<ServiceModel>().Sum(o => o.Hours);
}
19
View Source File : SymbolAnalyzersAggregator.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private void replacedyzeSymbolHandleAggregateException(SymbolreplacedysisContext context, PXContext pxContext)
{
try
{
replacedyzeSymbol(context, pxContext);
}
catch (AggregateException e)
{
var operationCanceledException = e.InnerExceptions
.OfType<OperationCanceledException>()
.FirstOrDefault();
if (operationCanceledException != null)
{
throw operationCanceledException;
}
throw;
}
}
19
View Source File : DacMissingPrimaryKeyFix.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private MethodDeclarationSyntax MakeFindMethodNode(SyntaxGenerator generator, PXContext pxContext, DacSemanticModel dacSemanticModel,
List<DacPropertyInfo> dacKeys)
{
var returnType = generator.TypeExpression(dacSemanticModel.Symbol);
var parameters = MakeParameterNodesForFindMethod(generator, pxContext, dacSemanticModel, dacKeys);
var findMethodNode = generator.MethodDeclaration(DelegateNames.PrimaryKeyFindMethod, parameters,
typeParameters: null, returnType,
Accessibility.Public, DeclarationModifiers.Static) as MethodDeclarationSyntax;
if (findMethodNode.Body != null)
findMethodNode = findMethodNode.RemoveNode(findMethodNode.Body, SyntaxRemoveOptions.KeepNoTrivia);
var findByCallArguments = parameters.OfType<ParameterSyntax>()
.Select(parameter => Argument(
IdentifierName(parameter.Identifier)));
var findByInvocation =
generator.InvocationExpression(
IdentifierName(DelegateNames.PrimaryKeyFindByMethod), findByCallArguments) as InvocationExpressionSyntax;
bool statementTooLongForOneLine = dacKeys.Count > MaxNumberOfKeysForOneLineStatement;
if (statementTooLongForOneLine)
{
var trivia = dacSemanticModel.Node.GetLeadingTrivia()
.Add(Whitespace("\t\t"))
.Where(trivia => trivia.IsKind(SyntaxKind.WhitespaceTrivia));
findByInvocation = findByInvocation.WithLeadingTrivia(trivia);
}
var arrowExpression = ArrowExpressionClause(findByInvocation);
if (statementTooLongForOneLine)
{
arrowExpression = arrowExpression.WithArrowToken(
Token(SyntaxKind.EqualsGreaterThanToken)
.WithTrailingTrivia(Whitespace(" "), EndOfLine(Environment.NewLine)));
}
return findMethodNode.WithExpressionBody(arrowExpression)
.WithSemicolonToken(
Token(SyntaxKind.SemicolonToken));
}
19
View Source File : DefaultCodeMapTreeBuilder_Graph.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
protected virtual IEnumerable<TreeNodeViewModel> CreateGraphCategoryChildren<TSymbolInfo>(GraphMemberCategoryNodeViewModel graphMemberCategory,
Func<TSymbolInfo, TreeNodeViewModel> constructor)
where TSymbolInfo : SymbolItem
{
IEnumerable<SymbolItem> categoryTreeNodes = graphMemberCategory.CheckIfNull(nameof(graphMemberCategory))
.GetCategoryGraphNodeSymbols();
if (categoryTreeNodes.IsNullOrEmpty())
return DefaultValue;
Cancellation.ThrowIfCancellationRequested();
var graphSemanticModel = graphMemberCategory.GraphSemanticModel;
var graphMemberViewModels = from graphMemberInfo in categoryTreeNodes.OfType<TSymbolInfo>()
where graphMemberInfo.SymbolBase.ContainingType == graphSemanticModel.Symbol ||
graphMemberInfo.SymbolBase.ContainingType.OriginalDefinition == graphSemanticModel.Symbol.OriginalDefinition
select constructor(graphMemberInfo);
return graphMemberViewModels;
}
19
View Source File : VisualTreeUtils.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
public static IEnumerable<FrameworkElement> GetVisualDescendants(this FrameworkElement uiElement)
{
uiElement.ThrowOnNull(nameof(uiElement));
int elementChildrenCount = VisualTreeHelper.GetChildrenCount(uiElement);
if (elementChildrenCount == 0)
return Enumerable.Empty<FrameworkElement>();
return GetVisualDescendantsImpl(uiElement, elementChildrenCount);
//-------------------------------------------Local function-----------------------------------
IEnumerable<FrameworkElement> GetVisualDescendantsImpl(FrameworkElement parent, int childrenCount)
{
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i) as FrameworkElement;
if (child == null)
continue;
yield return child;
int grandchildrenCount = VisualTreeHelper.GetChildrenCount(child);
foreach (var descendant in GetVisualDescendantsImpl(child, grandchildrenCount).OfType<FrameworkElement>())
{
yield return descendant;
}
}
}
}
19
View Source File : TypeExtensions.cs
License : MIT License
Project Creator : adamant
License : MIT License
Project Creator : adamant
public static bool HasCustomAttribute<TAttribute>(this Type type)
{
return type.GetCustomAttributes(true).OfType<TAttribute>().Any();
}
19
View Source File : LexicalScopesBuilderWalker.cs
License : MIT License
Project Creator : adamant
License : MIT License
Project Creator : adamant
private static LexicalScope BuildBodyScope(
IEnumerable<IConstructorParameterSyntax> parameters,
LexicalScope containingScope)
{
var symbols = parameters.OfType<INamedParameterSyntax>()
.GroupBy(p => p.Name, p => p.Symbol)
.ToFixedDictionary(e => (TypeName)e.Key, e => e.ToFixedSet<IPromise<Symbol>>());
return NestedScope.Create(containingScope, symbols);
}
19
View Source File : AssemblyExtensions.cs
License : Apache License 2.0
Project Creator : adamralph
License : Apache License 2.0
Project Creator : adamralph
public static string GetVersion(this replacedembly replacedembly) =>
replacedembly.GetCustomAttributes(false).OfType<replacedemblyInformationalVersionAttribute>().FirstOrDefault()?.InformationalVersion ?? "Unknown";
19
View Source File : RxContentPage.cs
License : MIT License
Project Creator : adospace
License : MIT License
Project Creator : adospace
public void Add(VisualNode child)
{
if (child is IRxView && _contents.OfType<IRxView>().Any())
throw new InvalidOperationException("Content already set");
_contents.Add(child);
}
19
View Source File : FabricHelper.cs
License : MIT License
Project Creator : adospace
License : MIT License
Project Creator : adospace
private static void OnTextColumnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is DataGrid dataGrid))
throw new InvalidOperationException("TextColumnStyle property works only on DataGrid");
if (e.OldValue == null && e.NewValue != DependencyProperty.UnsetValue)
{
foreach (var textColumn in dataGrid.Columns
.OfType<DataGridTextColumn>()
//.Where(_ => _.EditingElementStyle == null)
)
{
textColumn.EditingElementStyle = GetTextColumnStyle(dataGrid);
}
dataGrid.Columns.CollectionChanged += (s, eventArgs) =>
{
if (eventArgs.NewItems != null)
{
foreach (var textColumn in eventArgs.NewItems
.OfType<DataGridTextColumn>()
//.Where(_ => _.EditingElementStyle == null)
)
{
textColumn.EditingElementStyle = GetTextColumnStyle(dataGrid);
}
}
};
}
}
19
View Source File : FabricHelper.cs
License : MIT License
Project Creator : adospace
License : MIT License
Project Creator : adospace
private static void OnComboBoxColumnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is DataGrid dataGrid))
throw new InvalidOperationException("ComboBoxColumnStyle property works only on DataGrid");
if (e.OldValue == null && e.NewValue != DependencyProperty.UnsetValue)
{
foreach (var textColumn in dataGrid.Columns
.OfType<DataGridComboBoxColumn>()
//.Where(_ => _.EditingElementStyle == null)
)
{
textColumn.EditingElementStyle = GetComboBoxColumnStyle(dataGrid);
}
dataGrid.Columns.CollectionChanged += (s, eventArgs) =>
{
if (eventArgs.NewItems != null)
{
foreach (var comboBoxColumn in eventArgs.NewItems
.OfType<DataGridComboBoxColumn>()
//.Where(_ => _.EditingElementStyle == null)
)
{
comboBoxColumn.EditingElementStyle = GetComboBoxColumnStyle(dataGrid);
}
}
};
}
}
19
View Source File : FabricHelper.cs
License : MIT License
Project Creator : adospace
License : MIT License
Project Creator : adospace
private static void OnCheckBoxColumnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is DataGrid dataGrid))
throw new InvalidOperationException("CheckBoxColumnStyle or CheckBoxColumnEditingStyle property works only on DataGrid");
if (e.OldValue == null && e.NewValue != DependencyProperty.UnsetValue)
{
foreach (var textColumn in dataGrid.Columns
.OfType<DataGridCheckBoxColumn>()
//.Where(_ => _.EditingElementStyle == null)
)
{
textColumn.ElementStyle =
GetCheckBoxColumnStyle(dataGrid);
textColumn.EditingElementStyle =
GetCheckBoxColumnEditingStyle(dataGrid);
}
dataGrid.Columns.CollectionChanged += (s, eventArgs) =>
{
if (eventArgs.NewItems != null)
{
foreach (var CheckBoxColumn in eventArgs.NewItems
.OfType<DataGridCheckBoxColumn>()
//.Where(_ => _.EditingElementStyle == null)
)
{
CheckBoxColumn.EditingElementStyle = GetCheckBoxColumnStyle(dataGrid);
}
}
};
}
}
19
View Source File : CertificateExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IEnumerable<X509Certificate2> FindCertificatesByThumbprint(this IEnumerable<string> thumbprints, bool findByTimeValid = true, bool validOnly = false)
{
var certificates = thumbprints
.Where(thumbprint => !string.IsNullOrWhiteSpace(thumbprint))
.SelectMany(thumbprint => thumbprint.FindCertificatesByThumbprint(findByTimeValid, validOnly).OfType<X509Certificate2>());
return certificates;
}
19
View Source File : OrganizationServiceCacheServiceBehavior.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
serviceDescription.ThrowOnNull("serviceDescription");
serviceHostBase.ThrowOnNull("serviceHostBase");
var sb = serviceDescription.Behaviors.Find<ServiceBehaviorAttribute>();
foreach (var ed in serviceHostBase.ChannelDispatchers.OfType<ChannelDispatcher>().SelectMany(cd => cd.Endpoints))
{
if (sb != null && sb.InstanceContextMode == InstanceContextMode.Single)
{
ed.DispatchRuntime.SingletonInstanceContext = new InstanceContext(serviceHostBase);
}
ed.DispatchRuntime.InstanceProvider = new OrganizationServiceCacheServiceInstanceProvider(_cache);
}
}
19
View Source File : ContentMap.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public ContentSnippetNode GetSnippetNode(string name, ContextLanguageInfo language)
{
IDictionary<EnreplacedyReference, EnreplacedyNode> snippets;
// Note: Content snippets can have a language matching the current language, or they can have no language and apply for all languages
var userLanguageEnreplacedy = language == null || !language.IsCrmMultiLanguageEnabled ? null : language.ContextLanguage.EnreplacedyReference;
if (this.TryGetValue("adx_contentsnippet", out snippets))
{
var snippet = GetSnippetNode(snippets.Values.OfType<ContentSnippetNode>(), name, language);
ADXTrace.Instance.TraceInfo(
TraceCategory.Application,
snippet == null
? string.Format(
"Does not exist: SnippetName={0}, UserLanguageId={1}, UserLanguageName={2}",
name,
userLanguageEnreplacedy == null ? null : userLanguageEnreplacedy.Id.ToString(),
userLanguageEnreplacedy == null ? null : userLanguageEnreplacedy.Name)
: string.Format(
"Exist: SnippetName={0}, UserLanguageId={1}, UserLanguageName={2}, SnippetLanguageId={3}, SnippetLanguageName={4}",
name,
userLanguageEnreplacedy == null ? null : userLanguageEnreplacedy.Id.ToString(),
userLanguageEnreplacedy == null ? null : userLanguageEnreplacedy.Name,
snippet.Language == null ? null : snippet.Language.Id.ToString(),
snippet.Language == null ? null : snippet.Language.Name));
return snippet;
}
ADXTrace.Instance.TraceInfo(
TraceCategory.Application,
string.Format(
"No content snippets found. SnippetName={0}, UserLanguageId={1}, UserLanguageName={2}",
name,
userLanguageEnreplacedy == null ? null : userLanguageEnreplacedy.Id.ToString(),
userLanguageEnreplacedy == null ? null : userLanguageEnreplacedy.Name));
return null;
}
19
View Source File : CrmChangeTrackingManager.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private bool ChangesBelongsToWebsite(IGrouping<Guid, IChangedItem> groupedChanges, CrmDbContext context, Guid websiteId)
{
var enreplacedyId = groupedChanges.Key;
var enreplacedyName = this.GetEnreplacedyNameFromChangedItem(groupedChanges.First());
if (string.Equals("adx_website", enreplacedyName, StringComparison.OrdinalIgnoreCase))
{
return websiteId == enreplacedyId;
}
// if enreplacedy hasn't relationship with website or enreplacedy was deleted -> mark as `belongs to website`
EnreplacedyTrackingInfo info;
if (groupedChanges.Any(gc => gc.Type == ChangeType.RemoveOrDeleted)
|| !enreplacedyInfoList.TryGetValue(enreplacedyName, out info)
|| info.WebsiteLookupAttribute == null)
{
return true;
}
// trying to get website's id from changed items
var itemWithWebsiteIdValue = groupedChanges
.OfType<NewOrUpdatedItem>()
.FirstOrDefault(item => item.NewOrUpdatedEnreplacedy.Contains(info.WebsiteLookupAttribute));
// if all changes doesn't contain website lookup attribute but we know that enreplacedy should have it then try to get value from service context
var updatedEnreplacedy = itemWithWebsiteIdValue != null
? itemWithWebsiteIdValue.NewOrUpdatedEnreplacedy
: context.Service.RetrieveSingle(new EnreplacedyReference(enreplacedyName, enreplacedyId), new ColumnSet(info.WebsiteLookupAttribute));
return updatedEnreplacedy?.GetAttributeValue<EnreplacedyReference>(info.WebsiteLookupAttribute)?.Id == websiteId;
}
19
View Source File : Saml2ConfigurationManager.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static async Task<WsFederationConfiguration> GetConfigurationAsync(string address, IDoreplacedentRetriever retriever, CancellationToken cancel)
{
var doreplacedent = await retriever.GetDoreplacedentAsync(address, cancel);
var configuration = new WsFederationConfiguration();
using (var sr = new StringReader(doreplacedent))
using (var xr = XmlReader.Create(sr, _settings))
{
var serializer = new MetadataSerializer { CertificateValidationMode = X509CertificateValidationMode.None };
var enreplacedyDescriptor = serializer.ReadMetadata(xr) as EnreplacedyDescriptor;
if (enreplacedyDescriptor != null)
{
configuration.Issuer = enreplacedyDescriptor.EnreplacedyId.Id;
var idpssod = enreplacedyDescriptor.RoleDescriptors.OfType<IdenreplacedyProviderSingleSignOnDescriptor>().FirstOrDefault();
if (idpssod != null)
{
var redirectBinding = idpssod.SingleSignOnServices.FirstOrDefault(ssos => ssos.Binding == ProtocolBindings.HttpRedirect);
if (redirectBinding != null)
{
configuration.TokenEndpoint = redirectBinding.Location.OriginalString;
}
var keys = idpssod.Keys
.Where(key => key.KeyInfo != null && (key.Use == KeyType.Signing || key.Use == KeyType.Unspecified))
.SelectMany(key => key.KeyInfo.OfType<X509RawDataKeyIdentifierClause>())
.Select(clause => new X509SecurityKey(new X509Certificate2(clause.GetX509RawData())));
foreach (var key in keys)
{
configuration.SigningKeys.Add(key);
}
}
}
}
return configuration;
}
19
View Source File : PersistCachedRequestsJob.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected override void ExecuteInternal(Guid id)
{
var exceptions = new List<Exception>();
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.Cache, PerformanceMarkerArea.Cms, PerformanceMarkerTagName.PersistCachedRequests))
{
this.Settings.AppDataRetryPolicy.DirectoryCreate(this.AppDataFullPath);
// find cached requests for writing to disk
foreach (var telemetry in this.ObjectCache.Select(item => item.Value).OfType<CacheItemTelemetry>())
{
if (telemetry.Request != null)
{
this.Save(this.AppDataFullPath, telemetry);
}
}
// cleanup exipired files
var directory = this.Settings.AppDataRetryPolicy.GetDirectory(this.AppDataFullPath);
var files = this.Settings.AppDataRetryPolicy.GetFiles(directory, this.Settings.FilenameFormat.FormatWith("*"));
var expiresOn = DateTimeOffset.UtcNow - this.Settings.ExpirationWindow;
foreach (var file in files)
{
try
{
var expired = file.LastWriteTimeUtc < expiresOn;
if (expired)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Deleting: " + file.FullName);
this.Settings.AppDataRetryPolicy.FileDelete(file);
}
}
catch (Exception e)
{
WebEventSource.Log.GenericWarningException(e);
if (this.Settings.PropagateExceptions)
{
exceptions.Add(e);
}
}
}
}
if (this.Settings.PropagateExceptions && exceptions.Any())
{
throw new AggregateException(exceptions);
}
}
19
View Source File : CrmChart.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private string ReplacePresentationDescriptionOptionSetPlaceholderMatch(Match match, OrganizationServiceContext serviceContext)
{
var optionSetName = match.Groups["optionSetName"].Value;
var optionSetValue = match.Groups["optionSetValue"].Value;
var optionSetAttributeMetadata = this.PrimaryEnreplacedyMetadata.Attributes
.OfType<EnumAttributeMetadata>()
.FirstOrDefault(e => e.OptionSet != null && string.Equals(optionSetName, e.OptionSet.Name, StringComparison.OrdinalIgnoreCase));
if (optionSetAttributeMetadata != null)
{
return this.GetOptionSetValueLabel(optionSetAttributeMetadata.OptionSet, optionSetValue);
}
OptionSetMetadata optionSet;
try
{
var retrieveOptionSetResponse = (RetrieveOptionSetResponse)serviceContext.Execute(new RetrieveOptionSetRequest
{
Name = optionSetName
});
optionSet = retrieveOptionSetResponse.OptionSetMetadata as OptionSetMetadata;
}
catch (FaultException<OrganizationServiceFault>)
{
return optionSetValue;
}
if (optionSet == null)
{
return optionSetValue;
}
return this.GetOptionSetValueLabel(optionSet, optionSetValue);
}
19
View Source File : CacheDependencyCalculator.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
internal IEnumerable<string> GetDependencies(Enreplacedy enreplacedy, bool isSingle)
{
foreach (var dependency in this.GetDependencies(enreplacedy.ToEnreplacedyReference(), isSingle))
{
yield return dependency;
}
// Looks for Enreplacedy references (lookups) in enreplacedy.Attributes and adds dependencies, so when
// a lookup changes, a main enreplacedy also gets invalidated. Like Incident and changing Subject name.
var attributesLookups = enreplacedy.Attributes.Values.OfType<EnreplacedyReference>();
foreach (var lookup in attributesLookups)
{
foreach (var related in this.GetDependencies(lookup, true))
{
yield return related;
}
}
// walk the related enreplacedies
foreach (var related in this.GetDependencies(enreplacedy.RelatedEnreplacedies, isSingle))
{
yield return related;
}
// If the enreplacedy is also an Activity, then add dependency to activitypointer.
EnreplacedyReference activityDependency;
if (this.IsActivityEnreplacedy(enreplacedy, out activityDependency))
{
foreach (var dependency in this.GetDependencies(activityDependency, isSingle))
{
yield return dependency;
}
}
}
19
View Source File : PortalViewContext.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public bool IsAncestorSiteMapNode(SiteMapNode siteMapNode, bool excludeRootNodes = false)
{
if (siteMapNode == null)
{
return false;
}
var enreplacedyNode = siteMapNode as CrmSiteMapNode;
if (enreplacedyNode == null || enreplacedyNode.Enreplacedy == null)
{
return IsAncestorSiteMapNode(siteMapNode.Url);
}
var currentNodeAncestors = CurrentSiteMapNodeAncestors;
if (currentNodeAncestors.Length < 1)
{
return false;
}
var nodeEnreplacedyReference = enreplacedyNode.Enreplacedy.ToEnreplacedyReference();
var root = currentNodeAncestors.Last();
foreach (var ancestor in currentNodeAncestors.OfType<CrmSiteMapNode>())
{
if (ancestor.Enreplacedy == null)
{
continue;
}
if (ancestor.Enreplacedy.ToEnreplacedyReference().Equals(nodeEnreplacedyReference))
{
return !(excludeRootNodes && ancestor.Equals(root));
}
}
return false;
}
19
View Source File : PortalViewContext.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public bool IsAncestorSiteMapNode(EnreplacedyReference enreplacedyReference, bool excludeRootNodes = false)
{
if (enreplacedyReference == null)
{
return false;
}
var currentNodeAncestors = CurrentSiteMapNodeAncestors;
if (currentNodeAncestors.Length < 1)
{
return false;
}
var root = currentNodeAncestors.Last();
foreach (var ancestor in currentNodeAncestors.OfType<CrmSiteMapNode>())
{
if (ancestor.Enreplacedy == null)
{
continue;
}
if (ancestor.Enreplacedy.ToEnreplacedyReference().Equals(enreplacedyReference))
{
return !(excludeRootNodes && ancestor.Equals(root));
}
}
return false;
}
See More Examples