public void Publish_Photo_To_Existing_Album() { #if DEBUG string photoPath = @"..\..\..\Facebook.Tests\bin\Debug\monkey.jpg"; #else string photoPath = @"..\..\..\Facebook.Tests\bin\Release\monkey.jpg"; #endif string albumId = ConfigurationManager.AppSettings["AlbumId"]; byte[] photo = File.ReadAllBytes(photoPath); FacebookClient app = new FacebookClient(); dynamic parameters = new ExpandoObject(); parameters.access_token = ConfigurationManager.AppSettings["AccessToken"]; parameters.message = "This is a test photo of a monkey that has been uploaded " + "by the Facebook C# SDK (http://facebooksdk.codeplex.com)" + "using the Graph API"; var mediaObject = new FacebookMediaObject { FileName = "monkey.jpg", ContentType = "image/jpeg", }; mediaObject.SetValue(photo); parameters.source = mediaObject; dynamic result = app.Post(String.Format("/{0}/photos", albumId), parameters); Assert.NotNull(result); Assert.NotEqual(null, result.id); }
public void AddRows_Error_Rollback() { IDynamicTable table = new DynamicTable(DynamicTableType.Expandable); dynamic row; dynamic rowB; //add values row = new ExpandoObject(); row.FirstName = "Hans"; row.LastName = "Mueller"; row.Age = 30; table.AddRow(row); try { row = new ExpandoObject(); row.FirstName = "Hans"; row.LastName = "Meier"; row.Age = 30; rowB = new ExpandoObject(); rowB.LastName = 50; rowB.Street = "Main street"; table.AddRows(new List<dynamic>(){ row, rowB}); Assert.Fail(); } catch (ArgumentException) { } //compare Assert.AreEqual(1, table.Rows.Count); }
public IList<IStandupMessage> GetAllStandupHistory(string roomName, string botName) { dynamic expando = new ExpandoObject(); expando.GetAll = true; var result = _repository.GetItems(expando); return result.Succeed ? result.Result : null; }
public dynamic CreatePropsAndFields(Type reference) { var props = reference.GetProperties(); var fields = reference.GetFields().Where(x => x.IsPublic); var itemMapper = new System.Dynamic.ExpandoObject(); foreach (var prop in props) { if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string)) { var dynamicItem = CreatePropsAndFields(prop.PropertyType); ((IDictionary <String, Object>)itemMapper).Add(prop.Name, dynamicItem); } else { ((IDictionary <String, Object>)itemMapper).Add(prop.Name, $"${{item.{prop.Name}}}"); } } foreach (var field in fields) { if (field.FieldType.IsClass && field.FieldType != typeof(string)) { var dynamicItem = CreatePropsAndFields(field.FieldType); ((IDictionary <String, Object>)itemMapper).Add(field.Name, dynamicItem); } else { ((IDictionary <String, Object>)itemMapper).Add(field.Name, $"${{item.{field.Name}}}"); } } return(itemMapper); }
public void AddRow_Error_AdditionalElement_DefineOnce() { IDynamicTable table = new DynamicTable(DynamicTableType.DefineOnce); dynamic row; //add values row = new ExpandoObject(); row.FirstName = "Hans"; row.LastName = "Mueller"; row.Age = 30; table.AddRow(row); try { row = new ExpandoObject(); row.FirstName = "Hans"; row.LastName = "Meier"; row.Age = 30; row.Street = "Main street"; table.AddRow(row); Assert.Fail(); } catch (ArgumentException) { } }
public IActionResult selectByCharityId([Required] int charityId) { try { DataTable dt = Data.Charity.selectByCharityId(charityId); dynamic Charity = new System.Dynamic.ExpandoObject(); if (dt.Rows.Count > 0) { Charity.charityId = (int)dt.Rows[0]["charityId"]; Charity.firstName = (dt.Rows[0]["firstName"] == DBNull.Value ? "" : dt.Rows[0]["firstName"].ToString()); Charity.lastName = (dt.Rows[0]["lastName"] == DBNull.Value ? "" : dt.Rows[0]["lastName"].ToString()); Charity.phoneNumber = (dt.Rows[0]["phoneNumber"] == DBNull.Value ? "" : dt.Rows[0]["phoneNumber"].ToString()); Charity.email = (dt.Rows[0]["email"] == DBNull.Value ? "" : dt.Rows[0]["email"].ToString()); Charity.gender = (dt.Rows[0]["gender"] == DBNull.Value ? "" : dt.Rows[0]["gender"].ToString()); Charity.address = (dt.Rows[0]["address"] == DBNull.Value ? "" : dt.Rows[0]["address"].ToString()); Charity.profileImage = (dt.Rows[0]["profileImage"] == DBNull.Value ? "" : dt.Rows[0]["profileImage"].ToString()); Charity.createdDate = (dt.Rows[0]["createdDate"] == DBNull.Value ? "" : dt.Rows[0]["createdDate"].ToString()); return(StatusCode((int)HttpStatusCode.OK, Charity)); } else { return(StatusCode((int)HttpStatusCode.OK, Charity)); } } catch (Exception e) { string SaveErrorLog = Data.Common.SaveErrorLog("selectByCharityId", e.Message); return(StatusCode((int)HttpStatusCode.InternalServerError, new { ErrorMessage = e.Message })); } }
public Aplus(Scope dlrglobals, LexerMode parsemode) { this.sysvars = new SystemVariables(); this.dependencies = new DependencyManager(); this.callbackManager = new CallbackManager(); this.dlrglobals = dlrglobals; this.globals = new DYN.ExpandoObject(); this.sysvars["mode"] = ASymbol.Create(parsemode.ToString().ToLower()); this.mmfmanager = new MemoryMappedFileManager(); this.systemFunctions = Function.SystemFunction.DiscoverSystemFunctions(); if (String.IsNullOrEmpty(Environment.GetEnvironmentVariable("APATH", EnvironmentVariableTarget.User))) { string paths = String.Join(";", ".", "./Runtime/Context/"); Environment.SetEnvironmentVariable("APATH", paths, EnvironmentVariableTarget.User); } // TODO: Move this to app.config? this.autoloadContexts = new string[] { "sys" }; this.contextLoader = new ContextLoader(this); }
public async Task <IActionResult> ChatBox(int UserID1, int UserID2) { // Validate, else redirect to /login var cookies = Request.Cookies["token"]; if (cookies == null) { return(Redirect("/login")); } InfoHelper.IsLoggedIn = true; // Get current active user string email = SecurityHelper.GetLoggedInUser(cookies); UserModel currentUser = await Dataprovider.Instance.ReadUserByEmail(email); int relationshipId = await Dataprovider.Instance.ReadRealtionShipId(UserID1, UserID2); // Check if the relationshipID exists if (!await Dataprovider.Instance.CheckIfRelationshipExists(relationshipId)) { return(Unauthorized("403")); } RelationShipModel relation = await Dataprovider.Instance.ReadRelationShipById(relationshipId); // Validate same level of accepted relation if (!await Dataprovider.Instance.CheckIfSameRelationShip(relation.UserID1, relation.UserID2)) { return(Unauthorized("403")); } if (currentUser.ID != relation.UserID1 && currentUser.ID != relation.UserID2) { return(Unauthorized("403")); } UserModel antagonist = await Dataprovider.Instance.ReadUserById(currentUser.ID != relation.UserID1?relation.UserID1 : relation.UserID2); antagonist.Images = await Dataprovider.Instance.GetUserImagesByUserID(antagonist.ID); currentUser.Images = await Dataprovider.Instance.GetUserImagesByUserID(currentUser.ID); List <MessageModel> messages = new List <MessageModel>(); var _ = await Dataprovider.Instance.ReadAllMessagesBetweenTwoUsers(relationshipId); foreach (MessageModel m in _) { messages.Add(m); } dynamic model = new System.Dynamic.ExpandoObject(); model.Me = currentUser; model.NotMe = antagonist; model.Messages = messages; //(UserModel, UserModel, List<MessageModel>) tuple = (currentUser, antagonist, messages); return(View(model)); }
/// <summary> /// Loads default contexts into the provided <see cref="Scope"/>Scope. /// </summary> /// <param name="scope">Scope where the contexts will be loaded.</param> /// <remarks> /// Warning! This method will overwrite the context if there is already one. /// </remarks> /// <returns>On the first call it will return true, otherwise false.</returns> public bool AutoloadContext(Scope scope) { if (this.isAutoLoaded) { return(false); } foreach (string contextName in this.autoloadContexts) { IDictionary <string, object> context = new DYN.ExpandoObject(); IDictionary <string, AType> contextElements = this.ContextLoader.FindContextElements(contextName); foreach (KeyValuePair <string, AType> item in contextElements) { context[item.Key] = item.Value; } if (context.Count > 0) { // TODO: ? is it ok to replace the whole context or replace only individual elements? scope.Storage[contextName] = context; } } this.isAutoLoaded = true; return(true); }
static void AddValue() { //动态类,可以作为基类被继承 Dictionary <string, object> temp = new Dictionary <string, object>(); temp.Add("Name", "金朝钱"); temp["Age"] = 31; temp["Birthday"] = DateTime.Now; dynamic obj = new System.Dynamic.ExpandoObject(); foreach (KeyValuePair <string, object> item in temp) { ((IDictionary <string, object>)obj).Add(item.Key, item.Value); } Console.Write(string.Format("Name:{0}", obj.GetType().GetProperty("name").GetValue(obj, null).ToString())); dynamic model = new ExpandoObject(); var t1 = "t1".ToString(); AddProperty(model, t1, 1212); var sb = model.t1; }
private dynamic _createKey() { dynamic key = new ExpandoObject(); key.b = (Func<string, int>)( p1 => p1.Length ); key.r = (Func<double, int>)( p1 => (int)Math.Floor( p1 ) ); key.i = (Func<int, int>)( p1 => key.r( rand.NextDouble() * p1 ) ); key.j = (Func<int>)( () => 8 ); key.k = (Func<double, double, double>)( ( p1, p2 ) => (int)p1 ^ (int)p2 ); key.l = (Func<string, int, int, double>)( ( p1, p2, p3 ) => { double d; if ( double.TryParse( p1.substr( p2, p3 ), out d ) ) { return d; } return double.NaN; } ); key.m = (Func<double, double, double>)( ( p1, p2 ) => p1 - p2 ); key.n = (Func<double>)( () => key.r( DateTime.Now.getTime() / 1000 ) ); key.o = (Func<double, double, double>)( ( p1, p2 ) => p2 / p1 ); key.p = (Func<double, double, double>)( ( p1, p2 ) => p2 % p1 ); key.q = (Func<double>)( () => 1.44269504088896 ); key.s = (Func<object, string>)( p1 => p1.ToString() ); key.t = (Func<object[], string>)( ps => string.Join( "", ps ) ); key.u = (Func<double, double, double>)( ( p1, p2 ) => p1 + p2 ); key.v = (Func<int>)( () => 16 ); key.w = (Func<int>)( () => 2 ); key.x = (Func<int>)( () => 4 ); key.y = (Func<int, double>)( p1 => Math.Sqrt( p1 ) ); key.z = (Func<double, double, double>)( ( p1, p2 ) => p1 * p2 ); return ( key ); }
public void OpenPopup() { dynamic settings = new ExpandoObject(); settings.Placement = PlacementMode.Center; settings.PlacementTarget = GetView(null); windowManager.ShowPopup(new DialogViewModel(), "Popup", settings); }
public dynamic Request(string subject, object body) { object response = null; try { var token = Guid.NewGuid().ToString(); dynamic payload = new ExpandoObject(); payload.subject = subject; payload.body = body; payload.token = token; var json = LowerCaseSerializer.SerializeObject(payload); _responseHandlers.TryAdd(token, (msg) => { response = msg; }); _serverChatService.SendMessage(json); while (response == null) { Thread.Sleep(200); } Action<object> removedItem; _responseHandlers.TryRemove(token, out removedItem); return (dynamic)response; } catch (Exception ex) { _onSendException(ex); } return null; }
public void ExpandoPropertiesTest() { var x = new ExpandoObject() as IDictionary<string, Object>; x.Add("NewProp", "test"); dynamic model = x as dynamic; Assert.AreEqual(model.NewProp, "test"); }
public ActionResult Index(string authToken, string noteId) { if (String.IsNullOrWhiteSpace(authToken)) { throw new EverpageException("Argument \"authToken\" is required."); } if (String.IsNullOrWhiteSpace(noteId)) { throw new EverpageException("Argument \"noteId\" is required."); } authToken = authToken.Trim(); noteId = noteId.Trim(); var beginTime = DateTime.Now; var noteGuid = ParseNoteGuid(noteId); var userStore = GetUserStore(); var user = GetUser(userStore, authToken); var userInfo = GetPublicUserInfo(userStore, user.Username); var noteStore = GetNoteStore(userStore, authToken); var note = GetNote(noteStore, authToken, noteGuid); var loadTime = DateTime.Now - beginTime; dynamic model = new ExpandoObject(); model.Title = note.Title; model.Content = ProcessContent(userInfo, note); model.LoadTime = loadTime; return View(model); }
public dynamic ToBaseWireFormat() { dynamic result = new ExpandoObject(); result.id = Id; result.name = Name; return result; }
public void SuccessTest2() { using (IDocumentStore documentStore = new EmbeddableDocumentStore { RunInMemory = true }.Initialize()) { dynamic expando = new ExpandoObject(); using (IDocumentSession session = documentStore.OpenSession()) { session.Store(expando); RavenJObject metadata = session.Advanced.GetMetadataFor((ExpandoObject)expando); metadata[PropertyName] = RavenJToken.FromObject(true); session.SaveChanges(); } using (IDocumentSession session = documentStore.OpenSession()) { dynamic loaded = session.Advanced.LuceneQuery<dynamic>() .WhereEquals("@metadata.Raven-Entity-Name", documentStore.Conventions.GetTypeTagName(typeof(ExpandoObject))) .FirstOrDefault(); Assert.NotNull(loaded); } } }
public void ProcessContent(IContentPersister persister) { using (var db = new GameDatabaseContext()) { var repo = new QuestRepository(db); var items = repo.GetAll(); foreach (var item in items) { // Save out properties we want to a new object and then persist dynamic persistable = new ExpandoObject(); Console.WriteLine("Processing quest with ID {0}", item.Id); persistable.id = item.Id; persistable.name = item.Name; persistable.description = item.Description; persister.Persist(persistable, "\\quests\\{0}.json".FormatWith(item.Id)); } } }
private ExpandoObject ParseFromRow(Row row, ISheetDefinition sheetDefinition) { IDictionary<string, object> expando = new ExpandoObject(); var cells = row.Elements<Cell>().ToList(); var colDefs = sheetDefinition.ColumnDefinitions.ToList(); var count = Math.Max(cells.Count, colDefs.Count); for (var index = 0; index < count; index++) { var colDef = index < colDefs.Count ? colDefs[index] : null; var cell = index < cells.Count ? cells[index] : null; string propName; object propValue; if (cell != null) { propName = cell.GetMdsolAttribute("propertyName"); propValue = _converterManager.GetCSharpValue(cell); } else if (colDef != null) { propName = colDef.PropertyName; propValue = null; } else { throw new NotSupportedException("Cell and CellDefinition are both null"); } expando.Add(propName, propValue); } return (ExpandoObject) expando; }
public HomeModule(IViewLocationProvider viewLocationProvider) { this.viewLocationProvider = viewLocationProvider; Get["/"] = _ => { var popularposts = GetModel(); dynamic postModel = new ExpandoObject(); postModel.PopularPosts = popularposts; postModel.MetaData = popularposts; return View["blogindex", postModel]; }; Get["/{viewname}"] = parameters => { var popularposts = GetModel(); dynamic postModel = new ExpandoObject(); postModel.PopularPosts = popularposts; postModel.MetaData = popularposts.FirstOrDefault(x => x.Slug == parameters.viewname); return View["Posts/" + parameters.viewname, postModel]; }; }
/// <summary> /// Extract value, include extract "Property=Value" formay /// </summary> private static dynamic ExtractValue(string line, BCONConfig config) { if (config.ValueSeperator.Any(line.Contains) || config.PropertySeperator.Any(line.Contains)) { dynamic obj = new ExpandoObject(); string[] parameters = line.Split(config.PropertySeperator, StringSplitOptions.RemoveEmptyEntries); foreach (string p in parameters) { string[] values = p.Split(config.ValueSeperator, StringSplitOptions.RemoveEmptyEntries); if (values.Length > 1) { (obj as IDictionary<string, dynamic>)[values[0].Trim()] = ExtractValue(values[1].Trim(), config); } } return obj; } double doubleValue; int intValue; if (double.TryParse(line, NumberStyles.Number, null, out doubleValue)) { return doubleValue; } if (int.TryParse(line, NumberStyles.Number, null, out intValue)) { return intValue; } return line; }
public IEnumerable<dynamic> Execute(int? id) { var command = new SqlCommand(); command.Connection = _connection; command.CommandText = "SelectEmployees"; if (id.HasValue) { var parameter = new SqlParameter { Value = id, ParameterName = "@id", }; command.Parameters.Add(parameter); } var reader = command.ExecuteReader(); while (reader.Read()) { dynamic record = new ExpandoObject(); for (var ii = 0; ii < reader.FieldCount; ii++) { record[reader.GetName(ii)] = reader[ii]; } yield return record; } }
private dynamic GetBody(ParameterInfo p) { dynamic expando = new System.Dynamic.ExpandoObject(); if (p.ParameterType.IsPrimitive || p.ParameterType == typeof(string)) { ((IDictionary <string, object>)expando)[p.Name] = p.ParameterType.FullName; return(expando); } try { var type = TypeLoader.Find(p.ParameterType.FullName, _assemblies); var props = PropLoader.Get(type); foreach (var pr in props) { if (pr.PropertyType.IsPrimitive || pr.PropertyType == typeof(string)) { ((IDictionary <string, object>)expando)[pr.Name] = pr.PropertyType.FullName; } else { ((IDictionary <string, object>)expando)[pr.Name] = GetBody(pr); } } return(expando); } catch (Exception e) { var abc = e; } throw new Exception("Something has gone wrong!"); }
public IHttpActionResult GetKeyFromXml() { //random number between 1 and 6 Random rnd = new Random(); int id = rnd.Next(1, 7); string key = ""; string message = ""; //get guid from xml string fullPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/ApiKeys.xml"); XDocument doc = XDocument.Load(fullPath); XElement element = doc.Element("root").Elements("apikey").Elements("id").SingleOrDefault(x => x.Value == id.ToString()); if (element != null) { XElement parent = element.Parent; key = parent.Element("key").Value; message = "success"; } else { message = "fail"; } dynamic json = new ExpandoObject(); json.key = key; json.message = message; return Json(json); }
public override void Initialize() { _viewBag = new ExpandoObject(); var verb = _context.Request.HttpMethod; object methResult = null; var allParams = ReadRequestParameters(); var action = allParams.ContainsKey("action") ? allParams["action"].ToString() : null; var requestContentType = _context.Request.ContentType; bool hasConverter = _conversionService.HasConverter(requestContentType); var routeService = ServiceLocator.Locator.Resolve<IRoutingHandler>(); var cdd = _controller.WrapperDescriptor; for (int index = 0; index < _controller.Instance.Properties.Count; index++) { var property = _controller.Instance.Properties[index]; switch (property) { case ("HttpContext"): _controller.Instance.Set(property, _context); break; case ("Url"): _controller.Instance.Set(property, new UrlHelper(_context, routeService)); break; case ("ViewBag"): _controller.Instance.Set(property, _viewBag as dynamic); break; default: var prop = cdd.GetProperty(property); if (prop.SetterVisibility == ItemVisibility.Public) { var value = ServiceLocator.Locator.Resolve(prop.PropertyType); if (value != null) { _controller.Instance.Set(property, value); } } break; } } var methods = _controller.GetMethodGroup(action, verb).ToList(); bool methodInvoked = false; foreach (var method in methods) { if (TryInvoke(method, allParams, _controller.Instance, hasConverter, _context, false, out methResult)) { methodInvoked = true; break; } } if (!methodInvoked) { throw new HttpException(404, string.Format("Url '{0}' not found.", _context.Request.Url)); } _enumerableResult = (methResult as IEnumerable<IResponse>).GetEnumerator(); }
private dynamic GetBody(PropertyInfo pr) { dynamic expando = new System.Dynamic.ExpandoObject(); if (pr.PropertyType.IsPrimitive || pr.PropertyType == typeof(string)) { ((IDictionary <string, object>)expando)[pr.Name] = pr.PropertyType.FullName; return(expando); } var type = TypeLoader.Find(pr.PropertyType.FullName, _assemblies); var props = PropLoader.Get(type); foreach (var pr2 in props) { if (pr2.PropertyType.IsPrimitive || pr2.PropertyType == typeof(string)) { ((IDictionary <string, object>)expando)[pr2.Name] = pr2.PropertyType.FullName; } else { ((IDictionary <string, object>)expando)[pr2.Name] = GetBody(pr2); } } return(expando); }
public void ExpandoAsJoin() { var customers = new List<dynamic>(); for (int i = 0; i < 10; ++i) { string iter = i.ToString(); for (int j = 0; j < 3; ++j) { dynamic customer = new ExpandoObject(); customer.City = "Chicago" + iter; customer.Id = i; customer.Name = "Name" + iter; customer.CompanyName = "Company" + iter + j.ToString(); customers.Add(customer); } } var customers2 = new List<dynamic>(customers); var result = customers2.Cast<IDictionary<string, object>>().Query<IDictionary<string, object>, IDictionary<string, object>, dynamic>("SELECT this.City FROM this INNER JOIN that ON this.Id = that.Id", customers.Cast<IDictionary<string, object>>()); var answer = from c2 in customers2 join c in customers on c2.Id equals c.Id select c2.City; Assert.IsTrue(result.Any()); Assert.IsTrue(answer.SequenceEqual(result)); }
protected override void ShouldThrowAWobbly() { dynamic testDynamicObject = new ExpandoObject(); testDynamicObject.Bar = "BarPropertyValue"; DynamicShould .HaveProperty(testDynamicObject, "foo"); }
public void ExpandoAsSource() { var customers = new List<dynamic>(); for (int i = 0; i < 10; ++i) { string iter = i.ToString(); for (int j = 0; j < 3; ++j) { dynamic customer = new ExpandoObject(); customer.City = "Chicago" + iter; customer.Id = i; customer.Name = "Name" + iter; customer.CompanyName = "Company" + iter + j.ToString(); customers.Add(customer); } } // all this casting is just to get the answer and result into the same storage types for comparison var result = customers.Cast<IDictionary<string, object>>().Query<IDictionary<string, object>, dynamic>("SELECT City, Name FROM this").Cast<IDictionary<string, object>>(); var answer = customers.Select<dynamic, dynamic>(d => { dynamic o = new ExpandoObject(); o.City = d.City; o.Name = d.Name; return o; }).Cast<IDictionary<string, object>>(); Assert.IsTrue(result.Any()); Assert.IsTrue(answer.SequenceEqual(result, new DictionaryComparer<string, object>())); }
public HomeController(IStore store) : base("/") { Get["/{aggregate:guid}"] = parameters => { dynamic events = new ExpandoObject(); try { events.Result = store.GetEventsForAggregate(Guid.Parse(parameters.aggregate)).ToList<Event>(); } catch (AggregateNotFound ex) { events.Error = ex.GetType(); events.StatuCode = 404; events.Message = ex.Message; } catch (Exception ex) { events.Error = ex.GetType(); events.StatuCode = 500; events.Message = ex.Message; } return events; }; Post["/{aggregate:guid}"] = _ => { var eventList = this.Bind<RequestList>(); return 200; }; }
public void ReplaceNestedObjectTest() { dynamic doc = new ExpandoObject(); doc.SimpleDTO = new SimpleDTO() { IntegerValue = 5, IntegerList = new List<int>() { 1, 2, 3 } }; var newDTO = new SimpleDTO() { DoubleValue = 1 }; // create patch JsonPatchDocument patchDoc = new JsonPatchDocument(); patchDoc.Replace("SimpleDTO", newDTO); // serialize & deserialize var serialized = JsonConvert.SerializeObject(patchDoc); var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized); deserialized.ApplyTo(doc); Assert.Equal(1, doc.SimpleDTO.DoubleValue); Assert.Equal(0, doc.SimpleDTO.IntegerValue); Assert.Equal(null, doc.SimpleDTO.IntegerList); }
public static bool AreExpandoStructureEquals(ExpandoObject obj1, ExpandoObject obj2) { var obj1AsColl = (ICollection<KeyValuePair<string, object>>)obj1; var obj2AsDict = (IDictionary<string, object>)obj2; // Make sure they have the same number of properties if (obj1AsColl.Count != obj2AsDict.Count) return false; foreach (var pair in obj1AsColl) { if (!obj2AsDict.ContainsKey(pair.Key)) { return false; } else { //if (obj2AsDict[pair.Key].GetType() != pair.Value.GetType()) // return false; } } // Everything matches return true; }
public TResponse GetMeasurementConfig <TRequest, TResponse>(TRequest Request, Func <object, object> ExtensionFunction) where TRequest : class where TResponse : class { IDictionary <string, int[]> config = MessageConfig.FromJson($"{typeof(TRequest).Name}.json"); dynamic expando = new System.Dynamic.ExpandoObject(); Mapper <TRequest> .Map(Request, expando); byte[] bytes = MessageBuilder.CreateBytes(expando, config); this.socket.Send(bytes); if (ExtensionFunction != null) { ExtensionFunction(this.socket); } int bytesReceived = -1; byte[] receivedBytes = this.socket.Receive(out bytesReceived); config = MessageConfig.FromJson($"{typeof(TResponse).Name}.json"); dynamic expandoRec = MessageBuilder.CreateMessage(receivedBytes, config); TResponse response = default(TResponse); Mapper <TResponse> .Map(expandoRec, response); return(response); }
public IHttpActionResult AddToCalendar(FormDataCollection form) { string message = "success"; try { CylorDbEntities context = this.getContext(); string ThisDay = form.Get("ThisDay"); string sSelectUserId = form.Get("sSelectUserId"); int nCalendarUserListId; if (int.TryParse(sSelectUserId, out nCalendarUserListId) && DateFunctions.IsValidDate(ThisDay)) { CalendarItem instance = new CalendarItem(); instance.CalendarDate = DateTime.Parse(ThisDay); instance.CalendarUserListId = nCalendarUserListId; instance.EnteredDate = DateTime.Now.Date; context.CalendarItems.Add(instance); context.SaveChanges(); } } catch (Exception ex) { message = ex.Message; } dynamic json = new ExpandoObject(); json.message = message; return Json(json); }
protected override void DropMessageInternal(IIntegrationMessage integrationMessage) { DateTime nowUtc = DateTime.UtcNow; StreamReader streamReader; dynamic expando; IDictionary<string, object> associative; MongoCollection<BsonDocument> collection; expando = new ExpandoObject(); associative = new ExpandoObject(); streamReader = new StreamReader(integrationMessage.DataStream); foreach (KeyValuePair<string, object> metadata in integrationMessage.Metadata) associative.Add(metadata.Key, metadata.Value.SafeToString(null, null)); expando.Id = integrationMessage.RunTimeId; expando.CreationTimestamp = nowUtc; expando.ModificationTimestamp = nowUtc; expando.Charset = integrationMessage.ContentEncoding = streamReader.CurrentEncoding.WebName; expando.ContentType = integrationMessage.ContentType; expando.MessageClass = "unknown"; expando.MessageStateId = new Guid(MessageStateConstants.MESSAGE_STATE_CREATED); expando.MessageText = streamReader.ReadToEnd(); // TODO: inefficient buffered approach expando.Metadata = (IDictionary<string, object>)associative; expando = new BsonDocument((IDictionary<string, object>)expando); collection = this.AquireMessageCollection(); collection.Insert(expando); }
public MainModule() { Get["/"] = x => { return View["index"]; }; Get["/login"] = x => { dynamic model = new ExpandoObject(); model.Errored = this.Request.Query.error.HasValue; return View["login", model]; }; Post["/login"] = x => { var userGuid = UserDatabase.ValidateUser((string)this.Request.Form.Username, (string)this.Request.Form.Password); if (userGuid == null) { return Context.GetRedirect("~/login?error=true&username="******"/logout"] = x => { return this.LogoutAndRedirect("~/"); }; }
public void SuccessTest1() { using (IDocumentStore documentStore = new EmbeddableDocumentStore { RunInMemory = true }.Initialize()) { dynamic expando = new ExpandoObject(); using (IDocumentSession session = documentStore.OpenSession()) { session.Store(expando); RavenJObject metadata = session.Advanced.GetMetadataFor((ExpandoObject)expando); metadata[PropertyName] = RavenJToken.FromObject(true); session.SaveChanges(); } using (IDocumentSession session = documentStore.OpenSession()) { var loaded = session.Load<dynamic>((string)expando.Id); RavenJObject metadata = session.Advanced.GetMetadataFor((DynamicJsonObject)loaded); RavenJToken token = metadata[PropertyName]; Assert.NotNull(token); Assert.True(token.Value<bool>()); } } }
public void ApplyCommand(string issueId, string command, string comment, bool disableNotifications = false, string runAs = "") { if (!_connection.IsAuthenticated) { throw new InvalidRequestException(Language.YouTrackClient_CreateIssue_Not_Logged_In); } try { dynamic commandMessage = new ExpandoObject(); commandMessage.command = command; commandMessage.comment = comment; if (disableNotifications) commandMessage.disableNotifications = disableNotifications; if (!string.IsNullOrWhiteSpace(runAs)) commandMessage.runAs = runAs; _connection.Post(string.Format("issue/{0}/execute", issueId), commandMessage); } catch (HttpException httpException) { throw new InvalidRequestException(httpException.StatusDescription, httpException); } }
public LoginModule() { Get["/login"] = x => { dynamic model = new ExpandoObject(); model.LoginAttemptFailed = this.Request.Query.error.HasValue; return View["login", model]; }; Post["/login"] = x => { var model = this.Bind<LoginModel>(); var userId = Query(db => db.GetUserId(model.Username, model.Password)); if (userId == Guid.Empty) { return Context.GetRedirect("~/login?error=true"); } return this.LoginAndRedirect(userId, DateTime.Now.AddDays(7), "~/home"); }; Get["/logout"] = x => { return this.LogoutAndRedirect("~/index"); }; }
public IActionResult listRoutesByUserId(int userId) { if (userId <= 0 || userId == null) { return(StatusCode((int)HttpStatusCode.BadRequest, new { ErrorMessage = "Please enter userId" })); } List <dynamic> listRoutesDetails = new List <dynamic>(); try { DataTable dt = Data.Route.listRoutesByUserId(userId); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { dynamic listRoutes = new System.Dynamic.ExpandoObject(); listRoutes.routeId = (int)dt.Rows[i]["routeId"]; listRoutes.routeName = (dt.Rows[i]["routeName"] == DBNull.Value ? "" : dt.Rows[i]["routeName"].ToString()); listRoutes.comments = (dt.Rows[i]["comments"] == DBNull.Value ? "" : dt.Rows[i]["comments"].ToString()); listRoutes.designatedCharityId = (dt.Rows[i]["designatedCharityId"] == DBNull.Value ? 0 : (int)dt.Rows[i]["designatedCharityId"]); listRoutes.designatedCharityName = (dt.Rows[i]["designatedCharityName"] == DBNull.Value ? "" : dt.Rows[i]["designatedCharityName"].ToString()); listRoutes.isPrivate = (dt.Rows[i]["isPrivate"] == DBNull.Value ? false : (bool)dt.Rows[i]["isPrivate"]); listRoutes.createdDate = (dt.Rows[i]["createdDate"] == DBNull.Value ? "" : dt.Rows[i]["createdDate"].ToString()); listRoutes.startingPointId = (dt.Rows[i]["startingPointId"] == DBNull.Value ? 0 : (int)dt.Rows[i]["startingPointId"]); listRoutes.startingPointlatitude = (dt.Rows[i]["startingPointlatitude"] == DBNull.Value ? "" : dt.Rows[i]["startingPointlatitude"].ToString()); listRoutes.startingPointlongitude = (dt.Rows[i]["startingPointlongitude"] == DBNull.Value ? "" : dt.Rows[i]["startingPointlongitude"].ToString()); listRoutes.startingPointcountry = (dt.Rows[i]["startingPointcountry"] == DBNull.Value ? "" : dt.Rows[i]["startingPointcountry"].ToString()); listRoutes.startingPointstate = (dt.Rows[i]["startingPointstate"] == DBNull.Value ? "" : dt.Rows[i]["startingPointstate"].ToString()); listRoutes.startingPointcityName = (dt.Rows[i]["startingPointcityName"] == DBNull.Value ? "" : dt.Rows[i]["startingPointcityName"].ToString()); listRoutes.startingPointaddress = (dt.Rows[i]["startingPointaddress"] == DBNull.Value ? "" : dt.Rows[i]["startingPointaddress"].ToString()); listRoutes.endPointId = (dt.Rows[i]["endPointId"] == DBNull.Value ? 0 : (int)dt.Rows[i]["endPointId"]); listRoutes.endPointlatitude = (dt.Rows[i]["endPointlatitude"] == DBNull.Value ? "" : dt.Rows[i]["endPointlatitude"].ToString()); listRoutes.endPointlongitude = (dt.Rows[i]["endPointlongitude"] == DBNull.Value ? "" : dt.Rows[i]["endPointlongitude"].ToString()); listRoutes.endPointcountry = (dt.Rows[i]["endPointcountry"] == DBNull.Value ? "" : dt.Rows[i]["endPointcountry"].ToString()); listRoutes.endPointstate = (dt.Rows[i]["endPointstate"] == DBNull.Value ? "" : dt.Rows[i]["endPointstate"].ToString()); listRoutes.endPointcityName = (dt.Rows[i]["endPointcityName"] == DBNull.Value ? "" : dt.Rows[i]["endPointcityName"].ToString()); listRoutes.endPointaddress = (dt.Rows[i]["endPointaddress"] == DBNull.Value ? "" : dt.Rows[i]["endPointaddress"].ToString()); listRoutes.routePoints = (dt.Rows[i]["routePoints"] == DBNull.Value ? "" : dt.Rows[i]["routePoints"].ToString()); listRoutes.routePointNames = (dt.Rows[i]["routePointNames"] == DBNull.Value ? "" : dt.Rows[i]["routePointNames"].ToString()); listRoutes.totalMiles = (dt.Rows[i]["totalMiles"] == DBNull.Value ? "" : String.Concat(dt.Rows[i]["totalMiles"], "mi").ToString()); listRoutes.image = (dt.Rows[i]["path"] == DBNull.Value ? "" : dt.Rows[i]["path"].ToString()); listRoutes.markerUrlForDisplays = (dt.Rows[i]["markerUrlForDisplays"] == DBNull.Value ? "" : dt.Rows[i]["markerUrlForDisplays"].ToString()); listRoutesDetails.Add(listRoutes); } return(StatusCode((int)HttpStatusCode.OK, listRoutesDetails)); } else { return(StatusCode((int)HttpStatusCode.OK, listRoutesDetails)); } } catch (Exception e) { string SaveErrorLog = Data.Common.SaveErrorLog("listRoutesByUserId", e.Message); return(StatusCode((int)HttpStatusCode.InternalServerError, new { ErrorMessage = e.Message })); } }
public Dictionary <string, object> ExcuteReaderWithSPDyanamicObject(string storeProcName) { dynamic MyDynamic = new System.Dynamic.ExpandoObject(); var lstdicts = dBOperation.ExcuteReaderWithSP(storeProcName, lstDBParamaters).ToCustomObjectOfDictinory <System.Dynamic.ExpandoObject>(); ClearParameters(); return(lstdicts); }
/// <summary> /// 获取默认密码和其md5加密码 /// </summary> /// <returns></returns> public dynamic GetUserIntilPassWord() { string dePassword = "******"; dynamic result = new System.Dynamic.ExpandoObject(); result.Password = dePassword; result.strValue = GetMD5Password(dePassword); return(result); }
public static IDictionary <string, object> TransformDynamicProductDetailsForJson(Models.Search.Result searchResult) { IDictionary <string, object> product = new System.Dynamic.ExpandoObject(); product = searchResult.Document; product = LocationResultsTransforms.TransformLocationResults(product); product["images"] = searchResult.Images; return(product); }
private static dynamic ToDynamic(IDictionary <string, object> dict) { dynamic result = new System.Dynamic.ExpandoObject(); foreach (var entry in dict) { (result as ICollection <KeyValuePair <string, object> >).Add(new KeyValuePair <string, object>(entry.Key, entry.Value)); } return(result); }
private void EditTask() { var ctl = new TaskItemDetailsView(); ctl.DataContext = this; dynamic param = new System.Dynamic.ExpandoObject(); param.Title = this.Display; param.Control = ctl; Workspace.Instance.ViewModel.Overlay.SetOverlay(AppConstants.OverlayContent, param); }
private void ViewDomains() { Control ctl = new DomainsView(); //ctl.DataContext = this; ctl.DataContext = Workspace.Instance.ViewModel.Settings; dynamic param = new System.Dynamic.ExpandoObject(); param.Title = "Content Domains"; param.Control = ctl; Workspace.Instance.ViewModel.Overlay.SetOverlay(AppConstants.OverlayContent, param); }
public QvDataContractResponse getPreview(String tableName) { //need to modify this to return an actual preview string[] fields = getFieldNamesForTable(tableName); List <dynamic> preview = new List <dynamic>(); dynamic values = new System.Dynamic.ExpandoObject(); values.qValues = fields; preview.Add(values); return(new Info { qMessage = JsonConvert.SerializeObject(preview.ToArray()) }); }
public object GetAdminToken() { dynamic data = new System.Dynamic.ExpandoObject(); data.sub = "C675A96B-851E-49C2-BDB8-A6BB5AA41556"; data.name = "C675A96B-851E-49C2-BDB8-A6BB5AA41556"; data.fullname = "admin admin"; data.email = "*****@*****.**"; data.role = new List <string>() { "admin" }; return(data); }
public object GetGuestToken() { dynamic data = new System.Dynamic.ExpandoObject(); data.sub = "A9EC0802-AEF9-4D72-A686-9D4C110A3B94"; data.name = "A9EC0802-AEF9-4D72-A686-9D4C110A3B94"; data.fullname = "admin admin"; data.email = "*****@*****.**"; data.role = new List <string>() { "admin" }; return(data); }
// Load document content upon request public dynamic GetContent(long id) { Document document = this.documentRepository.GetByID(id); dynamic content = new System.Dynamic.ExpandoObject(); content.Id = id; content.Txt = this.resourceService.LoadResource(document.Filename); dynamic wrapper = new ExpandoObject(); wrapper.content = content; return(wrapper); }
/// <summary> /// Executes the test call /// </summary> public static dynamic ExecuteIt(Func <dynamic> action) { dynamic result = new System.Dynamic.ExpandoObject(); try { result = action.Invoke(); } catch (Exception x) { result.Passed = false; result.Result = new HtmlString(BuildExceptionMessage(x).Trim()); result.Message = x.Message; result.Threw = true; } return(result); }
public static dynamic ToDyn(this DataRow dr, Dictionary <String, object> template) { var eo = new System.Dynamic.ExpandoObject(); var eoColl = (ICollection <KeyValuePair <String, object> >)eo; foreach (var kvp in template) { KeyValuePair <String, object> newKvp = new KeyValuePair <string, object>(kvp.Key, dr.Field <object>(kvp.Key)); eoColl.Add(newKvp); } dynamic eoDynamic = eo; return(eoDynamic); }
public dynamic FormToOjbect( ) { var tablename = FormCollection["_tablename"]; var cols = DB.UniClient.DbMaintenance.GetColumnInfosByTableName(tablename); dynamic result = new System.Dynamic.ExpandoObject(); foreach (var cinfo in cols) { if (FormCollection.ContainsKey(cinfo.DbColumnName)) { (result as ICollection <KeyValuePair <string, object> >).Add(new KeyValuePair <string, object>(cinfo.DbColumnName, FormCollection[cinfo.DbColumnName])); } } return(result); }
private List <dynamic> SendTerminateEmail(List <RENTAL_AGREEMENT> forbros) { List <dynamic> dynamicjobs = new List <dynamic>(); INF370Entities db = new INF370Entities(); foreach (RENTAL_AGREEMENT Jb in forbros) { dynamic dynamicjob = new System.Dynamic.ExpandoObject(); var Property = db.PROPERTies.Where(zz => zz.PROPERTYID == Jb.PROPERTYID).Select(zz => zz.ADDRESS); dynamicjob.PropertyAddress = db.PROPERTies.Where(zz => zz.PROPERTYID == Jb.PROPERTYID).Select(zz => zz.ADDRESS); dynamicjob.PropertyID = Jb.PROPERTYID; dynamicjob.RefferenceNo = Jb.REFERENCE_NO; dynamicjobs.Add(dynamicjob); } return(dynamicjobs); }
public object GetGroupOrderModel(string skuId, int count, long GroupActionId, long?GroupId = null) { CheckUserLogin(); dynamic d = new System.Dynamic.ExpandoObject(); Mall.DTO.MobileOrderDetailConfirmModel result = OrderApplication.SubmitByGroupId(CurrentUser.Id, skuId, count, GroupActionId, GroupId); if (result.Address != null) { //result.Address.MemberInfo = new UserMemberInfo(); d.Address = result.Address; } bool canIntegralPerMoney = true, canCapital = true; CanDeductible(out canIntegralPerMoney, out canCapital); d.canIntegralPerMoney = canIntegralPerMoney; d.canCapital = canCapital; d.IsOpenStore = SiteSettingApplication.SiteSettings != null && SiteSettingApplication.SiteSettings.IsOpenStore; d.ProvideInvoice = ShopApplication.HasProvideInvoice(result.products.Select(s => s.shopId).Distinct().ToList()); d.products = result.products; d.totalAmount = result.totalAmount; d.Freight = result.Freight; d.orderAmount = result.orderAmount; d.integralPerMoney = result.integralPerMoney; d.integralPerMoneyRate = result.integralPerMoneyRate; d.userIntegralMaxDeductible = result.userIntegralMaxDeductible; d.IntegralDeductibleRate = result.IntegralDeductibleRate; d.userIntegrals = result.userIntegrals; d.capitalAmount = result.capitalAmount; d.memberIntegralInfo = result.memberIntegralInfo; d.InvoiceContext = result.InvoiceContext; //发票类容 d.InvoiceTitle = result.InvoiceTitle; //发票抬头 d.cellPhone = result.cellPhone; //默认收票人手机 d.email = result.email; //默认收票人邮箱 d.vatInvoice = result.vatInvoice; //默认增值税发票 d.invoiceName = result.invoiceName; //默认抬头(普通、电子) d.invoiceCode = result.invoiceCode; //默认税号(普通、电子) d.IsCashOnDelivery = result.IsCashOnDelivery; d.Sku = result.Sku; d.Count = result.Count; d.shopBranchInfo = result.shopBranchInfo; return(Json(result)); }
/// <summary> /// 获取购物车提交页面的数据 /// </summary> /// <param name="cartItemIds">购物车物品id集合</param> /// <returns></returns> object GetSubmitByCartModel(string cartItemIds = "") { CheckUserLogin(); var result = OrderApplication.GetMobileSubmiteByCart(CurrentUserId, cartItemIds); //解决循环引用的序列化的问题 dynamic address = new System.Dynamic.ExpandoObject(); if (result.Address != null) { var add = new { ShippingId = result.Address.Id, ShipTo = result.Address.ShipTo, CellPhone = result.Address.Phone, FullRegionName = result.Address.RegionFullName, FullAddress = result.Address.RegionFullName + " " + result.Address.Address, Address = result.Address.Address, RegionId = result.Address.RegionId }; address = add; } else { address = null; } return(Json(new { Status = "OK", Data = new { Address = address, IsCashOnDelivery = result.IsCashOnDelivery, InvoiceContext = result.InvoiceContext, products = result.products, integralPerMoney = result.integralPerMoney, userIntegrals = result.userIntegrals, TotalAmount = result.totalAmount, Freight = result.Freight, orderAmount = result.orderAmount, IsOpenStore = SiteSettingApplication.GetSiteSettings() != null && SiteSettingApplication.GetSiteSettings().IsOpenStore } })); }
/// <summary> /// 获取立即购买提交页面的数据 /// </summary> /// <param name="skuIds">库存ID集合</param> /// <param name="counts">库存ID对应的数量</param> object GetSubmitModelById(string skuId, int count) { CheckUserLogin(); var result = OrderApplication.GetMobileSubmit(CurrentUserId, skuId.ToString(), count.ToString()); dynamic d = new System.Dynamic.ExpandoObject(); dynamic add = new System.Dynamic.ExpandoObject(); if (result.Address != null) { add = new { ShippingId = result.Address.Id, ShipTo = result.Address.ShipTo, CellPhone = result.Address.Phone, FullRegionName = result.Address.RegionFullName, FullAddress = result.Address.RegionFullName + " " + result.Address.Address, Address = result.Address.Address, RegionId = result.Address.RegionId }; } else { add = null; } d.Status = "OK"; d.Data = new { InvoiceContext = result.InvoiceContext, products = result.products, integralPerMoney = result.integralPerMoney, userIntegrals = result.userIntegrals, TotalAmount = result.totalAmount, Freight = result.Freight, orderAmount = result.orderAmount, IsCashOnDelivery = result.IsCashOnDelivery, IsOpenStore = SiteSettingApplication.GetSiteSettings() != null && SiteSettingApplication.GetSiteSettings().IsOpenStore, Address = add }; return(d); }
public IHttpActionResult GetWxUser(string code, string iv, string encryptedData) { string Appid = "wx12a7e3bf7a31d815"; string Secret = ConfigHelper.GetConfig("Wx_Secret");//ConfigurationManager.AppSettings["Wx_Secret"]; //"b4722d8a6a5629ed7717e58d1af431ba"; string grant_type = "authorization_code"; //向微信服务端 使用登录凭证 code 获取 session_key 和 openid string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + Appid + "&secret=" + Secret + "&js_code=" + code + "&grant_type=" + grant_type; string type = "utf-8"; WxHelper wh = new WxHelper(); string html = wh.GetUrlToHtml(url, type);//获取微信服务器返回字符串 //将字符串转换为json格式 JObject jo = (JObject)JsonConvert.DeserializeObject(html); dynamic res = new System.Dynamic.ExpandoObject(); try { //微信服务器验证成功 res.openid = jo["openid"].ToString(); res.session_key = jo["session_key"].ToString(); } catch (Exception) { //微信服务器验证失败 res.errcode = jo["errcode"].ToString(); res.errmsg = jo["errmsg"].ToString(); } if (((IDictionary <string, object>)res).ContainsKey("openid") && !string.IsNullOrEmpty(res.openid)) { var decryptres = wh.AESDecrypt(encryptedData, res.session_key, iv); JObject userInfo = (JObject)JsonConvert.DeserializeObject(decryptres); res.userinfo = userInfo; } return(Ok(res)); }
/// <summary> /// Shape a list /// </summary> /// <typeparam name="TSource"></typeparam> /// <param name="obj"></param> /// <param name="fields"></param> /// <returns></returns> public static object ShapeList <TSource>(this IList <TSource> obj, string fields) { List <string> lstOfFields = new List <string>(); if (string.IsNullOrEmpty(fields)) { return(obj); } lstOfFields = fields.Split(',').ToList(); List <string> lstOfFieldsToWorkWith = new List <string>(lstOfFields); List <System.Dynamic.ExpandoObject> lsobjectToReturn = new List <System.Dynamic.ExpandoObject>(); if (!lstOfFieldsToWorkWith.Any()) { return(obj); } else { foreach (var kj in obj) { System.Dynamic.ExpandoObject objectToReturn = new System.Dynamic.ExpandoObject(); foreach (var field in lstOfFieldsToWorkWith) { try { var fieldValue = kj.GetType() .GetProperty(field.Trim(), BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) .GetValue(kj, null); ((IDictionary <String, Object>)objectToReturn).Add(field.Trim(), fieldValue); } catch { } } lsobjectToReturn.Add(objectToReturn); } } return(lsobjectToReturn); }
static void Main(string[] args) { dynamic sampleObject = new System.Dynamic.ExpandoObject(); sampleObject.MyName = "Omer"; sampleObject.myMethod = (Action)(() => Console.WriteLine("Omer")); sampleObject.myFunc = (Func <dynamic, bool>)((dynamic c) => { if (c != null) { return(true); } else { return(false); } }); Console.WriteLine(sampleObject.MyName); sampleObject.myMethod(); Console.WriteLine(sampleObject.myFunc(null)); }