Daily Archives

Articles indexed Tuesday September 11 2012

Page 8/18 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • MongoDB C# - Hide property from serializer

    - by ehftwelve
    This is what my user model looks like: namespace Api.Models { public class User { [BsonId(IdGenerator = typeof(StringObjectIdGenerator))] [BsonRequired] public string Id { get; set; } [Required(ErrorMessage = "Username is required.")] [StringLength(20, MinimumLength=3, ErrorMessage="Username must be between 3 and 20 characters.")] [BsonRequired] public string Username { get; set; } [Required(ErrorMessage="Email is required.")] [EmailAddress(ErrorMessage="Valid email required.")] [BsonRequired] public string Email { get; set; } [Required(ErrorMessage = "Password is required.")] [StringLength(50, MinimumLength=8, ErrorMessage="Password must be between 8 and 50 characters.")] [BsonRequired] public string Password { get; set; } [BsonRequired] public string Salt { get; set; } } } I want to write, and require, all of the properties into the MongoDB Database. What I don't want to do, is expose the Password and Salt properties when I send this through the request. Is there any sort of data attribute that I can set that will write it, but not expose it when displayed to any API user?

    Read the article

  • Mericural "no username supplied" error on Mac

    - by theDuncs
    I've just installed Mercurial on my Mountain Lion Max (10.8) and on my first commit I'm getting the error: abort: no username supplied (see "hg help config") I've seen a load of answers which suggest I need to create or copy a file form a certain location and paste it into another location and add my username and email to the document. If that is the right thing to do: Where is the file I need to copy (or what is the file called that I need to create) Where do I put that file Do I just need to add the following two lines to the file? [ui] username = Your Name Thanks guys.

    Read the article

  • count number of business that belongs to subcategory in doctrine

    - by Ibrahim Azhar Armar
    this is follow up of this question. count number of foreign keys i am using doctrine 1.2 and i want to count the number of business that belongs to subcategory. following are the mysql tables. 1.fi_category +----+-----------------+-----------------+ | id | name | slug | +----+-----------------+-----------------+ 2.fi_subcategory +----+-----------------+-----------------+-------------+ | id | name | slug | category_id | +----+-----------------+-----------------+-------------+ 3.fi_business_subcategory +----+-------------+----------------+ | id | business_id | subcategory_id | +----+-------------+----------------+ i am using this DQL. $q = Doctrine_Query::create() ->select('c.name, c.slug, sc.name, sc.slug') ->from('Model_Category c') ->leftJoin('c.Subcategory sc') ->leftJoin('sc.BusinessSubcategory bsc'); which gives me something like this. Array ( [0] => Array ( [id] => 1 [name] => Entertainment & Lifestyle [slug] => entertainment-lifestyle [Subcategory] => Array ( [0] => Array ( [id] => 1 [name] => Arts and Crafts [slug] => arts-and-crafts ) [1] => Array ( [id] => 2 [name] => Family [slug] => family ) [2] => Array ( [id] => 3 [name] => Fashion [slug] => fashion ) ) ) ) i am looking to fetch the number of business, i.e the returned result should be something like this depending on the business it belongs. Array ( [0] => Array ( [id] => 1 [name] => Entertainment & Lifestyle [slug] => entertainment-lifestyle [Subcategory] => Array ( [0] => Array ( [id] => 1 [name] => Arts and Crafts [slug] => arts-and-crafts [business_count] => 35 ) [1] => Array ( [id] => 2 [name] => Family [slug] => family [business_count] => 10 ) [2] => Array ( [id] => 3 [name] => Fashion [slug] => fashion [business_count] => 27 ) ) ) ) tried various ways using DQL, but nothing seems to work out. any idea how should i go with what i want?

    Read the article

  • Create an axpanding image with CSS and div or span

    - by user1594895
    I have a complex image cutted up in alot of slice. You can see http://jsfiddle.net/yefQR/ <!--Force IE6 into quirks mode with this comment tag--> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Page Title</title> <style type="text/css"> body{ margin: 0; padding: 0; border: 0; overflow: hidden; height: 100%; max-height: 100%; } #framecontentTop, #framecontentBottom{ position: absolute; top: 0; left: 0; width: 100%; height: 130px; /*Height of top frame div*/ overflow: hidden; /*Disable scrollbars. Set to "scroll" to enable*/ background-color: navy; color: white; } #framecontentBottom{ top: auto; bottom: 0; height: 110px; /*Height of bottom frame div*/ overflow: hidden; /*Disable scrollbars. Set to "scroll" to enable*/ background-color: navy; color: white; } #maincontent{ position: fixed; top: 130px; /*Set top value to HeightOfTopFrameDiv*/ left: 0; right: 0; bottom: 110px; /*Set bottom value to HeightOfBottomFrameDiv*/ overflow: auto; background: #fff; } .innertube{ margin: 15px; /*Margins for inner DIV inside each DIV (to provide padding)*/ } * html body{ /*IE6 hack*/ padding: 130px 0 110px 0; /*Set value to (HeightOfTopFrameDiv 0 HeightOfBottomFrameDiv 0)*/ } * html #maincontent{ /*IE6 hack*/ height: 100%; width: 100%; } </style> </head> <body> <div id="framecontentTop"> <div class="innertube"> <div id="screenshot%20tsam%20900r2c2" style=" background-color: green;position:absolute; left:4px; top:6px; width:20px; height:68px; z-index:1; visibility:visible; "> </div> <div id="screenshot%20tsam%20900r2c3" style="background-color: yellow; position:absolute; left:24px; top:6px;width:47px; height:68px;z-index:2; visibility:visible;"></div> <div id="screenshot%20tsam%20900r2c4" style="background-color: red; position:absolute; left:71px; top:6px;width:165px; height:68px;z-index:3; visibility:visible;"></div> <div id="screenshot%20tsam%20900r2c5" style="background-color: black; position:absolute; left:236px; top:6px;width:62px; height:68px;z-index:4; visibility:visible;"></div> <div id="screenshot%20tsam%20900r2c6" style="background-color: pink; position:absolute; left:298px; top:6px;width:147px; height:68px;z-index:5; visibility:visible;"></div> <div id="screenshot%20tsam%20900r2c7" style="background-color: orange; position:absolute; left:445px; top:6px;width:311px; height:37px;z-index:6; visibility:visible;"></div> <div id="screenshot%20tsam%20900r2c9" style="background-color: cyan; position:absolute; left:756px; top:6px;width:108px; height:37px;z-index:7; visibility:visible;"></div> <div id="screenshot%20tsam%20900r2c11" style="background-color: white; position:absolute; left:864px; top:6px;width:27px; height:37px;z-index:8; visibility:visible;"></div> <div id="screenshot%20tsam%20900r3c7" style="background-color: DodgerBlue; position:absolute; left:445px; top:43px;width:8px; height:31px;z-index:9; visibility:visible;"></div> <div id="screenshot%20tsam%20900r3c8" style="background-color: Gold; position:absolute; left:453px; top:43px;width:355px; height:31px;z-index:10; visibility:visible;"></div> <div id="screenshot%20tsam%20900r3c10" style="background-color: LightCyan ; position:absolute; left:808px; top:43px;width:83px; height:31px;z-index:11; visibility:visible;"></div> </div> </div> <div id="framecontentBottom"> <div class="innertube"> <h3>Sample text here</h3> </div> </div> <div id="maincontent"> <div class="innertube"> <h1>Lorem</h1> <p> Lorem ipsum </p> <p style="text-align: center">Vestibulum </p> </div> </div> </body> </html> Id like to make : 1) the header image autoexpanding using the repeated-y css property of DodgerBlue color and Orange div because thy are the only 2 part of image axpandible. 2) Is it possible to define a minimum size of header, and is possible to make the entire body minimum size based that size so the browser cant get smaller an if the window get smaller, scrollbar is show.

    Read the article

  • Request a Windows Phone 7.5 Location

    - by Christopher Cabezudo Rodriguez
    I am trying to track 5 windows phone 7.5 for a experiment and I have try using an app (that I am developing for that experiment) but the app must be active and that's not possible for all readings, I was looking online and I find something similar that Microsoft has done with the find my phone service, https://www.windowsphone.com/en-US/find Anyone knows how can i call that service outside the website or any other way to accomplish this task i need GEO position every 15 min

    Read the article

  • glReadPixels() returning non-accurate value

    - by max
    I'm trying to implement the flood fill algorithm. But glReadPixels() is returning float RGB values of a pixel which are slightly different from the actual value set by me, causing the algorithm to fail. Why is this happening? Outputting returned RGB values to check. #include<iostream> #include<GL/glut.h> using namespace std; float boundaryColor[3]={0,0,0}, interiorColor[3]={0,0,0.5}, fillColor[3]={1,0,0}; float readPixel[3]; void init(void) { glClearColor(0,0,0.5,0); glMatrixMode(GL_PROJECTION); gluOrtho2D(0,500,0,500); } void setPixel(int x,int y) { glColor3fv(fillColor); glBegin(GL_POINTS); glVertex2f(x,y); glEnd(); } void getPixel(int x, int y, float *color) { glReadPixels(x,y,1,1,GL_RGB,GL_FLOAT,color); } void floodFill(int x,int y) { getPixel(x,y,readPixel); //outputting values here to check cout<<readPixel[0]<<endl; cout<<readPixel[1]<<endl; cout<<readPixel[2]<<endl; if( readPixel[0]==interiorColor[0] && readPixel[1]==interiorColor[1] && readPixel[2]==interiorColor[2] ) { setPixel(x,y); floodFill(x+1,y); floodFill(x,y+1); floodFill(x-1,y); floodFill(x,y-1); } } void display() { glClear(GL_COLOR_BUFFER_BIT); glColor3fv(boundaryColor); glLineWidth(3); glBegin(GL_LINE_STRIP); glVertex2i(150,150); glVertex2i(150,350); glVertex2i(350,350); glVertex2i(350,150); glVertex2i(150,150); glEnd(); floodFill(200,200); glFlush(); } int main(int argc,char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowPosition(100,100); glutInitWindowSize(500,500); glutCreateWindow("Flood fill"); init(); glutDisplayFunc(display); glutMainLoop(); }

    Read the article

  • Add title to meta analysis forest plot

    - by Timothy Alston
    I am meta-analysing some studies and drawing a forest plot for my results. However I can`t seem to get the forest plot to display the title. An example of my code is: require(meta) parameter1<-metaprop(sm="PLOGIT", event=c(4,16,3,2,10,1,0,2), n=c(90,402,89,29,153,86,21,48), level = 0.95, studlab=c("study 1", "study 2", "study 3", "study 4", "study 5", "study 6", "study 7", "study 8"), title="meta analysis 1") forest(parameter1) When it produces the forest plot, the title "meta analysis 1" is missing. How can I add this in? Thanks in advance, Timothy

    Read the article

  • Is it possible to exclude some elements from parsing when using regular expression and .replace()?

    - by Fletus Mefitis
    <script language="javascript"> $("div.post-content , .parsedsig").each(function(){ if($(this).html().indexOf("[/tabulaScriptum]") != -1) { pattern = /\[tabulaScriptum=(.*?)\]([^\[]*)\[\/tabulaScriptum\]/gi $(this).html($(this).html().replace(pattern, "<div class='tabulaScriptum'><div class='tabulaNomen'>$1</div><div class='tabulaImpleo'>$2</div></div>")) } }); </script> This script is working perfectly, except for one thing... I need not to replace [tabulaScriptum=][/tabulaScriptum] in certain elements. For example, I don't want to replace those "tags" in element that has class .code-box. Is it possible? Clarification: element .code-box is located within .post-content. Clarification #2: this script creates simple division spoiler. .tabulaScriptum is spoier's body, .tabulaNomen is spoiler's name and button which, in turn, reveals(or hides) .tabulaImpleo on click. Reveal\hide script is located in some other place, and I didn't post it here since it doesn't really matter. Clarification #3: http://jsfiddle.net/PRtsw/1/ fiddle.

    Read the article

  • Unable to upgrade PEAR from 1.9.2 to 1.9.4

    - by user940768
    I am on a Ubuntu 11.10 and trying to upgrade from 1.9.2 to 1.9.4, but it simply don't work. Here are the commands I am following in sequence $ sudo apt-get install php-pear Reading package lists... Done Building dependency tree Reading state information... Done php-pear is already the newest version. The following packages were automatically installed and are no longer required: linux-headers-3.0.0-14-generic-pae libaccess-bridge-java-jni libaccess-bridge-java Use 'apt-get autoremove' to remove them. 0 upgraded, 0 newly installed, 0 to remove and 6 not upgraded. $ sudo pear channel-update pear.php.net Updating channel "pear.php.net" Channel "pear.php.net" is up to date $ sudo pear upgrade-all Nothing to upgrade-all $ sudo pear install –alldeps pear.phpunit.de/PHPUnit parsePackageName(): invalid package name "–alldeps" in "–alldeps" invalid package name/package file "–alldeps" Did not download optional dependencies: phpunit/PHP_Invoker, use --alldeps to download automatically phpunit/PHPUnit requires PEAR Installer (version >= 1.9.4), installed version is 1.9.2 phpunit/PHPUnit can optionally use package "phpunit/PHP_Invoker" (version >= 1.1.0) phpunit/Text_Template requires PEAR Installer (version >= 1.9.4), installed version is 1.9.2 phpunit/PHP_CodeCoverage requires PEAR Installer (version >= 1.9.4), installed version is 1.9.2 phpunit/PHP_CodeCoverage requires package "phpunit/Text_Template" (version >= 1.1.1) phpunit/PHP_CodeCoverage can optionally use PHP extension "xdebug" (version >= 2.0.5) phpunit/PHPUnit_MockObject requires PEAR Installer (version >= 1.9.4), installed version is 1.9.2 phpunit/PHPUnit_MockObject requires package "phpunit/Text_Template" (version >= 1.1.1) phpunit/PHP_TokenStream requires PEAR Installer (version >= 1.9.4), installed version is 1.9.2 No valid packages found install failed Any thoughts?

    Read the article

  • How to match this with a regex?

    - by andrei miko
    I just wanna use a regex to match something from my products file. I have them in this way "Something here","a link here","website here","date here(eg. 11/12/2012)","description1 here","**description2 here**","some other text here","here also", and so on ... I wanna match with a regex only description 2. I tried this: (?<=[0-9][0-9][0-9][0-9]).*(?=",") but it wasn't good because it was getting me description1, description2 and some quotes also. Thanks in advance.

    Read the article

  • Set JTabbedPane width to constant

    - by msp
    I'm implementing an UI in Java Swing. Therefore I use a JTabbedPane. The tabbedPane has no components at startup. When i add a tab to the tabbedpane, the width of the tabbedpane increases, when i remove the tab, the width resizes to the width at the startup. This should not happen. The tabbedpane is placed on a JPanel which has a gridbag layout. Layout code: Container contentPane = mainFrame.getContentPane(); contentPane.setLayout( new GridBagLayout() ); GridBagConstraints c = new GridBagConstraints(); // add the component tree initComponentTree(); c.gridx = 0; c.gridy = 0; c.gridheight = 1; c.gridwidth = 1; c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.LINE_START; c.weightx = 1; c.weighty = 1; contentPane.add( componentTree, c ); // add the tabbed pane initTabbedPane(); c.gridx = 1; c.weightx = 10; contentPane.add( tabbedPane, c ); // add the status panel initStatusPanel(); c.gridx = 0; c.gridy = 1; c.gridwidth = 2; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.LINE_START; c.weightx = 0; c.weighty = 0; contentPane.add( statusPanel, c ); Hope someone can help!

    Read the article

  • Error when customize ValidationMessageFor

    - by user1542080
    i want to customize ValidationMessageFor which display error. when i run application, a get an error : No overload for method 'ValidationMessageFor' takes 1 arguments I'm understand my error, but i don't know how to fix it ? I need some suggest . Thanks you for reading! My code : using System.Linq.Expressions; using System.Web; using System.Web.Mvc; namespace OurCompanyUI.app_code { public static class MyHtml { public static MvcHtmlString ValidationMessageFor<TModel, TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string validationMessage, IDictionary<string, Object> htmlAttributes ) { string modelName = ExpressionHelper.GetExpressionText(expression); TagBuilder p = new TagBuilder("p"); p.InnerHtml = htmlHelper.ValidationMessageFor(htmlHelper,expression).ToString(); // p.InnerHtml = htmlHelper.ValidationMessageFor().ToString(); return MvcHtmlString.Create(p.ToString(TagRenderMode.Normal)); } } }

    Read the article

  • PyQt : Checkbox in QTableWidget

    - by user1064815
    I use following code to put a checkbox in the 9th column of my QTableWidget chkBoxItem = QtGui.QTableWidgetItem() chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled) chkBoxItem.setCheckState(QtCore.Qt.Unchecked) table.setItem(rowNo,9,chkBoxItem) Where table is my QtTableWidget. I need to add the row where the checkbox is clicked to a list.. how on earth do I achieve this? Kind regards,

    Read the article

  • pyPDF - Retrieve page numbers from document

    - by SquidneyPoitier
    At the moment I'm looking into doing some PDF merging with pyPdf, but sometimes the inputs are not in the right order, so I'm looking into scraping each page for its page number to determine the order it should go in (e.g. if someone split up a book into 20 10-page PDFs and I want to put them back together). I have two questions - 1.) I know that sometimes the page number is stored in the document data somewhere, as I've seen PDFs that render on Adobe as something like [1243] (10 of 150), but I've read documents of this sort into pyPDF and I can't find any information indicating the page number - where is this stored? 2.) If avenue #1 isn't available, I think I could iterate through the objects on a given page to try to find a page number - likely it would be its own object that has a single number in it. However, I can't seem to find any clear way to determine the contents of objects. If I run: pdf.getPage(0).getContents() This usually either returns: {'/Filter': '/FlateDecode'} or it returns a list of IndirectObject(num, num) objects. I don't really know what to do with either of these and there's no real documentation on it as far as I can tell. Is anyone familiar with this kind of thing that could point me in the right direction?

    Read the article

  • Solving quadratic programming using R

    - by user702846
    I would like to solve the following quadratic programming equation using ipop function from kernlab : min 0.5*x'*H*x + f'*x subject to: A*x <= b Aeq*x = beq LB <= x <= UB where in our example H 3x3 matrix, f is 3x1, A is 2x3, b is 2x1, LB and UB are both 3x1. edit 1 My R code is : library(kernlab) H <- rbind(c(1,0,0),c(0,1,0),c(0,0,1)) f = rbind(0,0,0) A = rbind(c(1,1,1), c(-1,-1,-1)) b = rbind(4.26, -1.73) LB = rbind(0,0,0) UB = rbind(100,100,100) > ipop(f,H,A,b,LB,UB,0) Error in crossprod(r, q) : non-conformable arguments I know from matlab that is something like this : H = eye(3); f = [0,0,0]; nsamples=3; eps = (sqrt(nsamples)-1)/sqrt(nsamples); A=ones(1,nsamples); A(2,:)=-ones(1,nsamples); b=[nsamples*(eps+1); nsamples*(eps-1)]; Aeq = []; beq = []; LB = zeros(nsamples,1); UB = ones(nsamples,1).*1000; [beta,FVAL,EXITFLAG] = quadprog(H,f,A,b,Aeq,beq,LB,UB); and the answer is a vector of 3x1 equals to [0.57,0.57,0.57]; However when I try it on R, using ipop function from kernlab library ipop(f,H,A,b,LB,UB,0)) and I am facing Error in crossprod(r, q) : non-conformable arguments I appreciate any comment

    Read the article

  • Safari won't request video or audio from HTML 5 media elements?

    - by thure
    So far what I've been developing has worked in Chrome and, using fallbacks, IE8. What I don't get is this: Safari just won't start loading <video> or <audio> content. Safari 6 won't load, and neither will iOS 5's Safari: My code calls .load() on the elements at the appropriate time (at least for Chrome), so what gives? Here is the video declaration: <video width="800" height="600" class="faces" id="facesVideo"> <source src="video/grid.mp4" type="video/mp4" /> <source src="video/grid.ogv" type="video/ogg" /> </video> The audio is declared dynamically, but has the same problem. Do I need to wait for some DOM event that Chrome doesn't need before calling .load()? What does it take to get Safari to start buffering until the elements can fire canplaythrough?

    Read the article

  • Increasing TCP/IP Window size

    - by Lior
    I am trying to send messages over tcp/ip between two servers. I want to send a message that is 30KB. But I want to send it with as a whole. I don't want tcp protocol to break it into segments. I am using communication between 2 Windows Server 2008 R2. The client and the server are coded using c#. I tryed using tcpclnt.SendBufferSize = 100000; tcpclnt.Client.DontFragment = true; and the same at the server. I also tried configuring the window size of the server(editing the registry).

    Read the article

  • How to drop null values with a native Oracle XML DB Web Service?

    - by gfjr
    I am using native Oracle XML DB Web Services (using a PL/SQL function with a web service). I want to drop null values (put nothing in the output (no XML element)). It's working with Oracle 11.2.0.1.0 but not with Oracle 11.2.0.3.0. Just to clarify... I don't want to consume a webservice with PL/SQL, I want to publish my PL/SQL packages/procedures/functions as a web service! Hope someone can help me. Thank you. In this example is the column "country" null. Oracle 11.2.0.1.0 (this is what I want): <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <GET_PERSONOutput xmlns="http://xmlns.oracle.com/orawsv/TESTSTUFF/GET_PERSON"> <RETURN> <PERSON> <PERSON_ID>3</PERSON_ID> <FIRST_NAME>Harry</FIRST_NAME> <LAST_NAME>Potter</LAST_NAME> </PERSON> </RETURN> </GET_PERSONOutput> </soap:Body> </soap:Envelope> Oracle 11.2.0.3.0: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <GET_PERSONOutput xmlns="http://xmlns.oracle.com/orawsv/TESTSTUFF/GET_PERSON"> <RETURN> <PERSON> <PERSON_ID>3</PERSON_ID> <FIRST_NAME>Harry</FIRST_NAME> <LAST_NAME>Potter</LAST_NAME> <COUNTRY/> </PERSON> </RETURN> </GET_PERSONOutput> </soap:Body> </soap:Envelope>

    Read the article

  • Why is my background image not displaying properly in IE7?

    - by JAG2007
    Screenshot of the issue: here Webpage in Question: http://cure.org Offending browser: Internet Explorer 7 You'll notice from the screenshot, or if you view this site in IE7, that the background image is not displaying for the content div (#modal-inner-content). Strangely, the image displays in the other divs where it is used (since it's a sprite, I'm using that same image for #modal-top-border and #modal-btm-border). In all other browsers it displays properly, and even in IE8. I cannot seem to find what CSS rule (or lack thereof) I may be using that IE7 is choking on. NOTE: in order to get the modal screen, just click the link at the very top banner of the page that says "login to your CURE account

    Read the article

  • Free book on C++ from

    - by TATWORTH
    At https://www.syncfusion.com/resources/techportal/ebooks/Cplusplus?utm_medium=EDM, SyncFusion are offering a free book on C++ for C# developers."C++ Succinctly was written to help professional C# developers learn modern C++ programming. The aim of this book is to leverage your existing C# knowledge in order to expand your skills. Whether you need to use C++ in an upcoming project, or simply want to learn a new language (or reacquaint yourself with it), this book will help you learn all of the fundamental pieces of C++ so you can begin writing your own C++ programs."

    Read the article

  • Loosely coupled .NET Cache Provider using Dependency Injection

    - by Rhames
    I have recently been reading the excellent book “Dependency Injection in .NET”, written by Mark Seemann. I do not generally buy software development related books, as I never seem to have the time to read them, but I have found the time to read Mark’s book, and it was time well spent I think. Reading the ideas around Dependency Injection made me realise that the Cache Provider code I wrote about earlier (see http://geekswithblogs.net/Rhames/archive/2011/01/10/using-the-asp.net-cache-to-cache-data-in-a-model.aspx) could be refactored to use Dependency Injection, which should produce cleaner code. The goals are to: Separate the cache provider implementation (using the ASP.NET data cache) from the consumers (loose coupling). This will also mean that the dependency on System.Web for the cache provider does not ripple down into the layers where it is being consumed (such as the domain layer). Provide a decorator pattern to allow a consumer of the cache provider to be implemented separately from the base consumer (i.e. if we have a base repository, we can decorate this with a caching version). Although I used the term repository, in reality the cache consumer could be just about anything. Use constructor injection to provide the Dependency Injection, with a suitable DI container (I use Castle Windsor). The sample code for this post is available on github, https://github.com/RobinHames/CacheProvider.git ICacheProvider In the sample code, the key interface is ICacheProvider, which is in the domain layer. 1: using System; 2: using System.Collections.Generic; 3:   4: namespace CacheDiSample.Domain 5: { 6: public interface ICacheProvider<T> 7: { 8: T Fetch(string key, Func<T> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry); 9: IEnumerable<T> Fetch(string key, Func<IEnumerable<T>> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry); 10: } 11: }   This interface contains two methods to retrieve data from the cache, either as a single instance or as an IEnumerable. the second paramerter is of type Func<T>. This is the method used to retrieve data if nothing is found in the cache. The ASP.NET implementation of the ICacheProvider interface needs to live in a project that has a reference to system.web, typically this will be the root UI project, or it could be a separate project. The key thing is that the domain or data access layers do not need system.web references adding to them. In my sample MVC application, the CacheProvider is implemented in the UI project, in a folder called “CacheProviders”: 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Web; 5: using System.Web.Caching; 6: using CacheDiSample.Domain; 7:   8: namespace CacheDiSample.CacheProvider 9: { 10: public class CacheProvider<T> : ICacheProvider<T> 11: { 12: public T Fetch(string key, Func<T> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry) 13: { 14: return FetchAndCache<T>(key, retrieveData, absoluteExpiry, relativeExpiry); 15: } 16:   17: public IEnumerable<T> Fetch(string key, Func<IEnumerable<T>> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry) 18: { 19: return FetchAndCache<IEnumerable<T>>(key, retrieveData, absoluteExpiry, relativeExpiry); 20: } 21:   22: #region Helper Methods 23:   24: private U FetchAndCache<U>(string key, Func<U> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry) 25: { 26: U value; 27: if (!TryGetValue<U>(key, out value)) 28: { 29: value = retrieveData(); 30: if (!absoluteExpiry.HasValue) 31: absoluteExpiry = Cache.NoAbsoluteExpiration; 32:   33: if (!relativeExpiry.HasValue) 34: relativeExpiry = Cache.NoSlidingExpiration; 35:   36: HttpContext.Current.Cache.Insert(key, value, null, absoluteExpiry.Value, relativeExpiry.Value); 37: } 38: return value; 39: } 40:   41: private bool TryGetValue<U>(string key, out U value) 42: { 43: object cachedValue = HttpContext.Current.Cache.Get(key); 44: if (cachedValue == null) 45: { 46: value = default(U); 47: return false; 48: } 49: else 50: { 51: try 52: { 53: value = (U)cachedValue; 54: return true; 55: } 56: catch 57: { 58: value = default(U); 59: return false; 60: } 61: } 62: } 63:   64: #endregion 65:   66: } 67: }   The FetchAndCache helper method checks if the specified cache key exists, if it does not, the Func<U> retrieveData method is called, and the results are added to the cache. Using Castle Windsor to register the cache provider In the MVC UI project (my application root), Castle Windsor is used to register the CacheProvider implementation, using a Windsor Installer: 1: using Castle.MicroKernel.Registration; 2: using Castle.MicroKernel.SubSystems.Configuration; 3: using Castle.Windsor; 4:   5: using CacheDiSample.Domain; 6: using CacheDiSample.CacheProvider; 7:   8: namespace CacheDiSample.WindsorInstallers 9: { 10: public class CacheInstaller : IWindsorInstaller 11: { 12: public void Install(IWindsorContainer container, IConfigurationStore store) 13: { 14: container.Register( 15: Component.For(typeof(ICacheProvider<>)) 16: .ImplementedBy(typeof(CacheProvider<>)) 17: .LifestyleTransient()); 18: } 19: } 20: }   Note that the cache provider is registered as a open generic type. Consuming a Repository I have an existing couple of repository interfaces defined in my domain layer: IRepository.cs 1: using System; 2: using System.Collections.Generic; 3:   4: using CacheDiSample.Domain.Model; 5:   6: namespace CacheDiSample.Domain.Repositories 7: { 8: public interface IRepository<T> 9: where T : EntityBase 10: { 11: T GetById(int id); 12: IList<T> GetAll(); 13: } 14: }   IBlogRepository.cs 1: using System; 2: using CacheDiSample.Domain.Model; 3:   4: namespace CacheDiSample.Domain.Repositories 5: { 6: public interface IBlogRepository : IRepository<Blog> 7: { 8: Blog GetByName(string name); 9: } 10: }   These two repositories are implemented in the DataAccess layer, using Entity Framework to retrieve data (this is not important though). One important point is that in the BaseRepository implementation of IRepository, the methods are virtual. This will allow the decorator to override them. The BlogRepository is registered in a RepositoriesInstaller, again in the MVC UI project. 1: using Castle.MicroKernel.Registration; 2: using Castle.MicroKernel.SubSystems.Configuration; 3: using Castle.Windsor; 4:   5: using CacheDiSample.Domain.CacheDecorators; 6: using CacheDiSample.Domain.Repositories; 7: using CacheDiSample.DataAccess; 8:   9: namespace CacheDiSample.WindsorInstallers 10: { 11: public class RepositoriesInstaller : IWindsorInstaller 12: { 13: public void Install(IWindsorContainer container, IConfigurationStore store) 14: { 15: container.Register(Component.For<IBlogRepository>() 16: .ImplementedBy<BlogRepository>() 17: .LifestyleTransient() 18: .DependsOn(new 19: { 20: nameOrConnectionString = "BloggingContext" 21: })); 22: } 23: } 24: }   Now I can inject a dependency on the IBlogRepository into a consumer, such as a controller in my sample code: 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Web; 5: using System.Web.Mvc; 6:   7: using CacheDiSample.Domain.Repositories; 8: using CacheDiSample.Domain.Model; 9:   10: namespace CacheDiSample.Controllers 11: { 12: public class HomeController : Controller 13: { 14: private readonly IBlogRepository blogRepository; 15:   16: public HomeController(IBlogRepository blogRepository) 17: { 18: if (blogRepository == null) 19: throw new ArgumentNullException("blogRepository"); 20:   21: this.blogRepository = blogRepository; 22: } 23:   24: public ActionResult Index() 25: { 26: ViewBag.Message = "Welcome to ASP.NET MVC!"; 27:   28: var blogs = blogRepository.GetAll(); 29:   30: return View(new Models.HomeModel { Blogs = blogs }); 31: } 32:   33: public ActionResult About() 34: { 35: return View(); 36: } 37: } 38: }   Consuming the Cache Provider via a Decorator I used a Decorator pattern to consume the cache provider, this means my repositories follow the open/closed principle, as they do not require any modifications to implement the caching. It also means that my controllers do not have any knowledge of the caching taking place, as the DI container will simply inject the decorator instead of the root implementation of the repository. The first step is to implement a BlogRepository decorator, with the caching logic in it. Note that this can reside in the domain layer, as it does not require any knowledge of the data access methods. BlogRepositoryWithCaching.cs 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Text; 5:   6: using CacheDiSample.Domain.Model; 7: using CacheDiSample.Domain; 8: using CacheDiSample.Domain.Repositories; 9:   10: namespace CacheDiSample.Domain.CacheDecorators 11: { 12: public class BlogRepositoryWithCaching : IBlogRepository 13: { 14: // The generic cache provider, injected by DI 15: private ICacheProvider<Blog> cacheProvider; 16: // The decorated blog repository, injected by DI 17: private IBlogRepository parentBlogRepository; 18:   19: public BlogRepositoryWithCaching(IBlogRepository parentBlogRepository, ICacheProvider<Blog> cacheProvider) 20: { 21: if (parentBlogRepository == null) 22: throw new ArgumentNullException("parentBlogRepository"); 23:   24: this.parentBlogRepository = parentBlogRepository; 25:   26: if (cacheProvider == null) 27: throw new ArgumentNullException("cacheProvider"); 28:   29: this.cacheProvider = cacheProvider; 30: } 31:   32: public Blog GetByName(string name) 33: { 34: string key = string.Format("CacheDiSample.DataAccess.GetByName.{0}", name); 35: // hard code 5 minute expiry! 36: TimeSpan relativeCacheExpiry = new TimeSpan(0, 5, 0); 37: return cacheProvider.Fetch(key, () => 38: { 39: return parentBlogRepository.GetByName(name); 40: }, 41: null, relativeCacheExpiry); 42: } 43:   44: public Blog GetById(int id) 45: { 46: string key = string.Format("CacheDiSample.DataAccess.GetById.{0}", id); 47:   48: // hard code 5 minute expiry! 49: TimeSpan relativeCacheExpiry = new TimeSpan(0, 5, 0); 50: return cacheProvider.Fetch(key, () => 51: { 52: return parentBlogRepository.GetById(id); 53: }, 54: null, relativeCacheExpiry); 55: } 56:   57: public IList<Blog> GetAll() 58: { 59: string key = string.Format("CacheDiSample.DataAccess.GetAll"); 60:   61: // hard code 5 minute expiry! 62: TimeSpan relativeCacheExpiry = new TimeSpan(0, 5, 0); 63: return cacheProvider.Fetch(key, () => 64: { 65: return parentBlogRepository.GetAll(); 66: }, 67: null, relativeCacheExpiry) 68: .ToList(); 69: } 70: } 71: }   The key things in this caching repository are: I inject into the repository the ICacheProvider<Blog> implementation, via the constructor. This will make the cache provider functionality available to the repository. I inject the parent IBlogRepository implementation (which has the actual data access code), via the constructor. This will allow the methods implemented in the parent to be called if nothing is found in the cache. I override each of the methods implemented in the repository, including those implemented in the generic BaseRepository. Each override of these methods follows the same pattern. It makes a call to the CacheProvider.Fetch method, and passes in the parentBlogRepository implementation of the method as the retrieval method, to be used if nothing is present in the cache. Configuring the Caching Repository in the DI Container The final piece of the jigsaw is to tell Castle Windsor to use the BlogRepositoryWithCaching implementation of IBlogRepository, but to inject the actual Data Access implementation into this decorator. This is easily achieved by modifying the RepositoriesInstaller to use Windsor’s implicit decorator wiring: 1: using Castle.MicroKernel.Registration; 2: using Castle.MicroKernel.SubSystems.Configuration; 3: using Castle.Windsor; 4:   5: using CacheDiSample.Domain.CacheDecorators; 6: using CacheDiSample.Domain.Repositories; 7: using CacheDiSample.DataAccess; 8:   9: namespace CacheDiSample.WindsorInstallers 10: { 11: public class RepositoriesInstaller : IWindsorInstaller 12: { 13: public void Install(IWindsorContainer container, IConfigurationStore store) 14: { 15:   16: // Use Castle Windsor implicit wiring for the block repository decorator 17: // Register the outermost decorator first 18: container.Register(Component.For<IBlogRepository>() 19: .ImplementedBy<BlogRepositoryWithCaching>() 20: .LifestyleTransient()); 21: // Next register the IBlogRepository inmplementation to inject into the outer decorator 22: container.Register(Component.For<IBlogRepository>() 23: .ImplementedBy<BlogRepository>() 24: .LifestyleTransient() 25: .DependsOn(new 26: { 27: nameOrConnectionString = "BloggingContext" 28: })); 29: } 30: } 31: }   This is all that is needed. Now if the consumer of the repository makes a call to the repositories method, it will be routed via the caching mechanism. You can test this by stepping through the code, and seeing that the DataAccess.BlogRepository code is only called if there is no data in the cache, or this has expired. The next step is to add the SQL Cache Dependency support into this pattern, this will be a future post.

    Read the article

  • Jet Brains release WebStorm 5.0

    - by TATWORTH
    At http://www.jetbrains.com/webstorm/whatsnew/index.html?WS50ROW, Jet Brains have announced the release of WebStorm 5.0, an IDE that brings the ease of code writing in VB.NET and C# that you get with ReSharper, to JavaScript, CSS and LESS. (There are some more details in http://blog.jetbrains.com/webide/2012/08/liveedit-plugin-features-in-detail/)Code completion in JavaScript, CSS and LESS is a very welcome feature. I look forward to trying out Web Storm. The download at http://www.jetbrains.com/webstorm/download/index.html comes with a free 30-day trial).Price information is at http://www.jetbrains.com/webstorm/buy/index.jsp - you should note that if you are an open-source developer, you can apply for a free license. The price of a personal license at £23 + VAT is a no-brainer. The price of a Commercial license would have been paid for in a few days of the increased productivity that this tool brings.Web Storm currently requires Google Chrome to run. Like ReSharper it appears to be a very able tool. It includes tools such as:XSLT debuggingJSLint for checking for JavaScript errorsJavaScript debuggingJavaScript unit testing (including code coverage)JavaScript folding regionsCoffeeScript supportWell I suggest that you try WebStorm 5.0

    Read the article

  • Mod disk_cache permanent caching images and disabling reacurring header updates

    - by user135532
    I am trying to get mod disk_cache to permantly cache images retrieved from an image server on the webserver using ProxyPass. While the image is being retrieved correctly from the server and is served from the cache on further requests, then I am still having the webserver call the image server and causing the cached header to be updated. Because of load concerns then I need to never call the image server on a specific url again after it has been cached once, or extend the refresh time for as long as possible. The webserver is IHS 7.0 The mod's are mod_disk_cache.so, mod_cache.so, mod_proxy.so Version 2.2.8.0 Following is from my httpd.conf: ProxyPass /webserver/media/images/ http://imageserver.com/ws/media/images/ # Caching pictures <IfModule mod_cache.c> <IfModule mod_disk_cache.c> CacheDefaultExpire 2628000 #CacheDisable CacheEnable disk /webserver/media/images/ CacheIgnoreCacheControl On CacheIgnoreHeaders Cookie Referer User-Agent X-Forwarded-For X-Forwarded-Host X-Forwarded-Server Accept-Language Accept Host CacheIgnoreNoLastMod On CacheIgnoreQueryString Off #CacheIgnoreURLSessionIdentifiers CacheLastModifiedFactor 10000000.1 #CacheLock on #CacheLockMaxAge 5 #CacheLockPath CacheMaxExpire 1576800 CacheStoreNoStore On CacheStorePrivate On CacheDirLength 2 CacheDirLevels 3 CacheMaxFileSize 1000000 CacheMinFileSize 1 CacheRoot c:/cacheroot2 </IfModule> </IfModule>

    Read the article

  • Jenkins swarm-plugin jar file, won't run in background

    - by JeanMertz
    We're working on an automation script for our Jenkins slaves on a local Unix server. To connect the slaves to the Jenkins master, we use the swarm plugin. Setting up the master was easy, and connecting clients is also easy with a single command. However, I am trying to get the slave command (a java application) to run in the background without stalling the current process, this doesn't seem to work. I've created an init.d file and added it to update-rc.d but that doesn't work. #!/bin/bash /usr/bin/java -jar /root/swarm-client-1.7-jar-with-dependencies.jar -executors 4 I've also tried to run it with an ampersand & to start the process in the background, but that doesn't work either because - from looking at the source - the jar file actually boots another process that is then started in the foreground. Any ideas on how to make this jar file start without stopping the bootstrap script?

    Read the article

  • Using iptables to make a VPN router

    - by lost_in_the_sauce
    I am attempting to make a VPN connection to a third party VPN site, then forward traffic from my internal computers (ssh and ping for now) out to the VPN site using IPTables. 3rd Party <- (tun0/eth0)Linux VPN Box(eth1) <- Windows7TestBox I am running on CentOS 6.3 Linux and have two network connections eth0-public eth1-private. I am running vpnc-0.5.3-4 which is currently connecting to my destination. When I connect I am able to ping the destination IPAddresses but that is as far as I can get. ping -I tun0 10.1.33.26 success ping -I eth0 10.1.33.26 fail ping -I eth1 10.1.33.26 fail I have my private network Windows 7 test box set up to have the eth1 (private) network of my VPN Server as its gateway and can ping him fine. I need IPTables to send the Windows 7 traffic out the VPN tunnel. I have tried for a few days many different IPTables configurations from this site and others, either the other examples are too simple or overly complicated. The only thing this server is doing is connecting to the VPN and forwarding all traffic. So we can "flush" everything and start from scratch here. It is a blank slate. #!/bin/bash echo "Define variables" ipt="/sbin/iptables" echo "Zero out all counters" $ipt -Z $ipt -t nat -Z $ipt -t mangle -Z echo "Flush all active rules, delete all chains" $ipt -F $ipt -X $ipt -t nat -F $ipt -t nat -X $ipt -t mangle -F $ipt -t mangle -X $ipt -P INPUT ACCEPT $ipt -P FORWARD ACCEPT $ipt -P OUTPUT ACCEPT $ipt -t nat -A POSTROUTING -o tun0 -j MASQUERADE $ipt -A FORWARD -i eth1 -o eth0 -j ACCEPT $ipt -A FORWARD -i eth0 -o eth1 -j ACCEPT $ipt -A FORWARD -i eth0 -o tun0 -j ACCEPT $ipt -A FORWARD -i tun0 -o eth0 -j ACCEPT Again I have done many variations of the above and many other rules from other posts but haven't been able to move forward. It seems like such a simple task, and yet....

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >