public static ISendInfo CreateSink(dynamic typeName, dynamic configuration) { try { Logger.Debug("CreateSink"); Logger.DebugFormat("trying to create a sink of type {@typeName} with configuration {@configuration}", (object)typeName.ToString(), (object)configuration.ToString()); var type = FindType(typeName.ToString(),Sinks); if (type == null) { Logger.ErrorFormat( "could not find any type with name : {@typeName} implementing ISendInfo interface. Make sure the assembly is under the modules directory and that the class implements the ISendInfo interface!", (object)typeName.ToString()); throw new ArgumentException("typeName"); } var retval = (ISendInfo) Activator.CreateInstance(type); retval.Configure(configuration); Logger.DebugFormat("sink {@typeName} created!", (object)typeName.ToString()); return retval; } catch (Exception ex) { Logger.ErrorFormat("error instantiating {@typeName} : {@exception}", (object)typeName.ToString(), ex); throw; } }
static void BindHeaders(dynamic source, TemplateModel model) { if (HasMember(source, "Subject")) model.Subject = source.Subject; if (HasMember(source, "From")) { var from = source.From; if (HasMember(from, "Name")) model.From.Name = from.Name; if (HasMember(from, "Email")) model.From.Email = from.Email; } if (HasEnumeration(source, "To")) { foreach (var address in source.To) { var name = ""; var email = ""; if (HasMember(address, "Name")) name = address.Name; if (HasMember(address, "Email")) email = address.Email; model.To.Add(new Address { Name = name, Email = email }); } } }
public BaseDnsRecord Read(dynamic data) { var ns = new NsDnsRecord(); ns.Nsdname = data.Nsdname; return ns; }
private static object CleanupSsh(dynamic parm) { string userRegex = parm["user_regex"].Value; string userName = userRegex.Remove(0, 1); userName = userName.Remove(userName.Length - 1, 1); SshResult sshResult = new SshResult(); sshResult.Command = "cleanup"; Logger.Info("Cleaning up SSH"); try { WindowsVCAPUsers.DeleteUser(userName); File.Delete(Path.Combine(Config.BaseDir, "bosh", "salt", userName + ".salt")); Logger.Info("Deleted salt file"); sshResult.Status = "success"; Logger.Info("Deleted user for SSH"); SshdMonitor.StopSshd(); } catch (Exception ex) { Logger.Error("Failed to delete user " + ex.ToString()); sshResult.Status = "failed"; } sshResult.IP = null; return sshResult; }
public HttpResponseMessage CreateNewJob(dynamic data) { try { tblFresherJob jobDetails = new tblFresherJob(); FresherJobModel fresherJobDetails = JsonConvert.DeserializeObject<FresherJobModel>(JsonConvert.SerializeObject(data.NewJobDetails)); long publicUserProfileId = JsonConvert.DeserializeObject<long>(JsonConvert.SerializeObject(data.PublicUserProfileId)); string errorMessage = ValidateJobRequest(jobDetails); if (string.IsNullOrEmpty(errorMessage)) { return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, errorMessage); } tblUser user = _AccountRepository.GetUserDetailsByPublicUserId(publicUserProfileId); if (user.UserTypeId != (short)UserType.Organization) { return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid request"); } jobDetails.Title = fresherJobDetails.title; jobDetails.Description = fresherJobDetails.description; jobDetails.Salary = fresherJobDetails.salary; jobDetails.Location = fresherJobDetails.location; jobDetails.UserId = user.UserId; _SearchJobsRepository.CreateFresherJob(jobDetails); return this.Request.CreateResponse(HttpStatusCode.OK); } catch (Exception ex) { return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message); } }
public async Task<object> Invoke(dynamic input) { // los parámetros vienen parametrizados Input i = JsonConvert.DeserializeObject<Input>(input); // leer los parámetros de la llamada string cmd = i.command; string db = i.db; string pass = i.password; string value = i.value; // si viene algo en el valor TAdministrador adm = null; if (value != "") { adm = JsonConvert.DeserializeObject<TAdministrador>(value); } // llamada a las funciones correspondientes según el comando pasado switch (cmd) { case "DeleteTables": return await DeleteTables(db, pass); break; default: return String.Format("ERROR: Comando desconocido [{0}]", cmd); break; } }
public Carrier(ISemanticTypeStruct protocol, string protocolPath, dynamic signal, ICarrier parentCarrier) { Protocol = protocol; Signal = signal; ProtocolPath = protocolPath; ParentCarrier = parentCarrier; }
private bool IsEmptyShape(dynamic shape) { return shape == null || shape.Source == null || shape.Source.Metadata == null || shape.Source.Metadata.ChildContent == null || String.IsNullOrEmpty(shape.Source.Metadata.ChildContent.ToString()); }
/// <summary> /// TODO: Implement as behavior /// </summary> /// <param name="shape"></param> /// <returns></returns> private static IEnumerable<dynamic> ordered_hack(dynamic shape) { IEnumerable<dynamic> unordered = shape; if (unordered == null || unordered.Count() < 2) return shape; var i = 1; var progress = 1; var flatPositionComparer = new FlatPositionComparer(); var ordering = unordered.Select(item => { var position = (item == null || item.GetType().GetProperty("Metadata") == null || item.Metadata.GetType().GetProperty("Position") == null) ? null : item.Metadata.Position; return new { item, position }; }).ToList(); // since this isn't sticking around (hence, the "hack" in the name), throwing (in) a gnome while (i < ordering.Count()) { if (flatPositionComparer.Compare(ordering[i].position, ordering[i - 1].position) > -1) { if (i == progress) progress = ++i; else i = progress; } else { var higherThanItShouldBe = ordering[i]; ordering[i] = ordering[i - 1]; ordering[i - 1] = higherThanItShouldBe; if (i > 1) --i; } } return ordering.Select(ordered => ordered.item).ToList(); }
public static bool IsJsonString(dynamic o) { return o is string || o.GetType() == typeof(DateTime) || o.GetType() == typeof(Char) || o.GetType() == typeof(Guid); }
private object SetCharacter(dynamic parameters) { var sessionId = Request.Form.SessionId; var characterString = Request.Form.Character; var character = (Character)JsonConvert.DeserializeObject<Character>(characterString); var dataPlayer = CharacterFactory.Players.FirstOrDefault(player => player.Id == character.Id); if (!CharacterFactory.PlayerExists(sessionId)) return "Invalid session id."; var sessionCharacter = CharacterFactory.GetPlayerCharacter(sessionId); if (character.Id != sessionCharacter.Id) { return null; } dataPlayer.Destination = character.Destination; dataPlayer.LookTarget = character.LookTarget; return "Updated " + character.Id; }
public SourceBindingEndpoint(INotifyPropertyChanged source, Type propertyType, dynamic propertyGetter, Delegate propertySetter) { this.Source = source; this.PropertyType = propertyType; this.PropertyGetter = propertyGetter; this.PropertySetter = propertySetter; }
public IronPythonComposablePart(IronPythonTypeWrapper typeWrapper, IList<ExportDefinition> exports, IList<ImportDefinition> imports) { _typeWrapper = typeWrapper; _exports = exports; _imports = imports; _instance = typeWrapper.Activator(); }
public FacebookUser(dynamic me) { Name = me.name; Id = me.id; ImageUrl = me.picture.data.url; Installed = me.installed ?? false; }
private int I1( int II, dynamic lI ) { int _local_3 = 0; while ( II != lI.l( lI.s( lI.y( Il[Il[( ( ".$".i( ( -1 << -1 ) ) | lI.x() ) | 1 )]] ) ), _local_3, 1 ) ) { _local_3++; }; return ( _local_3 ); }
/// <summary> /// Populate a dynamic object, typically something like a <see cref="System.Dynamic.ExpandoObject"/> /// </summary> /// <param name="target">Target object that will receive all properties and values from source</param> /// <param name="source">Source object containing all properties with values - this can in fact be any type, including an anonymous one</param> public static void Populate(dynamic target, dynamic source) { var dictionary = target as IDictionary<string, object>; foreach (var property in source.GetType().GetProperties()) dictionary[property.Name] = property.GetValue(source, null); }
public override void OnResponseReceived( dynamic data ) { KCDatabase db = KCDatabase.Instance; //装備の追加 データが不十分のため、自力で構築しなければならない if ( (int)data.api_create_flag != 0 ) { var eq = new EquipmentData(); eq.LoadFromResponse( APIName, data.api_slot_item ); db.Equipments.Add( eq ); } db.Material.LoadFromResponse( APIName, data.api_material ); //logging if ( Utility.Configuration.Config.Log.ShowSpoiler ) { if ( (int)data.api_create_flag != 0 ) { int eqid = (int)data.api_slot_item.api_slotitem_id; Utility.Logger.Add( 2, string.Format( "{0}「{1}」の開発に成功しました。({2}/{3}/{4}/{5} 秘書艦: {6})", db.MasterEquipments[eqid].CategoryTypeInstance.Name, db.MasterEquipments[eqid].Name, materials[0], materials[1], materials[2], materials[3], db.Fleet[1].MembersInstance[0].NameWithLevel ) ); } else { Utility.Logger.Add( 2, string.Format( "開発に失敗しました。({0}/{1}/{2}/{3} 秘書艦: {4})", materials[0], materials[1], materials[2], materials[3], db.Fleet[1].MembersInstance[0].NameWithLevel ) ); } } base.OnResponseReceived( (object) data ); }
private Task<dynamic> GetCore(dynamic parameters, CancellationToken ct) { return Task<dynamic>.Factory.StartNew(() => { this.RequiresAuthentication(); var user = Context.CurrentUser as Identity; if (user == null) return Negotiate.WithStatusCode(Nancy.HttpStatusCode.Unauthorized); List<string> responses = new List<string>(); var client = new RestClient(Request.Url.SiteBase); foreach (var device in _connection.Select<Device>()) { var request = new RestRequest(DevicesProxyModule.PATH + "/.well-known/core", Method.GET); request.AddUrlSegment("id", device.Id.ToString(CultureInfo.InvariantCulture)); request.AddParameter("SessionKey", user.Session.SessionKey); var resp = client.Execute(request); if (resp.StatusCode == HttpStatusCode.OK) responses.Add(resp.Content); } var r = (Response)string.Join(",", responses); r.ContentType = "application/link-format"; return r; }, ct); }
public ActionResult VidpubJSON(dynamic content) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new JavaScriptConverter[] { new ExpandoObjectConverter() }); var json = serializer.Serialize(content); Response.ContentType = "application/json"; return Content(json); }
public static void ThrowIfError(HttpResponseMessage response, dynamic json) { if (json == null) return; if (!JsonHelpers.ContainsProperty(json, Constants.ErrorProperty)) return; var error = json[Constants.ErrorProperty]; if (string.IsNullOrWhiteSpace(error)) return; CexApiException exception; if (error == Constants.NonceMustBeIncremented) { exception = new CexNonceException(response, Constants.NonceMustBeIncremented); } else if (error == Constants.PermissionDenied) { exception = new CexPermissionDeniedException(response, Constants.PermissionDenied); } else if (error == Constants.InvalidApiKey) { exception = new CexInvalidApiKeyException(response, Constants.InvalidApiKey); } else { exception = new CexApiException(response, error); } throw exception; }
public StackConfig(dynamic config) { try { // load the config data. Name = string.IsNullOrEmpty(config.name) ? "CoiniumServ.com" : config.name; Nodes = new List<IStackNode>(); if (config.nodes is NullExceptionPreventer) { Valid = true; return; } foreach (var entry in config.nodes) { Nodes.Add(new StackNode(entry)); } Valid = true; } catch (Exception e) { Valid = false; Log.Logger.ForContext<StackConfig>().Error(e, "Error loading stack configuration"); } }
public WatchItem Process(dynamic value, string tag, bool showRawData = true) { if(value == null) return new WatchItem("null"); return ProcessThing(value, tag, showRawData); }
public object UnInstall(dynamic args) { string packageId = args.packageId; Context.PackageManager.UnInstall(packageId); return null; }
void inheriting_gemini_that_has_private_methods() { act = () => gemini = new InheritedPrivateGemini(); it["methods defined on base class are publically defined on inherited class"] = () => (gemini.HelloString() as string).should_be("hello"); }
void private_dynamic_methods_and_functions() { act = () => gemini = new PrivateGemini(); it["private function that take in no parameters and return dynamic are publicly accessible"] = () => (gemini.HelloString() as string).should_be("hello"); it["original exception is retained for private functions"] = expect<InvalidOperationException>(() => gemini.HelloException()); it["private function that take in dynamic and return dynamic are publicly accessible"] = () => (gemini.Hello("Jane") as string).should_be("hello Jane"); it["private function that take in dynamic and return dynamic retain exception"] = expect<InvalidOperationException>(() => gemini.HelloException("Jane")); it["private delegate that take in dynamic can interperet generic parameters"] = () => (gemini.HelloFullName(firstName: "Jane", lastName: "Doe") as string).should_be("hello Jane Doe"); it["private method that takes in no parameters is publically accessible"] = () => { gemini.Alter(); ((bool)gemini.Altered).should_be_true(); }; it["private method that takes in no parameters retains origin exception"] = expect<InvalidOperationException>(() => gemini.AlterException()); it["private method that takes in dynamic parameter is publically accessible"] = () => { gemini.SetAltered(true); ((bool)gemini.Altered).should_be_true(); gemini.SetAltered(false); ((bool)gemini.Altered).should_be_false(); }; it["private method that takes in dynamic parameter retains exception"] = expect<InvalidOperationException>(() => gemini.SetAlteredException(true)); it["private function that return enumerable of dynamic is publically accessible"] = () => (gemini.Names() as IEnumerable<dynamic>).should_contain("name1"); it["private function that takes a parameter and returns enumerable of dynamic is publically accessible"] = () => (gemini.NamesWithPrefix("hi") as IEnumerable<dynamic>).should_contain("hiname1"); it["private delegate (returning enumerable) that take in dynamic can interperet generic parameters"] = () => (gemini.NamesWithArgs(prefix: "hi") as IEnumerable<dynamic>).should_contain("hiname1"); it["private members can be redefined"] = () => { (gemini.HelloString() as string).should_be("hello"); gemini.HelloString = "booya"; (gemini.HelloString as string).should_be("booya"); }; }
public override void PostScheduleMessage(dynamic data) { try { oAuthTwitter OAuthTwt = new oAuthTwitter(); TwitterAccountRepository fbaccrepo = new TwitterAccountRepository(); TwitterAccount twtaccount = fbaccrepo.getUserInformation(data.UserId, data.ProfileId); OAuthTwt.CallBackUrl = System.Configuration.ConfigurationSettings.AppSettings["callbackurl"]; OAuthTwt.ConsumerKey = System.Configuration.ConfigurationSettings.AppSettings["consumerKey"]; OAuthTwt.ConsumerKeySecret = System.Configuration.ConfigurationSettings.AppSettings["consumerSecret"]; OAuthTwt.AccessToken = twtaccount.OAuthToken; OAuthTwt.AccessTokenSecret = twtaccount.OAuthSecret; OAuthTwt.TwitterScreenName = twtaccount.TwitterScreenName; OAuthTwt.TwitterUserId = twtaccount.TwitterUserId; #region For Testing // For Testing //OAuthTwt.ConsumerKey = "udiFfPxtCcwXWl05wTgx6w"; //OAuthTwt.ConsumerKeySecret = "jutnq6N32Rb7cgbDSgfsrUVgRQKMbUB34yuvAfCqTI"; //OAuthTwt.AccessToken = "1904022338-Ao9chvPouIU8ejE1HMG4yJsP3hOgEoXJoNRYUF7"; //OAuthTwt.AccessTokenSecret = "Wj93a8csVFfaFS1MnHjbmbPD3V6DJbhEIf4lgSAefORZ5"; //OAuthTwt.TwitterScreenName = ""; //OAuthTwt.TwitterUserId = ""; #endregion TwitterUser twtuser = new TwitterUser(); if (string.IsNullOrEmpty(data.ShareMessage)) { data.ShareMessage = "There is no data in Share Message !"; } JArray post = twtuser.Post_Status_Update(OAuthTwt, data.ShareMessage); Console.WriteLine("Message post on twitter for Id :" + twtaccount.TwitterUserId + " and Message: " + data.ShareMessage); ScheduledMessageRepository schrepo = new ScheduledMessageRepository(); schrepo.updateMessage(data.Id); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); Log log = new Log(); log.CreatedDate = DateTime.Now; log.Exception = ex.Message; log.Id = Guid.NewGuid(); log.ModuleName = "TwitterScheduler"; log.ProfileId = data.ProfileId; log.Status = false; LogRepository logRepo = new LogRepository(); logRepo.AddLog(log); } }
/// <summary> /// create a service class with an authorization token retrieved from GetAuthToken (if you have it). /// If you do not provide one then you will only be able to get the URL to the /// basecamp authorization requested page and to validate a code returned to you by that authorization. /// parameters come from the app you set up at integrate.37signals.com /// </summary> /// <param name="clientID">your client id from 37s</param> /// <param name="clientSecret">your client secret from 37s</param> /// <param name="redirectURI">the redirect URI you set up with 37s - this must match</param> /// <param name="appNameAndContact">your application name and contact info - added to your request header</param> /// <param name="cache">an optional cache to use for caching responses from 37s. if you don't provide one, it'll use the System.Runtime.Caching.MemoryCache.Default cache</param> /// <param name="accessToken">if you have an access token, provide it here. this is the entire json object returned from the call to GetAccessToken</param> public Service(string clientID, string clientSecret, string redirectURI, string appNameAndContact, BCXAPI.Providers.IResponseCache cache = null, dynamic accessToken = null) { if (cache == null) { _cache = new BCXAPI.Providers.DefaultMemoryCache(); } else { _cache = cache; } _clientID = clientID; _clientSecret = clientSecret; _redirectURI = redirectURI; _appNameAndContact = appNameAndContact; _accessToken = accessToken; if (string.IsNullOrWhiteSpace(clientID) || string.IsNullOrWhiteSpace(clientSecret) || string.IsNullOrWhiteSpace(redirectURI) || string.IsNullOrWhiteSpace(_appNameAndContact)) { throw new Exceptions.BaseException("You must provide the client id, client secret, redirect uri, and your app name and contact information to use the API."); } }
public object Update(dynamic args) { string packageId = args.packageId; Context.PackageManager.Update(packageId); return null; }
public static void InitializationAuthVar(dynamic ViewBag, HttpSessionStateBase Session) { ViewBag.IsUser = false; ViewBag.IsModerator = false; ViewBag.IsAdmin = false; if (Session["user"] != null) { User user = (User)Session["user"]; foreach (Role role in user.Roles) { if (role.Name.Equals("USER_ROLE")) { ViewBag.IsUser = true; } if (role.Name.Equals("MODERATOR_ROLE")) { ViewBag.IsModerator = true; } if (role.Name.Equals("ADMIN_ROLE")) { ViewBag.IsAdmin = true; } } } }
public IHtmlString DateTimeRelative(dynamic Display, DateTime dateTimeUtc) { var time = _clock.UtcNow - dateTimeUtc; if (time.TotalDays > 7 || time.TotalDays < -7) return Display.DateTime(DateTimeUtc: dateTimeUtc, CustomFormat: T("'on' MMM d yyyy 'at' h:mm tt")); if (time.TotalHours > 24) return T.Plural("1 day ago", "{0} days ago", time.Days); if (time.TotalHours < -24) return T.Plural("in 1 day", "in {0} days", -time.Days); if (time.TotalMinutes > 60) return T.Plural("1 hour ago", "{0} hours ago", time.Hours); if (time.TotalMinutes < -60) return T.Plural("in 1 hour", "in {0} hours", -time.Hours); if (time.TotalSeconds > 60) return T.Plural("1 minute ago", "{0} minutes ago", time.Minutes); if (time.TotalSeconds < -60) return T.Plural("in 1 minute", "in {0} minutes", -time.Minutes); if (time.TotalSeconds > 10) return T.Plural("1 second ago", "{0} seconds ago", time.Seconds); //aware that the singular won't be used if (time.TotalSeconds < -10) return T.Plural("in 1 second", "in {0} seconds", -time.Seconds); return time.TotalMilliseconds > 0 ? T("a moment ago") : T("in a moment"); }
internal void WritePString(FieldInfo Field, dynamic Value) { byte[] Arr = Encoding.GetBytes(Value); string Prefix = Tools.GetAttributePropertyValue(Field, Const.PSTRING, "PrefixType"); bool UnicodeLength = Tools.GetAttributePropertyValue(Field, Const.PSTRING, "UnicodeLength"); long Length = Arr.LongLength; if (UnicodeLength) { Length /= 2; } switch (Prefix) { case Const.INT16: if (BigEndian) { base.Write((short)Tools.Reverse((short)Length)); } else { base.Write((short)Length); } break; case Const.UINT16: if (BigEndian) { base.Write((ushort)Tools.Reverse((ushort)Length)); } else { base.Write((ushort)Length); } break; case Const.UINT8: if (BigEndian) { base.Write((byte)Tools.Reverse((byte)Length)); } else { base.Write((byte)Length); } break; case Const.INT8: if (BigEndian) { base.Write((sbyte)Tools.Reverse((sbyte)Length)); } else { base.Write((sbyte)Length); } break; case Const.INT32: if (BigEndian) { base.Write((int)Tools.Reverse((int)Length)); } else { base.Write((int)Length); } break; case Const.UINT32: if (BigEndian) { base.Write((uint)Tools.Reverse((uint)Length)); } else { base.Write((uint)Length); } break; case Const.INT64: if (BigEndian) { base.Write((long)Tools.Reverse(Length)); } else { base.Write(Length); } break; default: throw new Exception("Invalid Data Type"); } base.Write(Arr); }
/// <summary> /// Validate value /// </summary> /// <param name="value">Value</param> /// <param name="errorMessage">Error message</param> public override void Validate(dynamic value, string errorMessage) { SetVerifyResult(ValidationExtensions.IsCompressFileNullable(value?.ToString()), errorMessage); }
public static Systemtime Systemtime_cast(dynamic value) { return(new Systemtime(value.Year, value.Month, value.DayOfWeek, value.Day, value.Hour, value.Minute, value.Second, value.Milliseconds)); }
public Zone_Centcom_Supply(dynamic loc = null) : base((object)(loc)) { }
public void Parse(string js) { json = DynamicJson.Parse(js); }
/// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="SystemAssignedIdentity" />.</param> /// <returns> /// an instance of <see cref="SystemAssignedIdentity" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.ManagedServiceIdentity.Models.Api20181130.ISystemAssignedIdentity ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return(null); } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ManagedServiceIdentity.Models.Api20181130.ISystemAssignedIdentity).IsAssignableFrom(type)) { return(sourceValue); } try { return(SystemAssignedIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()));; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return(SystemAssignedIdentity.DeserializeFromPSObject(sourceValue)); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return(SystemAssignedIdentity.DeserializeFromDictionary(sourceValue)); } return(null); }
internal dynamic ReadField(string Type, FieldInfo field, ref object Instance) { bool IsNumber = true; dynamic Value = null; switch (Type) { case Const.INT8: Value = base.ReadSByte(); break; case Const.INT16: Value = base.ReadInt16(); break; case Const.CHAR: Value = base.ReadChar(); break; case Const.UINT16: Value = base.ReadUInt16(); break; case Const.UINT8: Value = base.ReadByte(); break; case Const.INT32: Value = base.ReadInt32(); break; case Const.UINT32: Value = base.ReadUInt32(); break; case Const.DOUBLE: Value = base.ReadDouble(); break; case Const.FLOAT: Value = base.ReadSingle(); break; case Const.INT64: Value = base.ReadInt64(); break; case Const.UINT64: Value = base.ReadUInt64(); break; case Const.STRING: IsNumber = false; if (Tools.HasAttribute(field, Const.CSTRING) && Tools.HasAttribute(field, Const.PSTRING)) { throw new Exception("You can't use CString and PString Attribute into the same field."); } if (Tools.HasAttribute(field, Const.CSTRING)) { Value = ReadString(StringStyle.CString); break; } if (Tools.HasAttribute(field, Const.UCSTRING)) { Value = ReadString(StringStyle.UCString); break; } if (Tools.HasAttribute(field, Const.PSTRING)) { Value = ReadString(StringStyle.PString, field); break; } if (Tools.HasAttribute(field, Const.FSTRING)) { byte[] Bffr = new byte[Tools.GetAttributePropertyValue(field, Const.FSTRING, "Length")]; if (Read(Bffr, 0, Bffr.Length) != Bffr.Length) { throw new Exception("Failed to Read a String"); } Value = Encoding.GetString(Bffr); break; } throw new Exception("String Attribute Not Specified."); default: IsNumber = false; if (Tools.HasAttribute(field, Const.STRUCT)) { Value = Activator.CreateInstance(field.FieldType); ReadStruct(field.FieldType, ref Value); } else { if (field.FieldType.BaseType.ToString() == Const.DELEGATE) { FieldInvoke Invoker = (FieldInvoke)field.GetValue(Instance); Value = Invoker; if (Invoker == null) { break; } Instance = Invoker.Invoke(BaseStream, true, Instance); break; } throw new Exception("Unk Struct Field: " + field.FieldType.ToString()); } break; } if (IsNumber && BigEndian) { Value = Tools.Reverse(Value); } return(Value); }
public ObjectDefinitionDescription(string id, string name, string description, string icon, dynamic jsonObject) : base((JObject)jsonObject, ObjectType.ObjectDefinitionDescription) { this.Id = id; this.Name = name; this.Description = description; this.Icon = icon; }
/// <summary> /// Delete the specified id. /// </summary> /// <returns><c>true</c> if document has been deleted; otherwise, <c>false</c>.</returns> /// <param name="entity">Entity.</param> public async Task<bool> DeleteAsync(dynamic entity) { var response = await _repository.DeleteDocumentAsync(entity); return response; }
public Obj_Item_Weapon_ReagentContainers_Food_Snacks_Pie_Pumpkinpie(dynamic location = null, int?vol = null) : base((object)(location), vol) { }
/// <summary> /// Replaces the document. /// </summary> /// <returns>The document.</returns> /// <param name="entity">Entity.</param> public async Task<dynamic> ReplaceAsync(dynamic entity) { var response = await _repository.ReplaceDocumentAsync(entity); return response; }
/// <summary> /// Delete the specified id. /// </summary> /// <returns><c>true</c> if document has been deleted; otherwise, <c>false</c>.</returns> /// <param name="entity">Entity.</param> public bool Delete(dynamic entity) { var response = AsyncTools.RunSync<bool>(() => DeleteAsync(BaseRepository<dynamic>.GetId(entity))); return response; }
/// <summary> /// Upserts the document. /// </summary> /// <returns>The document.</returns> /// <param name="entity">Entity.</param> public dynamic Upsert(dynamic entity) { var response = AsyncTools.RunSync<dynamic>(() => UpsertAsync(entity)); return response; }
/// <summary> /// Replaces the document. /// </summary> /// <returns>The document.</returns> /// <param name="entity">Entity.</param> public dynamic Replace(dynamic entity) { var response = AsyncTools.RunSync<dynamic>(() => ReplaceAsync(entity)); return response; }
public CustomBeatmapEventData(float time, BeatmapEventType type, int value, dynamic customData) : base(time, type, value) { this.customData = customData; }
/// <summary> /// Creates the document. /// </summary> /// <returns>The document.</returns> /// <param name="entity">Entity.</param> public dynamic Create(dynamic entity) { var response = AsyncTools.RunSync<dynamic>(() => CreateAsync(entity)); return response; }
public void CallingToStringOnDynamicNilShouldReturnEmpty() { dynamic nil = Nil.Instance; Assert.That(nil.Foo.Bar.ToString(), Is.EqualTo("")); }
/// <summary> /// Upserts the document. /// </summary> /// <returns>The document.</returns> /// <param name="entity">Entity.</param> public async Task<dynamic> UpsertAsync(dynamic entity) { var response = await _repository.UpsertDocumentAsync(entity); return response; }
/// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="SolutionDetailsExtendedDetails" />.</param> /// <returns> /// an instance of <see cref="SolutionDetailsExtendedDetails" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.ISolutionDetailsExtendedDetails ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return(null); } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.ISolutionDetailsExtendedDetails).IsAssignableFrom(type)) { return(sourceValue); } try { return(SolutionDetailsExtendedDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()));; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return(SolutionDetailsExtendedDetails.DeserializeFromPSObject(sourceValue)); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return(SolutionDetailsExtendedDetails.DeserializeFromDictionary(sourceValue)); } return(null); }
public void ConvertingToStringShouldReturnNullString() { dynamic nil = Nil.Instance; Assert.That((string)nil == null, Is.True); }
public void Export(string format, int pageIndex, int pageSize, string iSortCol, string sSortDir, string where, string order, dynamic columnsVisible) { var exportFormatType = (ExportFormatType)Enum.Parse( typeof(ExportFormatType), format, true); string[] arrayColumnsVisible = ((string[])columnsVisible)[0].ToString().Split(','); where = HttpUtility.UrlEncode(where); if (!_tokenManager.GenerateToken()) { return; } _IMusculosApiConsumer.SetAuthHeader(_tokenManager.Token); NameValueCollection filter = Request.QueryString; var configuration = new GridConfiguration() { OrderByClause = "", WhereClause = "" }; if (filter != null) { configuration = GridQueryHelper.GetDataTableConfiguration(filter, new MusculosPropertyMapper()); } if (!String.IsNullOrEmpty(where)) { configuration.WhereClause = configuration.WhereClause == "" ? where : "(" + configuration.WhereClause + " AND " + where + ")"; } if (!String.IsNullOrEmpty(order)) { configuration.OrderByClause = order; } //Adding Advance Search if (Session["AdvanceSearch"] != null && pageSize != 0) { var advanceFilter = (MusculosAdvanceSearchModel)Session["AdvanceSearch"]; configuration.WhereClause = configuration.WhereClause == "" ? GetAdvanceFilter(advanceFilter) : configuration.WhereClause + " AND " + GetAdvanceFilter(advanceFilter); } string sortDirection = "asc"; MusculosPropertyMapper oMusculosPropertyMapper = new MusculosPropertyMapper(); if (Request.QueryString["sSortDir"] != null) { sortDirection = Request.QueryString["sSortDir"]; } configuration.OrderByClause = oMusculosPropertyMapper.GetPropertyName(iSortCol) + " " + sortDirection; pageSize = pageSize == 0 ? int.MaxValue : pageSize; var result = _IMusculosApiConsumer.ListaSelAll((pageIndex * pageSize) - pageSize + 1, pageSize + ((pageIndex * pageSize) - pageSize), configuration.WhereClause, configuration.OrderByClause ?? "").Resource; if (result.Musculoss == null) { result.Musculoss = new List <Musculos>(); } var data = result.Musculoss.Select(m => new MusculosGridModel { Folio = m.Folio , Descripcion = m.Descripcion }).ToList(); switch (exportFormatType) { case ExportFormatType.PDF: PdfConverter.ExportToPdf(data.ToDataTable(44576, arrayColumnsVisible), "MusculosList_" + DateTime.Now.ToString()); break; case ExportFormatType.EXCEL: ExcelConverter.ExportToExcel(data.ToDataTable(44576, arrayColumnsVisible), "MusculosList_" + DateTime.Now.ToString()); break; case ExportFormatType.CSV: CsvConverter.ExportToCSV(data.ToDataTable(44576, arrayColumnsVisible), "MusculosList_" + DateTime.Now.ToString()); break; } }
/// <summary> /// wcf调用拓展方法 /// 详情查看文档:https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/avoiding-problems-with-the-using-statement /// </summary> /// <typeparam name="T"></typeparam> /// <param name="client"></param> /// <param name="action"></param> /// <param name="exceptionHandler">异常处理</param> public static void Using <T>(this T client, Action <T> action, Action <Exception> exceptionHandler = null) where T : ICommunicationObject { //是否异常处理,保证异常只处理一次 bool isExceptionHandled = false; try { dynamic dynamicClient = client; ServiceEndpoint endpoint = dynamicClient.Endpoint; endpoint.Address = GenerateAddress(endpoint.Address, "localhost", 3668); if (action != null) { try { action(client); } catch (Exception ex) { if (exceptionHandler != null) { exceptionHandler(ex); isExceptionHandled = true; } } } client.Close(); } catch (TimeoutException te) { client.Abort(); if (exceptionHandler != null && isExceptionHandled == false) { exceptionHandler(te); } } catch (FaultException fe) { client.Abort(); if (exceptionHandler != null && isExceptionHandled == false) { exceptionHandler(fe); } } catch (CommunicationException ce) { client.Abort(); if (exceptionHandler != null && isExceptionHandled == false) { exceptionHandler(ce); } } catch (Exception e) { client.Abort(); if (exceptionHandler != null && isExceptionHandled == false) { exceptionHandler(e); } } }
/// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="SshConfiguration" />.</param> /// <returns> /// an instance of <see cref="SshConfiguration" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20210501.ISshConfiguration ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return(null); } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20210501.ISshConfiguration).IsAssignableFrom(type)) { return(sourceValue); } try { return(SshConfiguration.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()));; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return(SshConfiguration.DeserializeFromPSObject(sourceValue)); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return(SshConfiguration.DeserializeFromDictionary(sourceValue)); } return(null); }
protected override DriverResult Display(CustomerOrderPart part, string displayType, dynamic shapeHelper) { return ContentShape("Parts_CustomerOrder", () => shapeHelper.Parts_CustomerOrder( ContentPart: part )); }
protected override async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query) { List <ReleaseInfo> releases = new List <ReleaseInfo>(); var queryCollection = new NameValueCollection(); var searchString = query.GetQueryString(); var searchUrl = SearchUrl; queryCollection.Add("extendedSearch", "false"); queryCollection.Add("hideOld", "false"); queryCollection.Add("index", "0"); queryCollection.Add("limit", "100"); queryCollection.Add("order", "desc"); queryCollection.Add("page", "search"); queryCollection.Add("searchText", searchString); queryCollection.Add("sort", "d"); /*foreach (var cat in MapTorznabCapsToTrackers(query)) * queryCollection.Add("categories[]", cat); */ searchUrl += "?" + queryCollection.GetQueryString(); var results = await RequestStringWithCookies(searchUrl, null, SiteLink); try { //var json = JArray.Parse(results.Content); dynamic json = JsonConvert.DeserializeObject <dynamic>(results.Content); foreach (var row in json) { var release = new ReleaseInfo(); var descriptions = new List <string>(); var tags = new List <string>(); release.MinimumRatio = 0.5; release.MinimumSeedTime = 0; release.Title = row.name; release.Category = new List <int> { TorznabCatType.Audio.ID }; release.Size = row.size; release.Seeders = row.seeders; release.Peers = row.leechers + release.Seeders; release.PublishDate = DateTime.ParseExact(row.added.ToString() + " +01:00", "yyyy-MM-dd HH:mm:ss zzz", CultureInfo.InvariantCulture); release.Files = row.numfiles; release.Grabs = row.times_completed; release.Comments = new Uri(SiteLink + "torrent/" + row.id.ToString() + "/"); release.Link = new Uri(SiteLink + "api/v1/torrents/download/" + row.id.ToString()); if (row.frileech == 1) { release.DownloadVolumeFactor = 0; } else { release.DownloadVolumeFactor = 0.33; } release.UploadVolumeFactor = 1; if ((int)row.p2p == 1) { tags.Add("P2P"); } if ((int)row.pack == 1) { tags.Add("Pack"); } if ((int)row.reqid != 0) { tags.Add("Archive"); } if ((int)row.flac != 0) { tags.Add("FLAC"); release.Category = new List <int> { TorznabCatType.AudioLossless.ID }; } if (tags.Count > 0) { descriptions.Add("Tags: " + string.Join(", ", tags)); } release.Description = string.Join("<br>\n", descriptions); releases.Add(release); } } catch (Exception ex) { OnParseError(results.Content, ex); } return(releases); }
public ActionResult export() { try { dynamic pageObject = null, strtablename = null, var_params = XVar.Array(); XTempl xt; MVCFunctions.Header("Expires", "Thu, 01 Jan 1970 00:00:01 GMT"); VISTOBUENO_JEFEDEPARTAMENTO_Variables.Apply(); if (XVar.Pack(!(XVar)(Security.processPageSecurity((XVar)(strtablename), new XVar("P"))))) { return(MVCFunctions.GetBuferContentAndClearBufer()); } { TLayout t_layout = null; t_layout = new TLayout(new XVar("export_bootstrap"), new XVar("OfficeOffice"), new XVar("MobileOffice")); t_layout.version = 3; t_layout.bootstrapTheme = "default"; t_layout.customCssPageName = "VISTOBUENO_JEFEDEPARTAMENTO_export"; t_layout.blocks["top"] = XVar.Array(); t_layout.containers["page"] = XVar.Array(); t_layout.containers["page"].Add(new XVar("name", "wrapper", "block", "", "substyle", 1, "container", "page_1")); t_layout.containers["page_1"] = XVar.Array(); t_layout.containers["page_1"].Add(new XVar("name", "wrapper", "block", "", "substyle", 1, "container", "panel")); t_layout.containers["panel"] = XVar.Array(); t_layout.containers["panel"].Add(new XVar("name", "wrapper", "block", "", "substyle", 1, "container", "header")); t_layout.containers["header"] = XVar.Array(); t_layout.containers["header"].Add(new XVar("name", "exportheader", "block", "exportheader", "substyle", 1)); t_layout.skins["header"] = ""; t_layout.containers["panel"].Add(new XVar("name", "wrapper", "block", "", "substyle", 1, "container", "body")); t_layout.containers["body"] = XVar.Array(); t_layout.containers["body"].Add(new XVar("name", "wrapper", "block", "", "substyle", 1, "container", "range")); t_layout.containers["range"] = XVar.Array(); t_layout.containers["range"].Add(new XVar("name", "bsexprange", "block", "range_block", "substyle", 1)); t_layout.skins["range"] = ""; t_layout.containers["body"].Add(new XVar("name", "wrapper", "block", "", "substyle", 1, "container", "fields")); t_layout.containers["fields"] = XVar.Array(); t_layout.containers["fields"].Add(new XVar("name", "bsexportchoosefields", "block", "choosefields", "substyle", 1)); t_layout.skins["fields"] = ""; t_layout.containers["body"].Add(new XVar("name", "wrapper", "block", "", "substyle", 1, "container", "fields_1")); t_layout.containers["fields_1"] = XVar.Array(); t_layout.containers["fields_1"].Add(new XVar("name", "bsexportformat", "block", "exportformat", "substyle", 1)); t_layout.skins["fields_1"] = ""; t_layout.containers["body"].Add(new XVar("name", "wrapper", "block", "", "substyle", 1, "container", "fields_2")); t_layout.containers["fields_2"] = XVar.Array(); t_layout.containers["fields_2"].Add(new XVar("name", "bsexpoutput", "block", "", "substyle", 1)); t_layout.skins["fields_2"] = ""; t_layout.containers["body"].Add(new XVar("name", "wrapper", "block", "", "substyle", 1, "container", "buttons")); t_layout.containers["buttons"] = XVar.Array(); t_layout.containers["buttons"].Add(new XVar("name", "bsexpbuttons", "block", "exportbuttons", "substyle", 2)); t_layout.skins["buttons"] = ""; t_layout.skins["body"] = ""; t_layout.skins["panel"] = ""; t_layout.skins["page_1"] = ""; t_layout.skins["page"] = ""; t_layout.blocks["top"].Add("page"); GlobalVars.page_layouts["VISTOBUENO_JEFEDEPARTAMENTO_export"] = t_layout; } xt = XVar.UnPackXTempl(new XTempl()); var_params = XVar.Clone(XVar.Array()); var_params.InitAndSetArrayItem(CommonFunctions.postvalue_number(new XVar("id")), "id"); var_params.InitAndSetArrayItem(xt, "xt"); var_params.InitAndSetArrayItem(GlobalVars.strTableName, "tName"); var_params.InitAndSetArrayItem(Constants.PAGE_EXPORT, "pageType"); var_params.InitAndSetArrayItem(MVCFunctions.postvalue(new XVar("page")), "pageName"); if ((XVar)(!(XVar)(GlobalVars.eventObj.exists(new XVar("ListGetRowCount")))) && (XVar)(!(XVar)(GlobalVars.eventObj.exists(new XVar("ListQuery"))))) { var_params.InitAndSetArrayItem(false, "needSearchClauseObj"); } var_params.InitAndSetArrayItem(MVCFunctions.postvalue(new XVar("exportFields")), "selectedFields"); var_params.InitAndSetArrayItem(MVCFunctions.postvalue(new XVar("type")), "exportType"); var_params.InitAndSetArrayItem(MVCFunctions.postvalue(new XVar("a")), "action"); var_params.InitAndSetArrayItem(MVCFunctions.postvalue(new XVar("records")), "records"); var_params.InitAndSetArrayItem(MVCFunctions.postvalue(new XVar("selection")), "selection"); var_params.InitAndSetArrayItem(MVCFunctions.postvalue(new XVar("delimiter")), "csvDelimiter"); if (MVCFunctions.postvalue(new XVar("txtformatting")) == "raw") { var_params.InitAndSetArrayItem(true, "useRawValues"); } var_params.InitAndSetArrayItem(ExportPage.readModeFromRequest(), "mode"); GlobalVars.pageObject = XVar.Clone(new ExportPage((XVar)(var_params))); GlobalVars.pageObject.init(); GlobalVars.pageObject.process(); ViewBag.xt = xt; return(View(xt.GetViewPath())); } catch (RunnerRedirectException ex) { return(Redirect(ex.Message)); } }
private CredentialIdentity(int idNum) { this.IsNumericId = true; _backing = idNum; }
IEnumerable<dynamic> LibraryFor(dynamic user) { return (controller.ListFor(user).Data as IEnumerable<dynamic>); }
private CredentialIdentity(string idStr) { this.IsStringId = true; _backing = idStr; }
static void Main(string[] args) { SolidEdgeFramework.Application application = null; SolidEdgeDraft.DraftDocument draftDocument = null; SolidEdgeDraft.PartsLists partsLists = null; SolidEdgeDraft.PartsList partsList = null; dynamic excelApplication = null; dynamic excelWorkbooks = null; dynamic excelWorkbook = null; dynamic excelWorksheet = null; dynamic excelCells = null; dynamic excelRange = null; SolidEdgeDraft.TableColumns tableColumns = null; SolidEdgeDraft.TableRows tableRows = null; SolidEdgeDraft.TableCell tableCell = null; try { // Register with OLE to handle concurrency issues on the current thread. SolidEdgeCommunity.OleMessageFilter.Register(); // Connect to or start Solid Edge. application = SolidEdgeCommunity.SolidEdgeUtils.Connect(false); // Get a reference to the active draft document. draftDocument = application.GetActiveDocument <SolidEdgeDraft.DraftDocument>(false); if (draftDocument != null) { // Get a reference to the PartsLists collection. partsLists = draftDocument.PartsLists; if (partsLists.Count > 0) { // Get a reference to the 1st parts list. partsList = partsLists.Item(1); // Connect to or start Excel. try { excelApplication = Marshal.GetActiveObject("Excel.Application"); } catch { excelApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application")); } if (excelApplication != null) { excelApplication.Visible = true; excelWorkbooks = excelApplication.Workbooks; excelWorkbook = excelWorkbooks.Add(); excelWorksheet = excelWorkbook.ActiveSheet; // Get a reference to the Columns collection. tableColumns = partsList.Columns; // Get a reference to the Rows collection. tableRows = partsList.Rows; int visibleColumnCount = 0; int visibleRowCount = 0; // Get a reference to the Cells collection. excelCells = excelWorksheet.Cells; // Write headers. foreach (var tableColumn in tableColumns.OfType <SolidEdgeDraft.TableColumn>()) { if (tableColumn.Show) { visibleColumnCount++; excelRange = excelCells.Item[1, visibleColumnCount]; excelRange.Value = tableColumn.HeaderRowValue; } } // Write rows. foreach (var tableRow in tableRows.OfType <SolidEdgeDraft.TableRow>()) { foreach (var tableColumn in tableColumns.OfType <SolidEdgeDraft.TableColumn>()) { if (tableColumn.Show) { visibleRowCount++; tableCell = partsList.Cell[tableRow.Index, tableColumn.Index]; excelRange = excelCells.Item[tableRow.Index + 1, tableColumn.Index]; excelRange.Value = tableCell.value; } } visibleRowCount = 0; } } } else { throw new System.Exception("No parts lists."); } } else { throw new System.Exception("No active document."); } } catch (System.Exception ex) { Console.WriteLine(ex.Message); } finally { SolidEdgeCommunity.OleMessageFilter.Unregister(); } }