Search Results

Search found 143 results on 6 pages for 'indexer'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • using indexer to retrieve Linq to SQL object from datastore

    - by fearofawhackplanet
    class UserDatastore : IUserDatastore { ... public IUser this[Guid userId] { get { User user = (from u in _dataContext.Users where u.Id == userId select u).FirstOrDefault(); return user; } } ... } One of the developers in our team is arguing that an indexer in the above situation is not appropriate and that a GetUser(Guid id) method should be prefered. The arguments being that: 1) We aren't indexing into an in-memory collection, the indexer is basically performing a hidden SQL query 2) Using a Guid in an indexer is bad (FxCop flagged this also) 3) Returning null from an indexer isn't normal behaviour 4) An API user generally wouldn't expect any of this behaviour I agree to an extent with (most of) these points. But I'm also inclined to argue that one of the characteristics of Linq is to abstract the database access to make it appear that you're simply working with a bunch of collections, even though the lazy evaluation paradigm means those collections aren't evaluated until you run a query over them. It doesn't seem inconsistent to me to access the datastore in the same manner as if it was a concrete in-memory collection here. Also bearing in mind this is an inherited codebase which uses this pattern extensively and consistently, is it worth the refactoring? I accept that it might have been better to use a Get method from the start, but I'm not yet convinced that it's completely incorrect to be using an indexer. I'd be interested to hear all opinions, thanks.

    Read the article

  • Returning IEnumerable from an indexer, bad practice?

    - by fearofawhackplanet
    If I had a CarsDataStore representing a table something like: Cars -------------- Ford | Fiesta Ford | Escort Ford | Orion Fiat | Uno Fiat | Panda Then I could do IEnumerable<Cars> fords = CarsDataStore["Ford"]; Is this a bad idea? It's iconsistent with the other datastore objects in my api (which all have a single column PK indexer), and I'm guessing most people don't expect an indexer to return a collection in this situation.

    Read the article

  • no Jquery only Javascrip fadein function with cleartype fot text

    - by Chetan
    Sorry guys.. I am not familiar with JavaScrip anymore but I need to add clear type of some thing which can make text anti-aliased in IE7 browser. My script as follow // JavaScript Document var CurrentDivIndex=0; var TimeOutValue; var btn; var TimeToFade = 1000.0; function ShowDivSlideShow() { try { if(CurrentDivIndex == 5) CurrentDivIndex=0; CurrentDivIndex++; //alert("Banner" + CurrentDivIndex); //alert(CurrentDivIndex); var Indexer=1; while(Indexer<6) { var DivToShow=document.getElementById("Banner" + Indexer); DivToShow.style.display = "none"; btn=document.getElementById("btnb" + Indexer); btn.setAttribute("class","none"); Indexer++; } var DivToShow=document.getElementById("Banner" + CurrentDivIndex); DivToShow.style.display = "block"; btn=document.getElementById("btnb" + CurrentDivIndex); btn.setAttribute("class","activeSlide"); // btn.className="activeSlide"; fadeIn(); TimeOutValue=setTimeout("ShowDivSlideShow()",6000); } catch(err) { alert(err) } } function ShowCustomDiv(CurrentDivIndexRec) { clearTimeout(TimeOutValue) CurrentDivIndex=CurrentDivIndexRec var Indexer=1; while(Indexer<6) { if(CurrentDivIndex==Indexer) { Indexer++; continue; } var DivToShow=document.getElementById("Banner" + Indexer); DivToShow.style.display = "none"; btn=document.getElementById("btnb" + Indexer); btn.setAttribute("class","none"); Indexer++; } var DivToShow=document.getElementById("Banner" + CurrentDivIndex); DivToShow.style.display = "block"; btn=document.getElementById("btnb" + CurrentDivIndex); btn.setAttribute("class","activeSlide"); btn.className="activeSlide" fadeIn(); } function ShowDivSlideShowWithTimeOut(CurrentDivIndexRec) { clearTimeout(TimeOutValue) CurrentDivIndex=CurrentDivIndexRec; var Indexer=1; while(Indexer<6) { if(CurrentDivIndex==Indexer) { Indexer++; continue; } var DivToShow=document.getElementById("Banner" + Indexer); DivToShow.style.display = "none"; btn=document.getElementById("btnb" + Indexer); btn.setAttribute("class","none"); Indexer++; } var DivToShow=document.getElementById("Banner" + CurrentDivIndexRec); DivToShow.style.display = "block"; btn=document.getElementById("btnb" + CurrentDivIndexRec); btn.setAttribute("class","activeSlide"); TimeOutValue=setTimeout("ShowDivSlideShow()",6000); } function ShowCustomDivOnClick(CurrentDivIndexRec) { clearTimeout(TimeOutValue) CurrentDivIndex=CurrentDivIndexRec; var Indexer=1; while(Indexer<6) { if(CurrentDivIndex==Indexer) { Indexer++; continue; } var DivToShow=document.getElementById("Banner" + Indexer); DivToShow.style.display = "none"; btn=document.getElementById("btnb" + Indexer); btn.setAttribute("class","none"); Indexer++; } var DivToShow=document.getElementById("Banner" + CurrentDivIndexRec); DivToShow.style.display = "block"; btn=document.getElementById("btnb" + CurrentDivIndexRec); btn.setAttribute("class","activeSlide"); fadeIn(); TimeOutValue=setTimeout("ShowDivSlideShow()",6000); } function setOpacity(level) { element=document.getElementById("Banner" + CurrentDivIndex); element.style.opacity = level; element.style.MozOpacity = level; element.style.KhtmlOpacity = level; element.style.filter = "alpha(opacity=" + (level * 100) + ");"; } var duration = 300; /* 1000 millisecond fade = 1 sec */ var steps = 10; /* number of opacity intervals */ var delay = 6000; /* 5 sec delay before fading out */ function fadeIn(){ for (i = 0; i <= 1; i += (1 / steps)) { setTimeout("setOpacity(" + i + ")", i * duration); } // setTimeout("fadeOut()", delay); } function fadeOut() { for (i = 0; i <= 1; i += (1 / steps)) { setTimeout("setOpacity(" + (1 - i) + ")", i * duration); } setTimeout("fadeIn()", duration); } //end of script Now I am very confused where to add : $('#slideshow').cycle({ cleartype: 1 // enable cleartype corrections }); or $('#fadingElement').fadeIn(2000, function(){ $(this).css('filter',''); }); so it will work... Please Help me...

    Read the article

  • laptop and it drastically reduces the performance of my machine as the Indexer is constantly running

    - by Sakthy
    I get the below error on my laptop and it drastically reduces the performance of my machine as the Indexer is constantly running. Please identify a solution except re-installation ? Faulting application name: SearchIndexer.exe, version: 7.0.7600.16385, time stamp: 0x4a5bcdd0 Faulting module name: TQUERY.DLL, version: 7.0.7600.16385, time stamp: 0x4a5bdb21 Exception code: 0xc0000006 Fault offset: 0x0002e5c2 Faulting process id: 0xbe0 Faulting application start time: 0x01cd0752bd78cce1 Faulting application path: C:\Windows\system32\SearchIndexer.exe Faulting module path: C:\Windows\system32\TQUERY.DLL Report Id: 16ce8a2f-7346-11e1-840a-a92a5ee507c3 EventID: 1000

    Read the article

  • Fixing Outlook 2010's notorious 'Disabled Search Indexer' Add-in problem

    - by Muhimbi
    I have been impressed with the improvements in search introduced in Outlook 2010. Unfortunately, in the last week search has stopped working for me. I have tried all the obvious repair tasks such as repairing office, disabling all add-ins, rebuilding the index, compacting the PST, but no luck. It appears that 'mssphtb.dll' (Used by search) keeps crashing and as a result Outlook Disables it. I have tried re-enabling it, but Outlook immediately disables it again. I have had a look in the Windows Event Log as well, but Outlook does not appear to log any errors that occur when loading add-ins. A lot of people appear to have the same problem, but no fixes so far. I am considering installing Xobni, but I prefer to make Outlook work the way it is supposed to and not rely on 3rd party applications.

    Read the article

  • Indexer in C sharp.

    - by Jacksquad
    Hello guys, i got a problem while overloading indexer property. public class ClassName { private int[] a; private int[] b; private string[] c; private string[] d; public int this[int pos] { get{ return a[pos];} set{a[pos] = value;} } public int this[int pos] { get{ return b[pos];} set{b[pos] = value;} } public int this[int pos] { get{ return c[pos];} set{c[pos] = value;} } public int this[int pos] { get{ return d[pos];} set{d[pos] = value;} } } /* I AM GETTING "Error 1 'Class1 variables' already defines a member called 'this' with the same parameter types" Please suggest me how to implement this?

    Read the article

  • Interface that Entails the Implementation of Indexer

    - by Ngu Soon Hui
    I am looking for a framework-defined interface that declares indexer. In other words, I am looking for something like this: public interface IYourList<T> { T this[int index] { get; set; } } I just wonder whether .Net framework contains such interface? If yes, what is it called? You might ask why I can't just create the interface myself. Well, I could have. But if .Net framework already has that why should I reinvent the wheel?

    Read the article

  • Issue with getting 2 chars from string using indexer

    - by Learner
    I am facing an issue in reading char values. See my program below. I want to evaluate an infix expression. As you can see I want to read '10' , '*', '20' and then use them...but if I use string indexer s[0] will be '1' and not '10' and hence I am not able to get the expected result. Can you guys suggest me something? Code is in c# class Program { static void Main(string[] args) { string infix = "10*2+20-20+3"; float result = EvaluateInfix(infix); Console.WriteLine(result); Console.ReadKey(); } public static float EvaluateInfix(string s) { Stack<float> operand = new Stack<float>(); Stack<char> operator1 = new Stack<char>(); int len = s.Length; for (int i = 0; i < len; i++) { if (isOperator(s[i])) // I am having an issue here as s[i] gives each character and I want the number 10 operator1.Push(s[i]); else { operand.Push(s[i]); if (operand.Count == 2) Compute(operand, operator1); } } return operand.Pop(); } public static void Compute(Stack<float> operand, Stack<char> operator1) { float operand1 = operand.Pop(); float operand2 = operand.Pop(); char op = operator1.Pop(); if (op == '+') operand.Push(operand1 + operand2); else if(op=='-') operand.Push(operand1 - operand2); else if(op=='*') operand.Push(operand1 * operand2); else if(op=='/') operand.Push(operand1 / operand2); } public static bool isOperator(char c) { bool result = false; if (c == '+' || c == '-' || c == '*' || c == '/') result = true; return result; } } }

    Read the article

  • How can I apply indexer to Dictionary VALUES (C#3.0)

    - by Newbie
    I have done a program string[] arrExposureValues = stock.ExposureCollection[dt] .Values.ToArray(); for(int i=0;i<arrExposureValues .length;i++) Console.WriteLine(arrExposureValues[i]); Nothing wrong and works fine. But is it possible to do something like the below for(int i=0;i<stock.ExposureCollection[dt].Count;i++) Console.WriteLine(stock.ExposureCollection[dt].Values[i]); This is just for my sake of knowledge (Basically trying to accomplish the same in one line). Note: ExposureCollection is a dictionary object Dictionary<DateTime, Dictionary<string, string>> First of all I have the doubt if it is at all possible! I am using C#3.0. Thanks.

    Read the article

  • How can I apply indexer to Dictionary.Values (C# 3.0)

    - by Newbie
    I have done a program string[] arrExposureValues = stock.ExposureCollection[dt].Values.ToArray(); for(int i = 0; i < arrExposureValues.Length; i++) Console.WriteLine(arrExposureValues[i]); Nothing wrong and works fine. But is it possible to do something like the below for(int i = 0; i < stock.ExposureCollection[dt].Count; i++) Console.WriteLine(stock.ExposureCollection[dt].Values[i]); This is just for my sake of knowledge (Basically trying to accomplish the same in one line). Note: ExposureCollection is Dictionary<DateTime, Dictionary<string, string>> First of all I have the doubt if it is at all possible! I am using C# 3.0. Thanks.

    Read the article

  • How do you escape parentheses in a Binding indexer

    - by Chris S
    I have the following XAML: <Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource MyDataKey}}"> <TextBox Name="_myId" Text="{Binding MyDictionary[(Textbox.Name)]" /> </Grid> But it thinks the key in my dictionary is called "(Textbox.Name)", instead of "_myId". The format below works, where I have a property in my class called "_myId": <TextBox Name="_myId" Text="{Binding (Textbox.Name)" /> I've tried using ^ and \ to escape the brackets. Is this syntax supported? I'm trying to avoid duplication of the name in two attributes.

    Read the article

  • SharePoint 2010 Hosting :: Error Message - Your search cannot be completed because this site is not assigned to an indexer

    - by mbridge
    Error when we are trying to access search in sharepoint site: "Your search cannot be completed because this site is not assigned to an indexer. Contact your administrator for more information." Solving Problem: 1. Go to SharePoint Central Administration > Application Management > Content Databases (Underneath SharePoint Web Application Management). 2. Select the correct SharePoint web application – click on the name of the Content databases  - this will open the  “Manage Content Database Settings” page. 3. Make sure that the Search Server is set on the “Manage Content Database Settings” page. Hope it helps!!

    Read the article

  • Google menace de ne plus indexer la presse française si une taxe sur le référencement est votée : qu'en pensez-vous ?

    Google menace de ne plus indexer la presse française si une taxe sur le référencement venait à être votée Google vient de lancer un ultimatum à la presse française et au gouvernement en menaçant de déréférencer les contenus des éditeurs en cas d'adoption de la taxe Google. L'Association de la presse d'information politique et générale (IPG) et le Syndicat de la presse quotidienne nationale ont adressé en septembre dernier une ébauche d'un projet de loi au gouvernement français, visant à l'instauration d'une taxe Google. Ceux-ci estiment que le géant de la recherche tire profit de leurs contenus et actualités pour enrichir son moteur de recherche, permettant à celui-ci de générer de...

    Read the article

  • Lucene: Wildcards are missing from index

    - by Eleasar
    Hi - i am building a search index that contains special names - containing ! and ? and & and + and ... I have to tread the following searches different: me & you me + you But whatever i do (did try with queryparser escaping before indexing, escaped it manually, tried different indexers...) - if i check the search index with Luke they do not show up (question marks and @-symbols and the like show up) The logic behind is that i am doing partial searches for a live suggestion (and the fields are not that large) so i split it up into "m" and "me" and "+" and "y" and "yo" and "you" and then index it (that way it is way faster than a wildcard query search (and the index size is not a big problem). So what i would need is to also have this special wildcard characters be inserted into the index. This is my code: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Lucene.Net.Analysis; using Lucene.Net.Util; namespace AnalyzerSpike { public class CustomAnalyzer : Analyzer { public override TokenStream TokenStream(string fieldName, TextReader reader) { return new ASCIIFoldingFilter(new LowerCaseFilter(new CustomCharTokenizer(reader))); } } public class CustomCharTokenizer : CharTokenizer { public CustomCharTokenizer(TextReader input) : base(input) { } public CustomCharTokenizer(AttributeSource source, TextReader input) : base(source, input) { } public CustomCharTokenizer(AttributeFactory factory, TextReader input) : base(factory, input) { } protected override bool IsTokenChar(char c) { return c != ' '; } } } The code to create the index: private void InitIndex(string path, Analyzer analyzer) { var writer = new IndexWriter(path, analyzer, true); //some multiline textbox that contains one item per line: var all = new List<string>(txtAllAvailable.Text.Replace("\r","").Split('\n')); foreach (var item in all) { writer.AddDocument(GetDocument(item)); } writer.Optimize(); writer.Close(); } private static Document GetDocument(string name) { var doc = new Document(); doc.Add(new Field( "name", DeNormalizeName(name), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field( "raw_name", name, Field.Store.YES, Field.Index.NOT_ANALYZED)); return doc; } (Code is with Lucene.net in version 1.9.x (EDIT: sorry - was 2.9.x) but is compatible with Lucene from Java) Thx

    Read the article

  • Using Moq to set indexers in C#

    - by emddudley
    I'm having trouble figuring out how to set indexers in C# with Moq. The Moq documentation is weak, and I've done a lot of searching... what I'd like to do is similar in the solution to How to Moq Setting an Indexed property: var someClass = new Mock<ISomeClass>(); someClass.SetupSet(o => o.SomeIndexedProperty[3] = 25); I want to modify the above to work for any index and any value so I can just do something like this: someClass.Object.SomeIndexedProperty[1] = 5; Currently I have the following, which works great for the indexed property getter, but if I ever set the value Moq ignores it: var someValues = new int[] { 10, 20, 30, 40 }; var someClass = new Mock<ISomeClass>(); someClass.Setup(o => o.SomeIndexedProperty[It.IsAny<int>()]) .Returns<int>(index => someValues[index]); // Moq doesn't set the value below, so the Assert fails! someClass.Object.SomeIndexedProperty[3] = 25; Assert.AreEqual(25, someClass.Object.SomeIndexedProperty[3]);

    Read the article

  • How do I access the enumerated item with an indexer and assign array string to it for display?

    - by g00p3k
    EDITED: Updated 3/23/09. See rest of post at bottom. I'm still having trouble with the indexer. Anymore help or examples would really help me out. Write a class, MyCourses, that contains an enumeration of all the courses that you are currently taking. This enum should be nested inside of your class MyCourses. Your class should also have an array field that provides a short description (as a String) of each of your courses. Write an indexer that takes one of your enumerated courses as an index and returns the String description of the course. Write a class MyFriends that contains an indexer that provides access to the names of your friends. namespace IT274_Unit4Project { public class MyCourses { // enumeration that contains an enumeration of all the courses that // student is currently enrolled in public enum CourseName {IT274= 0,CS210 = 1} // array field that provides short description for each of classes, // returns string description of the course private String[] courseDescription = {"Intermediate C#: Teaches intermediate elements of C# programming and software design", "Career Development Strategies: Teaches principles for career progression, resume preparation, and overall self anaylsis"}; // indexer that takes one of the enumerated courses as an index // and returns the String description of the course public String this[CourseName index] { get { if (index == 1) return courseDescription[0]; else return courseDescription[1]; } set { if (index == 1) courseDescription[0] = value; else courseDescription[1] = value; } } } }//end public class MyCourses I'm working on this homework project and having trouble understanding the text explaining how to correctly take the accessed value of the enumeration and then apply the string array value to it. Can you please help me understand this? The text we are using is very difficult and poorly written for a beginner to understand, so I'm kind of on my own here. I've got the first parts written, but need some help on the accessing of the enumeration value and assigning, i think i'm close, but don't understand how to properly get and set the values on this. Please do not provide me with direct code answers, unless a MSDN style explanation that is generalized and not specific to my project. ie: public class MyClass { string field1; string field2; //properties public string Value1 get etc... Thanks!

    Read the article

  • Eclipse’s Ctrl+click does not work and indexer does not seem to update?

    - by bbazso
    I am running Eclipse IDE for C/C++ Developers (Ganymede) and I have recently encountered a problem with it. I can no longer get Ctrl+click navigation to work! I went to my project and tried to rebuild the index, but the rebuild command of the indexer does not work either. I did not do anything to my knowledge that may have caused this bug and so I was wondering if it could be a corrupt index or something else weird like that. Any help on this matter would be greatly appreciated. Thanks!

    Read the article

  • Is it possible to create a simple frontend indexer for openbittorent torrents?

    - by SimonK
    I run a website which distributes a few files every now and again, live music performances by a rock band. I create a torrent file, set the trackers as openbittorrent, publicbt and other similar open trackers. I upload the torrent file to my forum, my users download it and the files are shared. No problems there. What I would like to do is index those torrents properly on my website though so I can follow seeders/leechers and other stats online. I know the open torrent trackers don't have an index but I am aware of many, many indexing sites that do that exact thing. I don't know how though. So what I'm asking is what do I need to do to do that myself? I simply want to create a page that lists the torrents I and other users on my site create, the seeders/leechers ratio and a link to the torrent file etc. What data do I need to be able to do that? I'm proficient in general web design but I don't know what I would need data wise to pull the required info on the torrents? Thanks

    Read the article

  • How to speed up a slow UPDATE query

    - by Mike Christensen
    I have the following UPDATE query: UPDATE Indexer.Pages SET LastError=NULL where LastError is not null; Right now, this query takes about 93 minutes to complete. I'd like to find ways to make this a bit faster. The Indexer.Pages table has around 506,000 rows, and about 490,000 of them contain a value for LastError, so I doubt I can take advantage of any indexes here. The table (when uncompressed) has about 46 gigs of data in it, however the majority of that data is in a text field called html. I believe simply loading and unloading that many pages is causing the slowdown. One idea would be to make a new table with just the Id and the html field, and keep Indexer.Pages as small as possible. However, testing this theory would be a decent amount of work since I actually don't have the hard disk space to create a copy of the table. I'd have to copy it over to another machine, drop the table, then copy the data back which would probably take all evening. Ideas? I'm using Postgres 9.0.0. UPDATE: Here's the schema: CREATE TABLE indexer.pages ( id uuid NOT NULL, url character varying(1024) NOT NULL, firstcrawled timestamp with time zone NOT NULL, lastcrawled timestamp with time zone NOT NULL, recipeid uuid, html text NOT NULL, lasterror character varying(1024), missingings smallint, CONSTRAINT pages_pkey PRIMARY KEY (id ), CONSTRAINT indexer_pages_uniqueurl UNIQUE (url ) ); I also have two indexes: CREATE INDEX idx_indexer_pages_missingings ON indexer.pages USING btree (missingings ) WHERE missingings > 0; and CREATE INDEX idx_indexer_pages_null ON indexer.pages USING btree (recipeid ) WHERE NULL::boolean; There are no triggers on this table, and there is one other table that has a FK constraint on Pages.PageId.

    Read the article

  • Creating a dynamic, extensible C# Expando Object

    - by Rick Strahl
    I love dynamic functionality in a strongly typed language because it offers us the best of both worlds. In C# (or any of the main .NET languages) we now have the dynamic type that provides a host of dynamic features for the static C# language. One place where I've found dynamic to be incredibly useful is in building extensible types or types that expose traditionally non-object data (like dictionaries) in easier to use and more readable syntax. I wrote about a couple of these for accessing old school ADO.NET DataRows and DataReaders more easily for example. These classes are dynamic wrappers that provide easier syntax and auto-type conversions which greatly simplifies code clutter and increases clarity in existing code. ExpandoObject in .NET 4.0 Another great use case for dynamic objects is the ability to create extensible objects - objects that start out with a set of static members and then can add additional properties and even methods dynamically. The .NET 4.0 framework actually includes an ExpandoObject class which provides a very dynamic object that allows you to add properties and methods on the fly and then access them again. For example with ExpandoObject you can do stuff like this:dynamic expand = new ExpandoObject(); expand.Name = "Rick"; expand.HelloWorld = (Func<string, string>) ((string name) => { return "Hello " + name; }); Console.WriteLine(expand.Name); Console.WriteLine(expand.HelloWorld("Dufus")); Internally ExpandoObject uses a Dictionary like structure and interface to store properties and methods and then allows you to add and access properties and methods easily. As cool as ExpandoObject is it has a few shortcomings too: It's a sealed type so you can't use it as a base class It only works off 'properties' in the internal Dictionary - you can't expose existing type data It doesn't serialize to XML or with DataContractSerializer/DataContractJsonSerializer Expando - A truly extensible Object ExpandoObject is nice if you just need a dynamic container for a dictionary like structure. However, if you want to build an extensible object that starts out with a set of strongly typed properties and then allows you to extend it, ExpandoObject does not work because it's a sealed class that can't be inherited. I started thinking about this very scenario for one of my applications I'm building for a customer. In this system we are connecting to various different user stores. Each user store has the same basic requirements for username, password, name etc. But then each store also has a number of extended properties that is available to each application. In the real world scenario the data is loaded from the database in a data reader and the known properties are assigned from the known fields in the database. All unknown fields are then 'added' to the expando object dynamically. In the past I've done this very thing with a separate property - Properties - just like I do for this class. But the property and dictionary syntax is not ideal and tedious to work with. I started thinking about how to represent these extra property structures. One way certainly would be to add a Dictionary, or an ExpandoObject to hold all those extra properties. But wouldn't it be nice if the application could actually extend an existing object that looks something like this as you can with the Expando object:public class User : Westwind.Utilities.Dynamic.Expando { public string Email { get; set; } public string Password { get; set; } public string Name { get; set; } public bool Active { get; set; } public DateTime? ExpiresOn { get; set; } } and then simply start extending the properties of this object dynamically? Using the Expando object I describe later you can now do the following:[TestMethod] public void UserExampleTest() { var user = new User(); // Set strongly typed properties user.Email = "[email protected]"; user.Password = "nonya123"; user.Name = "Rickochet"; user.Active = true; // Now add dynamic properties dynamic duser = user; duser.Entered = DateTime.Now; duser.Accesses = 1; // you can also add dynamic props via indexer user["NickName"] = "AntiSocialX"; duser["WebSite"] = "http://www.west-wind.com/weblog"; // Access strong type through dynamic ref Assert.AreEqual(user.Name,duser.Name); // Access strong type through indexer Assert.AreEqual(user.Password,user["Password"]); // access dyanmically added value through indexer Assert.AreEqual(duser.Entered,user["Entered"]); // access index added value through dynamic Assert.AreEqual(user["NickName"],duser.NickName); // loop through all properties dynamic AND strong type properties (true) foreach (var prop in user.GetProperties(true)) { object val = prop.Value; if (val == null) val = "null"; Console.WriteLine(prop.Key + ": " + val.ToString()); } } As you can see this code somewhat blurs the line between a static and dynamic type. You start with a strongly typed object that has a fixed set of properties. You can then cast the object to dynamic (as I discussed in my last post) and add additional properties to the object. You can also use an indexer to add dynamic properties to the object. To access the strongly typed properties you can use either the strongly typed instance, the indexer or the dynamic cast of the object. Personally I think it's kinda cool to have an easy way to access strongly typed properties by string which can make some data scenarios much easier. To access the 'dynamically added' properties you can use either the indexer on the strongly typed object, or property syntax on the dynamic cast. Using the dynamic type allows all three modes to work on both strongly typed and dynamic properties. Finally you can iterate over all properties, both dynamic and strongly typed if you chose. Lots of flexibility. Note also that by default the Expando object works against the (this) instance meaning it extends the current object. You can also pass in a separate instance to the constructor in which case that object will be used to iterate over to find properties rather than this. Using this approach provides some really interesting functionality when use the dynamic type. To use this we have to add an explicit constructor to the Expando subclass:public class User : Westwind.Utilities.Dynamic.Expando { public string Email { get; set; } public string Password { get; set; } public string Name { get; set; } public bool Active { get; set; } public DateTime? ExpiresOn { get; set; } public User() : base() { } // only required if you want to mix in seperate instance public User(object instance) : base(instance) { } } to allow the instance to be passed. When you do you can now do:[TestMethod] public void ExpandoMixinTest() { // have Expando work on Addresses var user = new User( new Address() ); // cast to dynamicAccessToPropertyTest dynamic duser = user; // Set strongly typed properties duser.Email = "[email protected]"; user.Password = "nonya123"; // Set properties on address object duser.Address = "32 Kaiea"; //duser.Phone = "808-123-2131"; // set dynamic properties duser.NonExistantProperty = "This works too"; // shows default value Address.Phone value Console.WriteLine(duser.Phone); } Using the dynamic cast in this case allows you to access *three* different 'objects': The strong type properties, the dynamically added properties in the dictionary and the properties of the instance passed in! Effectively this gives you a way to simulate multiple inheritance (which is scary - so be very careful with this, but you can do it). How Expando works Behind the scenes Expando is a DynamicObject subclass as I discussed in my last post. By implementing a few of DynamicObject's methods you can basically create a type that can trap 'property missing' and 'method missing' operations. When you access a non-existant property a known method is fired that our code can intercept and provide a value for. Internally Expando uses a custom dictionary implementation to hold the dynamic properties you might add to your expandable object. Let's look at code first. The code for the Expando type is straight forward and given what it provides relatively short. Here it is.using System; using System.Collections.Generic; using System.Linq; using System.Dynamic; using System.Reflection; namespace Westwind.Utilities.Dynamic { /// <summary> /// Class that provides extensible properties and methods. This /// dynamic object stores 'extra' properties in a dictionary or /// checks the actual properties of the instance. /// /// This means you can subclass this expando and retrieve either /// native properties or properties from values in the dictionary. /// /// This type allows you three ways to access its properties: /// /// Directly: any explicitly declared properties are accessible /// Dynamic: dynamic cast allows access to dictionary and native properties/methods /// Dictionary: Any of the extended properties are accessible via IDictionary interface /// </summary> [Serializable] public class Expando : DynamicObject, IDynamicMetaObjectProvider { /// <summary> /// Instance of object passed in /// </summary> object Instance; /// <summary> /// Cached type of the instance /// </summary> Type InstanceType; PropertyInfo[] InstancePropertyInfo { get { if (_InstancePropertyInfo == null && Instance != null) _InstancePropertyInfo = Instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); return _InstancePropertyInfo; } } PropertyInfo[] _InstancePropertyInfo; /// <summary> /// String Dictionary that contains the extra dynamic values /// stored on this object/instance /// </summary> /// <remarks>Using PropertyBag to support XML Serialization of the dictionary</remarks> public PropertyBag Properties = new PropertyBag(); //public Dictionary<string,object> Properties = new Dictionary<string, object>(); /// <summary> /// This constructor just works off the internal dictionary and any /// public properties of this object. /// /// Note you can subclass Expando. /// </summary> public Expando() { Initialize(this); } /// <summary> /// Allows passing in an existing instance variable to 'extend'. /// </summary> /// <remarks> /// You can pass in null here if you don't want to /// check native properties and only check the Dictionary! /// </remarks> /// <param name="instance"></param> public Expando(object instance) { Initialize(instance); } protected virtual void Initialize(object instance) { Instance = instance; if (instance != null) InstanceType = instance.GetType(); } /// <summary> /// Try to retrieve a member by name first from instance properties /// followed by the collection entries. /// </summary> /// <param name="binder"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { result = null; // first check the Properties collection for member if (Properties.Keys.Contains(binder.Name)) { result = Properties[binder.Name]; return true; } // Next check for Public properties via Reflection if (Instance != null) { try { return GetProperty(Instance, binder.Name, out result); } catch { } } // failed to retrieve a property result = null; return false; } /// <summary> /// Property setter implementation tries to retrieve value from instance /// first then into this object /// </summary> /// <param name="binder"></param> /// <param name="value"></param> /// <returns></returns> public override bool TrySetMember(SetMemberBinder binder, object value) { // first check to see if there's a native property to set if (Instance != null) { try { bool result = SetProperty(Instance, binder.Name, value); if (result) return true; } catch { } } // no match - set or add to dictionary Properties[binder.Name] = value; return true; } /// <summary> /// Dynamic invocation method. Currently allows only for Reflection based /// operation (no ability to add methods dynamically). /// </summary> /// <param name="binder"></param> /// <param name="args"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (Instance != null) { try { // check instance passed in for methods to invoke if (InvokeMethod(Instance, binder.Name, args, out result)) return true; } catch { } } result = null; return false; } /// <summary> /// Reflection Helper method to retrieve a property /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="result"></param> /// <returns></returns> protected bool GetProperty(object instance, string name, out object result) { if (instance == null) instance = this; var miArray = InstanceType.GetMember(name, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0]; if (mi.MemberType == MemberTypes.Property) { result = ((PropertyInfo)mi).GetValue(instance,null); return true; } } result = null; return false; } /// <summary> /// Reflection helper method to set a property value /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> protected bool SetProperty(object instance, string name, object value) { if (instance == null) instance = this; var miArray = InstanceType.GetMember(name, BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0]; if (mi.MemberType == MemberTypes.Property) { ((PropertyInfo)mi).SetValue(Instance, value, null); return true; } } return false; } /// <summary> /// Reflection helper method to invoke a method /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="args"></param> /// <param name="result"></param> /// <returns></returns> protected bool InvokeMethod(object instance, string name, object[] args, out object result) { if (instance == null) instance = this; // Look at the instanceType var miArray = InstanceType.GetMember(name, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0] as MethodInfo; result = mi.Invoke(Instance, args); return true; } result = null; return false; } /// <summary> /// Convenience method that provides a string Indexer /// to the Properties collection AND the strongly typed /// properties of the object by name. /// /// // dynamic /// exp["Address"] = "112 nowhere lane"; /// // strong /// var name = exp["StronglyTypedProperty"] as string; /// </summary> /// <remarks> /// The getter checks the Properties dictionary first /// then looks in PropertyInfo for properties. /// The setter checks the instance properties before /// checking the Properties dictionary. /// </remarks> /// <param name="key"></param> /// /// <returns></returns> public object this[string key] { get { try { // try to get from properties collection first return Properties[key]; } catch (KeyNotFoundException ex) { // try reflection on instanceType object result = null; if (GetProperty(Instance, key, out result)) return result; // nope doesn't exist throw; } } set { if (Properties.ContainsKey(key)) { Properties[key] = value; return; } // check instance for existance of type first var miArray = InstanceType.GetMember(key, BindingFlags.Public | BindingFlags.GetProperty); if (miArray != null && miArray.Length > 0) SetProperty(Instance, key, value); else Properties[key] = value; } } /// <summary> /// Returns and the properties of /// </summary> /// <param name="includeProperties"></param> /// <returns></returns> public IEnumerable<KeyValuePair<string,object>> GetProperties(bool includeInstanceProperties = false) { if (includeInstanceProperties && Instance != null) { foreach (var prop in this.InstancePropertyInfo) yield return new KeyValuePair<string, object>(prop.Name, prop.GetValue(Instance, null)); } foreach (var key in this.Properties.Keys) yield return new KeyValuePair<string, object>(key, this.Properties[key]); } /// <summary> /// Checks whether a property exists in the Property collection /// or as a property on the instance /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Contains(KeyValuePair<string, object> item, bool includeInstanceProperties = false) { bool res = Properties.ContainsKey(item.Key); if (res) return true; if (includeInstanceProperties && Instance != null) { foreach (var prop in this.InstancePropertyInfo) { if (prop.Name == item.Key) return true; } } return false; } } } Although the Expando class supports an indexer, it doesn't actually implement IDictionary or even IEnumerable. It only provides the indexer and Contains() and GetProperties() methods, that work against the Properties dictionary AND the internal instance. The reason for not implementing IDictionary is that a) it doesn't add much value since you can access the Properties dictionary directly and that b) I wanted to keep the interface to class very lean so that it can serve as an entity type if desired. Implementing these IDictionary (or even IEnumerable) causes LINQ extension methods to pop up on the type which obscures the property interface and would only confuse the purpose of the type. IDictionary and IEnumerable are also problematic for XML and JSON Serialization - the XML Serializer doesn't serialize IDictionary<string,object>, nor does the DataContractSerializer. The JavaScriptSerializer does serialize, but it treats the entire object like a dictionary and doesn't serialize the strongly typed properties of the type, only the dictionary values which is also not desirable. Hence the decision to stick with only implementing the indexer to support the user["CustomProperty"] functionality and leaving iteration functions to the publicly exposed Properties dictionary. Note that the Dictionary used here is a custom PropertyBag class I created to allow for serialization to work. One important aspect for my apps is that whatever custom properties get added they have to be accessible to AJAX clients since the particular app I'm working on is a SIngle Page Web app where most of the Web access is through JSON AJAX calls. PropertyBag can serialize to XML and one way serialize to JSON using the JavaScript serializer (not the DCS serializers though). The key components that make Expando work in this code are the Properties Dictionary and the TryGetMember() and TrySetMember() methods. The Properties collection is public so if you choose you can explicitly access the collection to get better performance or to manipulate the members in internal code (like loading up dynamic values form a database). Notice that TryGetMember() and TrySetMember() both work against the dictionary AND the internal instance to retrieve and set properties. This means that user["Name"] works against native properties of the object as does user["Name"] = "RogaDugDog". What's your Use Case? This is still an early prototype but I've plugged it into one of my customer's applications and so far it's working very well. The key features for me were the ability to easily extend the type with values coming from a database and exposing those values in a nice and easy to use manner. I'm also finding that using this type of object for ViewModels works very well to add custom properties to view models. I suspect there will be lots of uses for this - I've been using the extra dictionary approach to extensibility for years - using a dynamic type to make the syntax cleaner is just a bonus here. What can you think of to use this for? Resources Source Code and Tests (GitHub) Also integrated in Westwind.Utilities of the West Wind Web Toolkit West Wind Utilities NuGet© Rick Strahl, West Wind Technologies, 2005-2012Posted in CSharp  .NET  Dynamic Types   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • posting nutch data into a BASIC auth secured Solr instance

    - by mlathe
    Hi. I've secured a solr instance using BASIC auth, kind of how it is shown here: http://blog.comtaste.com/2009/02/securing_your_solr_server_on_t.html Now i'm trying to update my batch processes to push data into the authenticated instance. The ones using "curl" are easy, but i also have a Nutch crawl that uses the "solrindex" command to push data into Solr. When i do that i get this error: 2010-02-22 12:09:28,226 INFO auth.AuthChallengeProcessor - basic authentication scheme selected 2010-02-22 12:09:28,229 INFO httpclient.HttpMethodDirector - No credentials available for BASIC 'Tomcat Manager Application'@ninja:5500 2010-02-22 12:09:28,236 WARN mapred.LocalJobRunner - job_local_0001 org.apache.solr.common.SolrException: Unauthorized Unauthorized request: http://ninja:5500/solr/foo/update?wt=javabin&version=2.2 at org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.request(CommonsHttpSolrServer.java:343) at org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.request(CommonsHttpSolrServer.java:183) at org.apache.solr.client.solrj.request.UpdateRequest.process(UpdateRequest.java:217) at org.apache.solr.client.solrj.SolrServer.add(SolrServer.java:48) at org.apache.nutch.indexer.solr.SolrWriter.close(SolrWriter.java:69) at org.apache.nutch.indexer.IndexerOutputFormat$1.close(IndexerOutputFormat.java:48) at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:447) at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:170) 2010-02-22 12:09:29,134 FATAL solr.SolrIndexer - SolrIndexer: java.io.IOException: Job failed! at org.apache.hadoop.mapred.JobClient.runJob(JobClient.java:1232) at org.apache.nutch.indexer.solr.SolrIndexer.indexSolr(SolrIndexer.java:73) at org.apache.nutch.indexer.solr.SolrIndexer.run(SolrIndexer.java:95) at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65) at org.apache.nutch.indexer.solr.SolrIndexer.main(SolrIndexer.java:104) Apparently nutch uses SolrJ to push the content, and after going through the solrj code, it's clear that it uses commons-httpclient without providing a way to set the credentials. Here are my question(s) Is this possible to do? ie push from nutch into a BASIC auth secured Solr instance? Is it possible to tell commons-httpclient about a credential without explicitly doing an _httpclient.getState().setCredentials(...)? Anyother ideas? One idea i had was to use an IPfiltering Valve for just the "update" Solr webservices. That would mean you could only make an update call from certain nodes. Thanks

    Read the article

  • Select TOP 5 * from SomeTable, using Dataview.RowFilter ?

    - by eugeneK
    I need to select 5 most recent rows from cached Dataview object, is there any way to do that? I've tried but Indexer DataColumn is empty. : public static DataView getLatestFourActive() { DataTable productDataTable = getAll().ToTable(); DataColumn ExpressionColumn = new DataColumn("Indexer",typeof(System.Int32)); ExpressionColumn.Unique = true; ExpressionColumn.AutoIncrement = true; ExpressionColumn.AllowDBNull = false; ExpressionColumn.AutoIncrementSeed = 0; ExpressionColumn.AutoIncrementStep = 1; productDataTable.Columns.Add(ExpressionColumn); DataView productFilteredView = productDataTable.DefaultView; productFilteredView.RowFilter = "isActive=1 and Indexer<4"; return productFilteredView; } getAll() returns cached DataView thanks

    Read the article

1 2 3 4 5 6  | Next Page >