Search Results

Search found 12222 results on 489 pages for 'initial context'.

Page 49/489 | < Previous Page | 45 46 47 48 49 50 51 52 53 54 55 56  | Next Page >

  • Tomcat deploy error

    - by David
    When deploying an application with the Tomcat manager I get the following error: FAIL - Failed to deploy application at context path /prademo Tomcat log shows: INFO: HTMLManager: install: Installing context configuration at '/home//webapps/PRA/META-INF/context.xml' from '/home//webapps/PRA' java.io.FileNotFoundException: /home/dstefan/webapps/PRA/META-INF/context.xml (Permission denied) Permission to what? Both PRA and contex.xml have -rwxrwxrwx. Thanks!

    Read the article

  • RouteTable.Routes.GetVirtualPath with route data asp.net MVC 2

    - by Bill
    Dear all, I'm trying to get a URL from my routes table. Here is the method. private static void RedirectToRoute(ActionExecutingContext context, string param) { var actionName = context.ActionDescriptor.ActionName; var controllerName = context.ActionDescriptor.ControllerDescriptor.ControllerName; var rc = new RequestContext(context.HttpContext, context.RouteData); string url = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { actionName = actionName, controller = controllerName, parameter = param })).VirtualPath; context.HttpContext.Response.Redirect(url, true); } I'm trying to map it to. However RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { actionName = actionName, controller = controllerName, parameter = param })) keeps giving me null. Any thoughts? routes.MapRoute( "default3", // Route name "{parameter}/{controller}/{action}", // URL with parameters new { parameter= "parameterValue", controller = "Home", action = "Index" } ); I know I can use redirectToAction and other methods, but I would like to change the URL in the browser with new routedata.

    Read the article

  • EPPlus - .xlsx is locked for editing by 'another user'

    - by AdamTheITMan
    I have searched through every possible answer on SO for a solution, but nothing has worked. I am basically creating an excel file from a database and sending the results to the response stream using EPPlus(OpenXML). The following code gives me an error when trying to open my generated excel sheet "[report].xlsx is locked for editing by 'another user'." It will open fine the first time, but the second time it's locked. Dim columnData As New List(Of Integer) Dim rowHeaders As New List(Of String) Dim letter As String = "B" Dim x As Integer = 0 Dim trendBy = context.Session("TRENDBY").ToString() Dim dateHeaders As New List(Of String) dateHeaders = DirectCast(context.Session("DATEHEADERS"), List(Of String)) Dim DS As New DataSet DS = DirectCast(context.Session("DS"), DataSet) Using excelPackage As New OfficeOpenXml.ExcelPackage Dim excelWorksheet = excelPackage.Workbook.Worksheets.Add("Report") 'Add title to the top With excelWorksheet.Cells("B1") .Value = "Account Totals by " + If(trendBy = "Months", "Month", "Week") .Style.Font.Bold = True End With 'add date headers x = 2 'start with letter B (aka 2) For Each Header As String In dateHeaders With excelWorksheet.Cells(letter + "2") .Value = Header .Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Right .AutoFitColumns() End With x = x + 1 letter = Helper.GetColumnIndexToColumnLetter(x) Next 'Adds the descriptive row headings down the left side of excel sheet x = 0 For Each DC As DataColumn In DS.Tables(0).Columns If (x < DS.Tables(0).Columns.Count) Then rowHeaders.Add(DC.ColumnName) End If Next Dim range = excelWorksheet.Cells("A3:A30") range.LoadFromCollection(rowHeaders) 'Add the meat and potatoes of report x = 2 For Each dTable As DataTable In DS.Tables columnData.Clear() For Each DR As DataRow In dTable.Rows For Each item As Object In DR.ItemArray columnData.Add(item) Next Next letter = Helper.GetColumnIndexToColumnLetter(x) excelWorksheet.Cells(letter + "3").LoadFromCollection(columnData) With excelWorksheet.Cells(letter + "3") .Formula = "=SUM(" + letter + "4:" + letter + "6)" .Style.Font.Bold = True .Style.Font.Size = 12 End With With excelWorksheet.Cells(letter + "7") .Formula = "=SUM(" + letter + "8:" + letter + "11)" .Style.Font.Bold = True .Style.Font.Size = 12 End With With excelWorksheet.Cells(letter + "12") .Style.Font.Bold = True .Style.Font.Size = 12 End With With excelWorksheet.Cells(letter + "13") .Formula = "=SUM(" + letter + "14:" + letter + "20)" .Style.Font.Bold = True .Style.Font.Size = 12 End With With excelWorksheet.Cells(letter + "21") .Formula = "=SUM(" + letter + "22:" + letter + "23)" .Style.Font.Bold = True .Style.Font.Size = 12 End With With excelWorksheet.Cells(letter + "24") .Formula = "=SUM(" + letter + "25:" + letter + "26)" .Style.Font.Bold = True .Style.Font.Size = 12 End With With excelWorksheet.Cells(letter + "27") .Formula = "=SUM(" + letter + "28:" + letter + "29)" .Style.Font.Bold = True .Style.Font.Size = 12 End With With excelWorksheet.Cells(letter + "30") .Formula = "=SUM(" + letter + "3," + letter + "7," + letter + "12," + letter + "13," + letter + "21," + letter + "24," + letter + "27)" .Style.Font.Bold = True .Style.Font.Size = 12 End With x = x + 1 Next range.AutoFitColumns() 'send it to response Using stream As New MemoryStream(excelPackage.GetAsByteArray()) context.Response.Clear() context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" context.Response.AddHeader("content-disposition", "attachment; filename=filetest.xlsx") context.Response.OutputStream.Write(stream.ToArray(), 0, stream.ToArray().Length) context.Response.Flush() context.Response.Close() End Using End Using

    Read the article

  • WCF Data Service Exception

    - by Ravi
    Hi, I am working on C#.Net with ADO.NET Dataservice WCF Data Services. I try to update one record to relational table, when I reach context.SetLink() I am getting exception("The context is not currently tracking the entity"). I don't know how to solve this problem. My code is specified below. LogNote dbLogNote =logNote; LogSubSession dbLogSubSession = (from p in context.LogSubSession where p.UID == logNote.SubSessionId select p).First<LogSubSession>() as LogSubSession; context.AddToLogNote(dbLogNote); dbLogNote.LogSubSession = dbLogSubSession; context.SetLink(dbLogNote, "LogSubSession", dbLogSubSession); context.SaveChanges(); Here LogSubSession is a primary table and LogNote is a foreign table. I am updating data into foreign table based on primary key table. Thanks

    Read the article

  • java.lang.NoClassDefFoundError: org/springframework/transaction/interceptor/TransactionInterceptor

    - by user1137146
    I am trying to integrate spring 3.1.1 with hibernate 4.0. This is my dispatcher-servlet.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.future.controllers" /> <context:annotation-config /> <context:component-scan base-package="com.future.services.menu" /> <context:component-scan base-package="com.future.dao" /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/bar_visitor2" p:username="root" p:password=""/> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> </bean> <tx:annotation-driven /> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> When I try to use @Transactional annotation I am getting an error java.lang.NoClassDefFoundError: org/springframework/transaction/interceptor/TransactionInterceptor. I checked my classpath and there is TransactionInterceptor.class. What am I doing wrong? Should I add something? Edit This is my lib folder:

    Read the article

  • Can I pass constructor parameters to Unity's Resolve() method?

    - by NotDan
    I am using Microsoft's Unity for dependency injection and I want to do something like this: IDataContext context = _unityContainer.Resolve<IDataContext>(); var repositoryA = _unityContainer.Resolve<IRepositoryA>(context); //Same instance of context var repositoryB = _unityContainer.Resolve<IRepositoryB>(context); //Same instance of context IDataContext context2 = _unityContainer.Resolve<IDataContext>(); //New instance var repositoryA2 = _unityContainer.Resolve<IRepositoryA>(context2); RepositoryA and RepositoryB both have a constructor that takes an IDataContext parameter, and I want Unity to initialize the repository with the context that I pass it. Also note that IDataContext is not registered with Unity (I dont want 3 instances of IDataContext).

    Read the article

  • UITableViewCell rounded corners and clip subviews

    - by Brenden
    I can't find anything anywhere(search engines, docs, here, etc) that shows how to create rounded corners (esp. in a grouped table view) on an element that also clips the subviews. I have code that properly creates a rounded rectangle out of a path with 4 arcs(the rounded corners) that has been tested in the drawRect: method in my subclassed uitableviewcell. The issue is that the subviews, which happen to be uibuttons with their internal uiimageviews, do no obey the CGContextClip() that the uitableviewcell obeys. Here is the code: - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGFloat radius = 12; CGFloat width = CGRectGetWidth(rect); CGFloat height = CGRectGetHeight(rect); // Make sure corner radius isn't larger than half the shorter side if (radius > width/2.0) radius = width/2.0; if (radius > height/2.0) radius = height/2.0; CGFloat minx = CGRectGetMinX(rect) + 10; CGFloat midx = CGRectGetMidX(rect); CGFloat maxx = CGRectGetMaxX(rect) - 10; CGFloat miny = CGRectGetMinY(rect); CGFloat midy = CGRectGetMidY(rect); CGFloat maxy = CGRectGetMaxY(rect); [[UIColor greenColor] set]; CGContextBeginPath(context); CGContextMoveToPoint(context, minx, midy); CGContextAddArcToPoint(context, minx, miny, midx, miny, radius); CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius); CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius); CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius); CGContextClip(context); CGContextFillRect(context, rect); [super drawRect:rect]; } Because this specific case is static(only shows in 1 specific row of buttons), I can edit the images being used for the buttons to get the desired effect. HOWEVER, I have another case that is dynamic. Specifically, a grouped table with lots of database-driven results that will show photos that may be in the first or last row with rounded corners and thus needs to be clipped). So, is it possible to create a CGContextClip() that also clips the subviews? If so, how?

    Read the article

  • Spring MVC annotation config problem

    - by Seth
    I'm trying to improve my spring mvc configuration so as to not require a new config file for every servlet I add, but I'm running into problems. I've tried using this tutorial as a starting point, but I'm running into an issue that I can't figure out. The problem is that when I do a GET to my servlet, I get back a 404 error. Here's my config and a representative java snippet from a Controller: web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>SightLogix Coordination System</display-name> <description>SightLogix Coordination System</description> <servlet> <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/application-context.xml /WEB-INF/application-security.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> <url-pattern>/slcs/*</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/application-context.xml /WEB-INF/application-security.xml </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> application-context.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-init-method="init" default-destroy-method="destroy"> <mvc:annotation-driven /> <context:component-scan base-package="top.level" /> </beans> application-security.xml: <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"> <http> <intercept-url pattern="/**" access="ROLE_MANAGER" requires-channel="https" /> <http-basic /> </http> <authentication-manager> <authentication-provider user-service-ref="myUserDetailsService"> <password-encoder hash="sha"/> </authentication-provider> </authentication-manager> <beans:bean id="myUserDetailsService" class="path.to.my.UserDetailsServiceImpl"> </beans:bean> </beans:beans> Snippet of a Controller class (one of many, but they all look essentially like this): @Controller @RequestMapping("/foo.xml") public class FooController { @RequestMapping(method=RequestMethod.GET) public void handleGET(HttpServletRequest request, HttpServletResponse response) throws IOException { ... Can anyone tell me what I'm doing incorrectly? Thanks!

    Read the article

  • How does TransactionScope guarantee data integrity across multiple databases?

    - by Bas Smit
    Hey guys, Can someone tell me the principle of how TransactionScope guarantees data integrity across multiple databases? I imagine it first sends the commands to the databases and then waits for the databases to respond before sending them a message to apply the command sent earlier. However when execution is stopped abruptly when sending those apply messages we could still end up with a database that has applied the command and one that has not. Can anyone shed some light on this? Edit: I guess what Im asking is can I rely on TransactionScope to guarantee data integrity when writing to multiple databases in case of a power outage or a sudden shutdown. Thanks, Bas Example: using(var scope=new TransactionScope()) { using (var context = new FirstEntities()) { context.AddToSomethingSet(new Something()); context.SaveChanges(); } using (var context = new SecondEntities()) { context.AddToSomethingElseSet(new SomethingElse()); context.SaveChanges(); } scope.Complete(); }

    Read the article

  • Creating a tiled map with blender

    - by JamesB
    I'm looking at creating map tiles based on a 3D model made in blender, The map is 16 x 16 in blender. I've got 4 different zoom levels and each tile is 100 x 100 pixels. The entire map at the most zoomed out level is 4 x 4 tiles constructing an image of 400 x 400. The most zoomed in level is 256 x 256 obviously constructing an image of 25600 x 25600 What I need is a script for blender that can create the tiles from the model. I've never written in python before so I've been trying to adapt a couple of the scripts which are already there. So far I've come up with a script, but it doesn't work very well. I'm having real difficulties getting the tiles to line up seamlessly. I'm not too concerned about changing the height of the camera as I can always create the same zoomed out tiles at 6400 x 6400 images and split the resulting images into the correct tiles. Here is what I've got so far... #!BPY """ Name: 'Export Map Tiles' Blender: '242' Group: 'Export' Tip: 'Export to Map' """ import Blender from Blender import Scene,sys from Blender.Scene import Render def init(): thumbsize = 200 CameraHeight = 4.4 YStart = -8 YMove = 4 XStart = -8 XMove = 4 ZoomLevel = 1 Path = "/Images/Map/" Blender.drawmap = [thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path] def show_prefs(): buttonthumbsize = Blender.Draw.Create(Blender.drawmap[0]); buttonCameraHeight = Blender.Draw.Create(Blender.drawmap[1]) buttonYStart = Blender.Draw.Create(Blender.drawmap[2]) buttonYMove = Blender.Draw.Create(Blender.drawmap[3]) buttonXStart = Blender.Draw.Create(Blender.drawmap[4]) buttonXMove = Blender.Draw.Create(Blender.drawmap[5]) buttonZoomLevel = Blender.Draw.Create(Blender.drawmap[6]) buttonPath = Blender.Draw.Create(Blender.drawmap[7]) block = [] block.append(("Image Size", buttonthumbsize, 0, 500)) block.append(("Camera Height", buttonCameraHeight, -0, 10)) block.append(("Y Start", buttonYStart, -10, 10)) block.append(("Y Move", buttonYMove, 0, 5)) block.append(("X Start", buttonXStart,-10, 10)) block.append(("X Move", buttonXMove, 0, 5)) block.append(("Zoom Level", buttonZoomLevel, 1, 10)) block.append(("Export Path", buttonPath,0,200,"The Path to save the tiles")) retval = Blender.Draw.PupBlock("Draw Map: Preferences" , block) if retval: Blender.drawmap[0] = buttonthumbsize.val Blender.drawmap[1] = buttonCameraHeight.val Blender.drawmap[2] = buttonYStart.val Blender.drawmap[3] = buttonYMove.val Blender.drawmap[4] = buttonXStart.val Blender.drawmap[5] = buttonXMove.val Blender.drawmap[6] = buttonZoomLevel.val Blender.drawmap[7] = buttonPath.val Export() def Export(): scn = Scene.GetCurrent() context = scn.getRenderingContext() def cutStr(str): #cut off path leaving name c = str.find("\\") while c != -1: c = c + 1 str = str[c:] c = str.find("\\") str = str[:-6] return str #variables from gui: thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path = Blender.drawmap XMove = XMove / ZoomLevel YMove = YMove / ZoomLevel Camera = Scene.GetCurrent().getCurrentCamera() Camera.LocZ = CameraHeight / ZoomLevel YStart = YStart + (YMove / 2) XStart = XStart + (XMove / 2) #Point it straight down Camera.RotX = 0 Camera.RotY = 0 Camera.RotZ = 0 TileCount = 4**ZoomLevel #Because the first thing we do is move the camera, start it off the map Camera.LocY = YStart - YMove for i in range(0,TileCount): Camera.LocY = Camera.LocY + YMove Camera.LocX = XStart - XMove for j in range(0,TileCount): Camera.LocX = Camera.LocX + XMove Render.EnableDispWin() context.extensions = True context.renderPath = Path #setting thumbsize context.imageSizeX(thumbsize) context.imageSizeY(thumbsize) #could be put into a gui. context.imageType = Render.PNG context.enableOversampling(0) #render context.render() #save image ZasString = '%s' %(int(ZoomLevel)) XasString = '%s' %(int(j+1)) YasString = '%s' %(int((3-i)+1)) context.saveRenderedImage("Z" + ZasString + "X" + XasString + "Y" + YasString) #close the windows Render.CloseRenderWindow() try: type(Blender.drawmap) except: #print 'initialize extern variables' init() show_prefs()

    Read the article

  • How to get rid of previous reflection when reflecting a UIImageView (with changing pictures)?

    - by epale
    Hi everyone, I have managed to use the reflection sample app from apple to create a reflection from a UIImageView. But the problem is that when I change the picture inside the UIImageView, the reflection from the previous displayed picture remains on the screen. The new reflection on the next picture then overlaps the previous reflection. How do I ensure that the previous reflection is removed when I change to the next picture? Thank you so much. I hope my question is not too basic. Here is the codes which i used so far: //reflection self.view.autoresizesSubviews = YES; self.view.userInteractionEnabled = YES; // create the reflection view CGRect reflectionRect = currentView.frame; // the reflection is a fraction of the size of the view being reflected reflectionRect.size.height = reflectionRect.size.height * kDefaultReflectionFraction; // and is offset to be at the bottom of the view being reflected reflectionRect = CGRectOffset(reflectionRect, 0, currentView.frame.size.height); reflectionView = [[UIImageView alloc] initWithFrame:reflectionRect]; // determine the size of the reflection to create NSUInteger reflectionHeight = currentView.bounds.size.height * kDefaultReflectionFraction; // create the reflection image, assign it to the UIImageView and add the image view to the containerView reflectionView.image = [self reflectedImage:currentView withHeight:reflectionHeight]; reflectionView.alpha = kDefaultReflectionOpacity; [self.view addSubview:reflectionView]; //reflection */ Then the codes below are used to form the reflection: CGImageRef CreateGradientImage(int pixelsWide, int pixelsHigh) { CGImageRef theCGImage = NULL; // gradient is always black-white and the mask must be in the gray colorspace CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); // create the bitmap context CGContextRef gradientBitmapContext = CGBitmapContextCreate(nil, pixelsWide, pixelsHigh, 8, 0, colorSpace, kCGImageAlphaNone); // define the start and end grayscale values (with the alpha, even though // our bitmap context doesn't support alpha the gradient requires it) CGFloat colors[] = {0.0, 1.0, 1.0, 1.0}; // create the CGGradient and then release the gray color space CGGradientRef grayScaleGradient = CGGradientCreateWithColorComponents(colorSpace, colors, NULL, 2); CGColorSpaceRelease(colorSpace); // create the start and end points for the gradient vector (straight down) CGPoint gradientStartPoint = CGPointZero; CGPoint gradientEndPoint = CGPointMake(0, pixelsHigh); // draw the gradient into the gray bitmap context CGContextDrawLinearGradient(gradientBitmapContext, grayScaleGradient, gradientStartPoint, gradientEndPoint, kCGGradientDrawsAfterEndLocation); CGGradientRelease(grayScaleGradient); // convert the context into a CGImageRef and release the context theCGImage = CGBitmapContextCreateImage(gradientBitmapContext); CGContextRelease(gradientBitmapContext); // return the imageref containing the gradient return theCGImage; } CGContextRef MyCreateBitmapContext(int pixelsWide, int pixelsHigh) { CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); // create the bitmap context CGContextRef bitmapContext = CGBitmapContextCreate (nil, pixelsWide, pixelsHigh, 8, 0, colorSpace, // this will give us an optimal BGRA format for the device: (kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst)); CGColorSpaceRelease(colorSpace); return bitmapContext; } (UIImage *)reflectedImage:(UIImageView *)fromImage withHeight:(NSUInteger)height { if (!height) return nil; // create a bitmap graphics context the size of the image CGContextRef mainViewContentContext = MyCreateBitmapContext(fromImage.bounds.size.width, height); // offset the context - // This is necessary because, by default, the layer created by a view for caching its content is flipped. // But when you actually access the layer content and have it rendered it is inverted. Since we're only creating // a context the size of our reflection view (a fraction of the size of the main view) we have to translate the // context the delta in size, and render it. // CGFloat translateVertical= fromImage.bounds.size.height - height; CGContextTranslateCTM(mainViewContentContext, 0, -translateVertical); // render the layer into the bitmap context CALayer *layer = fromImage.layer; [layer renderInContext:mainViewContentContext]; // create CGImageRef of the main view bitmap content, and then release that bitmap context CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext); CGContextRelease(mainViewContentContext); // create a 2 bit CGImage containing a gradient that will be used for masking the // main view content to create the 'fade' of the reflection. The CGImageCreateWithMask // function will stretch the bitmap image as required, so we can create a 1 pixel wide gradient CGImageRef gradientMaskImage = CreateGradientImage(1, height); // create an image by masking the bitmap of the mainView content with the gradient view // then release the pre-masked content bitmap and the gradient bitmap CGImageRef reflectionImage = CGImageCreateWithMask(mainViewContentBitmapContext, gradientMaskImage); CGImageRelease(mainViewContentBitmapContext); CGImageRelease(gradientMaskImage); // convert the finished reflection image to a UIImage UIImage *theImage = [UIImage imageWithCGImage:reflectionImage]; // image is retained by the property setting above, so we can release the original CGImageRelease(reflectionImage); return theImage; } */

    Read the article

  • Dependency Injection with Spring/Junit/JPA

    - by Steve
    I'm trying to create JUnit tests for my JPA DAO classes, using Spring 2.5.6 and JUnit 4.8.1. My test case looks like this: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:config/jpaDaoTestsConfig.xml"} ) public class MenuItem_Junit4_JPATest extends BaseJPATestCase { private ApplicationContext context; private InputStream dataInputStream; private IDataSet dataSet; @Resource private IMenuItemDao menuItemDao; @Test public void testFindAll() throws Exception { assertEquals(272, menuItemDao.findAll().size()); } ... Other test methods ommitted for brevity ... } I have the following in my jpaDaoTestsConfig.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- uses the persistence unit defined in the META-INF/persistence.xml JPA configuration file --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="CONOPS_PU" /> </bean> <bean id="groupDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.GroupDao" lazy-init="true" /> <bean id="permissionDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.PermissionDao" lazy-init="true" /> <bean id="applicationUserDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.ApplicationUserDao" lazy-init="true" /> <bean id="conopsUserDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.ConopsUserDao" lazy-init="true" /> <bean id="menuItemDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.MenuItemDao" lazy-init="true" /> <!-- enables interpretation of the @Required annotation to ensure that dependency injection actually occures --> <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> <!-- enables interpretation of the @PersistenceUnit/@PersistenceContext annotations providing convenient access to EntityManagerFactory/EntityManager --> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/> <!-- transaction manager for use with a single JPA EntityManagerFactory for transactional data access to a single datasource --> <bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <!-- enables interpretation of the @Transactional annotation for declerative transaction managment using the specified JpaTransactionManager --> <tx:annotation-driven transaction-manager="jpaTransactionManager" proxy-target-class="false"/> </beans> Now, when I try to run this, I get the following: SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@fa60fa6] to prepare test instance [null(mil.navy.ndms.conops.common.dao.impl.MenuItem_Junit4_JPATest)] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mil.navy.ndms.conops.common.dao.impl.MenuItem_Junit4_JPATest': Injection of resource fields failed; nested exception is java.lang.IllegalStateException: Specified field type [interface javax.persistence.EntityManagerFactory] is incompatible with resource type [javax.persistence.EntityManager] at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessAfterInstantiation(CommonAnnotationBeanPostProcessor.java:292) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:959) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:329) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:255) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:93) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:130) at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:61) at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:54) at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34) at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44) at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:52) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196) Caused by: java.lang.IllegalStateException: Specified field type [interface javax.persistence.EntityManagerFactory] is incompatible with resource type [javax.persistence.EntityManager] at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.checkResourceType(InjectionMetadata.java:159) at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.(PersistenceAnnotationBeanPostProcessor.java:559) at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$1.doWith(PersistenceAnnotationBeanPostProcessor.java:359) at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:492) at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:469) at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:351) at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(PersistenceAnnotationBeanPostProcessor.java:296) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:745) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:448) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(AccessController.java:219) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:168) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:435) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:409) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:537) at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:180) at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:105) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessAfterInstantiation(CommonAnnotationBeanPostProcessor.java:289) ... 18 more It seems to be telling me that its attempting to store an EntityManager object into an EntityManagerFactory field, but I don't understand how or why. My DAO classes accept both an EntityManager and EntityManagerFactory via the @PersistenceContext attribute, and they work find if I load them up and run them without the @ContextConfiguration attribute (i.e. if I just use the XmlApplcationContext to load the DAO and the EntityManagerFactory directly in setUp ()). Any insights would be appreciated. Thanks. --Steve

    Read the article

  • Strange error in ASP.NET

    - by rockinthesixstring
    Every once in a while I get about 10 - 20 identical errors on my asp.net app. It's always the same, and I'm wondering if it is someone trying to hack in (it happens about once a month). Source: System.Web Message: The file '/~/Default.aspx' does not exist. User IP: 89.122.29.80 User Browser: Unknown 0.0 User OS: Unknown Stack trace: at System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath) at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean noAssert) at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp, Boolean noAssert) at System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) at System.Web.UI.PageHandlerFactory.System.Web.IHttpHandlerFactory2.GetHandler(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) at System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean completedSynchronously) why on earth would someone be trying to access "/~/Default.aspx" ?

    Read the article

  • Possible to do rounded corners in custom Progressbar progressDrawable?

    - by b-ryce
    I have a progress bar that is supposed to look like the attached image: And I've made it a long way. I'm very close the only part that isn't working is the rounded corners for the progressDrawable. Here is what mine looks like. (Notice, circled in red, that the fill inside the white outline does not have rounded corners): So, I've found a couple of ways to make this work when the progress bar is colored in with a shape, gradient, or color. BUT, I can't get it with an image as the progressDrawable. Here is my class that extends ProgressBar public class RoundedProgressBar extends ProgressBar{ private Paint paint; public RoundedProgressBar(Context context) { super(context); setup(); } public RoundedProgressBar(Context context, AttributeSet attrs) { super(context, attrs); setup(); } public RoundedProgressBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setup(); ; } protected void setup() { paint = new Paint(); } @Override protected synchronized void onDraw(Canvas canvas) { // First draw the regular progress bar, then custom draw our text super.onDraw(canvas); paint.setColor(Color.WHITE); paint.setStyle(Paint.Style.STROKE); RectF r = new RectF(0,0,getWidth()-1,getHeight()-1); canvas.drawRoundRect(r,getHeight()/2,getHeight()/2, paint); } } Here is my selector: <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@android:id/background" android:drawable="@drawable/slider_track" /> <item android:id="@android:id/secondaryProgress" android:drawable="@drawable/slider_track" /> <item android:id="@android:id/progress" android:drawable="@drawable/slider_track_progress" /> </layer-list> Here are the images used in the selector: slider_track- slider_track_progress- Here is where I embed my progressbar in the layout for my activity <com.android.component.RoundedProgressBar android:id="@+id/player_hp_bar" android:layout_width="fill_parent" android:layout_height="36dip" android:layout_marginLeft="30dip" android:layout_marginRight="30dip" android:max="100" style="?android:attr/progressBarStyleHorizontal" android:progressDrawable="@drawable/slider_layer_list" android:progress="20" android:maxHeight="12dip" android:minHeight="12dip" /> Anyone know how to make this work?

    Read the article

  • How can I call the iPhone to draw using other method?

    - by Tattat
    I have a view with a class called "drawingViewController", and I have the drawRect method: - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(context, 2.0); CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); CGContextMoveToPoint(context, 0.0f, 0.0f); CGContextAddLineToPoint(context, 100.0f, 100.0f); CGContextStrokePath(context); } But I wanna to define some other drawing method, but it did't work, how can I do so apart from calling drawRect method? thz in advance.

    Read the article

  • [ASP.NET] IIS7 downloading file length

    - by GTD
    I've following code for file download: FileInfo fileInfo = new FileInfo(filePath); context.Response.Clear(); context.Response.ContentType = "application/octet-stream"; context.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(filePath)); context.Response.AddHeader("Content-Length", fileInfo.Length.ToString()); context.Response.WriteFile(filePath); context.Response.End(); When I run it on my local IIS6 it works fine. Web browser (tested on IE8, Firefox 3.5.2, Opera 10) shows file length before I start download the file. When I run this code on remote IIS7, web browser doesn't shows file length. File length is unknown. Why I don't get file length when this code runs under IIS7?

    Read the article

  • Active Directory validate service account and user accounts

    - by Padur
    Hello folks I have an issue here, I guess you all know what is AD service account and why it is used for, if not please see the below description ? SSL-Explorer requires a dedicated Active Directory account to use for authenticating AD users. This account serves as a link to your Active Directory database. If the Service Account is not found on your AD database then the SSL-Explorer service will not start. Well I have Active Directory service account details and user submitted login/password details.In the code below I validated service account by giving MEMBER_GRPUP and adminPassword and I check whether the user exists in Active Directory by submitting samaaccountname but my question here is how do I validate the password submitted for that user? I am not sure how to do this, I appreciate if anybody has any suggestions on this. Thanks for your time. public boolean validateUserFromActiveDirectory(String userId) { final String MEMBER_GROUP = "CN=asdadasd,OU=asdasdasd Accounts,OU=adasdas,OU=asdasdas,DC=asdasdas,DC=asdasdas,DC=adasdasd,DC=asdasdasd"; String employeeNumber = ""; final String LDAP_INIT_CTX = "com.sun.jndi.ldap.LdapCtxFactory"; final String LDAP_URL = "ldap://xx-ssssssss.eee.eee.eeeee.eeeee:636"; final String MY_ATTRS[] = { "employeeNumber" }; String adminPassword = "somepassword"; String securityProtocol = "ssl"; boolean isValidUser = false; try { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_INIT_CTX); env.put(Context.PROVIDER_URL, LDAP_URL); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.REFERRAL, "follow"); env.put(Context.SECURITY_PRINCIPAL, MEMBER_GROUP); env.put(Context.SECURITY_CREDENTIALS, adminPassword); env.put(Context.SECURITY_PROTOCOL, securityProtocol); //C:\Documents and Settings\yourusername\Local Settings\Temp File tf = File.createTempFile("adentTruststore", ".jks"); tf.deleteOnExit(); byte buffer[] = new byte[0x1000]; ClassLoader cl = JNDI.class.getClassLoader(); InputStream in = cl.getResourceAsStream( "someTruststore.jks"); FileOutputStream out = new FileOutputStream(tf); int cnt; while ((cnt = in.read(buffer)) != -1) out.write(buffer, 0, cnt); in.close(); out.close(); System.setProperty("javax.net.ssl.trustStore", tf .getAbsolutePath()); DirContext context = new InitialLdapContext(env, null); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration results = context.search( "XX=ent,XX=abc,XX=aaaaa,XX=aaaa", "(sAMAccountName=" + userId + ")", searchControls); if (results != null && results.hasMore()) { //some logic } } } catch (Exception e) { e.printStackTrace(); } return isValidUser; }

    Read the article

  • UIView Animation won't run transition

    - by dpelletier
    So, I've searched quite a bit for this and can't seem to find a solution. This code works: CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationDuration:5]; [c setCenter:CGPointMake(200, 200)]; [UIView commitAnimations]; This code doesn't: CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationBeginsFromCurrentState:YES]; [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:c cache:YES]; [UIView setAnimationDuration:5]; [c exchangeSubviewAtIndex:0 withSubviewAtIndex:1]; [UIView commitAnimations]; And I know the call to exchangeSubViewAtIndex is working because if I remove it from the animation block it functions as expected. Anyone have any insight as to why this transition won't run? Something I need to import?

    Read the article

  • Android OnClick in ListView calling parent function

    - by user1321683
    I have an Android application with a ListView in it, the ListView will setup fine but now I want a image in the ListView to be clickable. I do this by using 2 classes, the Activity class (parent) and an ArrayAdapter to fill the list. In the ArrayAdapter I implement a OnClickListener for the image in the list that I want to be clickable. So far it all works. But now I want to run a function from the activity class when the onClick, for the image in the list, is run but I do not know how. Below are the 2 classes that I use. First the Activity class: public class parent_class extends Activity implements OnClickListener, OnItemClickListener { child_class_list myList; ListView myListView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // setup the Homelist data myList = new child_class_list (this, Group_Names, Group_Dates); myListView = (ListView) findViewById(R.id.list); // set the HomeList myListView.setAdapter( myList ); myListView.setOnItemClickListener(this); } void function_to_run() { // I want to run this function from the LiscView Onclick } public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // do something } } And the ArrayAdapter from where I want to call a function from the Activity class: public class child_class_list extends ArrayAdapter<String> { // private private final Context context; private String[] mName; private String[] mDate; public child_class_list (Context context, String[] Name, String[] Date) { super(context, R.layout.l_home, GroupName); this.context = context; this.mName = Name; this.mDate = Date; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.l_home, parent, false); ImageView selectable_image = (ImageView) rowView.findViewById(R.id.l_selectable_image); selectable_image.setOnClickListener(new OnClickListener() { public void onClick(View v) { // I want to run the function_to_run() function from the parant class here } } ); // get the textID's TextView tvName = (TextView) rowView.findViewById(R.id.l_name); TextView tvDate = (TextView) rowView.findViewById(R.id.l_date); // set the text tvName.setText (mName[position]); tvDate.setText (mDate[position]); return rowView; } } If anyone knows how to run the function in the activity class from the arrayadapter or how to set the image onClickListener in the Activity Class I would greatly apriciate the help.

    Read the article

  • What am I missing in this ASP.NET XSS Security Helper class?

    - by smartcaveman
    I need a generic method for preventing XSS attacks in ASP.NET. The approach I came up with is a ValidateRequest method that evaluates the HttpRequest for any potential issues, and if issues are found, redirect the user to the same page, but in a away that is not threatening to the application. (Source code below) While I know this method will prevent most XSS attacks, I am not certain that I am adequately preventing all possible attacks while also minimizing false positives. So, what is the most effective way to adequately prevent all possible attacks, while minimizing false positives? Are there changes I should make to the helper class below, or is there an alternative approach or third party library that offers something more convincing? public static class XssSecurity { public const string PotentialXssAttackExpression = "(http(s)*(%3a|:))|(ftp(s)*(%3a|:))|(javascript)|(alert)|(((\\%3C) <)[^\n]+((\\%3E) >))"; private static readonly Regex PotentialXssAttackRegex = new Regex(PotentialXssAttackExpression, RegexOptions.IgnoreCase); public static bool IsPotentialXssAttack(this HttpRequest request) { if(request != null) { string query = request.QueryString.ToString(); if(!string.IsNullOrEmpty(query) && PotentialXssAttackRegex.IsMatch(query)) return true; if(request.HttpMethod.Equals("post", StringComparison.InvariantCultureIgnoreCase)) { string form = request.Form.ToString(); if (!string.IsNullOrEmpty(form) && PotentialXssAttackRegex.IsMatch(form)) return true; } if(request.Cookies.Count > 0) { foreach(HttpCookie cookie in request.Cookies) { if(PotentialXssAttackRegex.IsMatch(cookie.Value)) { return true; } } } } return false; } public static void ValidateRequest(this HttpContext context, string redirectToPath = null) { if(context == null || !context.Request.IsPotentialXssAttack()) return; // expire all cookies foreach(HttpCookie cookie in context.Request.Cookies) { cookie.Expires = DateTime.Now.Subtract(TimeSpan.FromDays(1)); context.Response.Cookies.Set(cookie); } // redirect to safe path bool redirected = false; if(redirectToPath != null) { try { context.Response.Redirect(redirectToPath,true); redirected = true; } catch { redirected = false; } } if (redirected) return; string safeUrl = context.Request.Url.AbsolutePath.Replace(context.Request.Url.Query, string.Empty); context.Response.Redirect(safeUrl,true); } }

    Read the article

  • Using IOperationBehavior to supply a WCF parameter

    - by Chris Kemp
    This is my first step into the world of stackoverflow, so apologies if I cock anything up. I'm trying to create a WCF Operation which has a parameter that is not exposed to the outside world, but is instead automatically passed into the function. So the world sees this: int Add(int a, int b) But it is implemented as: int Add(object context, int a, int b) Then, the context gets supplied by the system at run-time. The example I'm working with is completely artificial, but mimics something that I'm looking into in a real-world scenario. I'm able to get close, but not quite the whole way there. First off, I created a simple method and wrote an application to confirm it works. It does. It returns a + b and writes the context as a string to my debug. Yay. [OperationContract] int Add(object context, int a, int b); I then wrote the following code: public class SupplyContextAttribute : Attribute, IOperationBehavior { public void Validate(OperationDescription operationDescription) { if (!operationDescription.Messages.Any(m => m.Body.Parts.First().Name == "context")) throw new FaultException("Parameter 'context' is missing."); } public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) { dispatchOperation.Invoker = new SupplyContextInvoker(dispatchOperation.Invoker); } public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) { } public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) { // Remove the 'context' parameter from the inbound message operationDescription.Messages[0].Body.Parts.RemoveAt(0); } } public class SupplyContextInvoker : IOperationInvoker { readonly IOperationInvoker _invoker; public SupplyContextInvoker(IOperationInvoker invoker) { _invoker = invoker; } public object[] AllocateInputs() { return _invoker.AllocateInputs().Skip(1).ToArray(); } private object[] IntroduceContext(object[] inputs) { return new[] { "MyContext" }.Concat(inputs).ToArray(); } public object Invoke(object instance, object[] inputs, out object[] outputs) { return _invoker.Invoke(instance, IntroduceContext(inputs), out outputs); } public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state) { return _invoker.InvokeBegin(instance, IntroduceContext(inputs), callback, state); } public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result) { return _invoker.InvokeEnd(instance, out outputs, result); } public bool IsSynchronous { get { return _invoker.IsSynchronous; } } } And my WCF operation now looks like this: [OperationContract, SupplyContext] int Amend(object context, int a, int b); My updated references no longer show the 'context' parameter, which is exactly what I want. The trouble is that whenver I run the code, it gets past the AllocateInputs and then throws an Index was outside the bounds of the Array. error somewhere in the WCF guts. I've tried other things, and I find that I can successfully change the type of the parameter and rename it and have my code work. But the moment I remove the parameter it falls over. Can anyone give me some idea of how to get this to work (or if it can be done at all).

    Read the article

  • How to select all parent objects into DataContext using single LINQ query ?

    - by too
    I am looking for an answer to a specific problem of fetching whole LINQ object hierarchy using single SELECT. At first I was trying to fill as much LINQ objects as possible using LoadOptions, but AFAIK this method allows only single table to be linked in one query using LoadWith. So I have invented a solution to forcibly set all parent objects of entity which of list is to be fetched, although there is a problem of multiple SELECTS going to database - a single query results in two SELECTS with the same parameters in the same LINQ context. For this question I have simplified this query to popular invoice example: public static class Extensions { public static IEnumerable<T> ForEach<T>(this IEnumerable<T> collection, Action<T> func) { foreach(var c in collection) { func(c); } return collection; } } public IEnumerable<Entry> GetResults(AppDataContext context, int CustomerId) { return ( from entry in context.Entries join invoice in context.Invoices on entry.EntryInvoiceId equals invoice.InvoiceId join period in context.Periods on invoice.InvoicePeriodId equals period.PeriodId // LEFT OUTER JOIN, store is not mandatory join store in context.Stores on entry.EntryStoreId equals store.StoreId into condStore from store in condStore.DefaultIfEmpty() where (invoice.InvoiceCustomerId = CustomerId) orderby entry.EntryPrice descending select new { Entry = entry, Invoice = invoice, Period = period, Store = store } ).ForEach(x => { x.Entry.Invoice = Invoice; x.Invoice.Period = Period; x.Entry.Store = Store; } ).Select(x => x.Entry); } When calling this function and traversing through result set, for example: var entries = GetResults(this.Context); int withoutStore = 0; foreach(var k in entries) { if(k.EntryStoreId == null) withoutStore++; } the resulting query to database looks like (single result is fetched): SELECT [t0].[EntryId], [t0].[EntryInvoiceId], [t0].[EntryStoreId], [t0].[EntryProductId], [t0].[EntryQuantity], [t0].[EntryPrice], [t1].[InvoiceId], [t1].[InvoiceCustomerId], [t1].[InvoiceDate], [t1].[InvoicePeriodId], [t2].[PeriodId], [t2].[PeriodName], [t2].[PeriodDateFrom], [t4].[StoreId], [t4].[StoreName] FROM [Entry] AS [t0] INNER JOIN [Invoice] AS [t1] ON [t0].[EntryInvoiceId] = [t1].[InvoiceId] INNER JOIN [Period] AS [t2] ON [t2].[PeriodId] = [t1].[InvoicePeriodId] LEFT OUTER JOIN ( SELECT 1 AS [test], [t3].[StoreId], [t3].[StoreName] FROM [Store] AS [t3] ) AS [t4] ON [t4].[StoreId] = ([t0].[EntryStoreId]) WHERE (([t1].[InvoiceCustomerId]) = @p0) ORDER BY [t0].[InvoicePrice] DESC -- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [186] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1 SELECT [t0].[EntryId], [t0].[EntryInvoiceId], [t0].[EntryStoreId], [t0].[EntryProductId], [t0].[EntryQuantity], [t0].[EntryPrice], [t1].[InvoiceId], [t1].[InvoiceCustomerId], [t1].[InvoiceDate], [t1].[InvoicePeriodId], [t2].[PeriodId], [t2].[PeriodName], [t2].[PeriodDateFrom], [t4].[StoreId], [t4].[StoreName] FROM [Entry] AS [t0] INNER JOIN [Invoice] AS [t1] ON [t0].[EntryInvoiceId] = [t1].[InvoiceId] INNER JOIN [Period] AS [t2] ON [t2].[PeriodId] = [t1].[InvoicePeriodId] LEFT OUTER JOIN ( SELECT 1 AS [test], [t3].[StoreId], [t3].[StoreName] FROM [Store] AS [t3] ) AS [t4] ON [t4].[StoreId] = ([t0].[EntryStoreId]) WHERE (([t1].[InvoiceCustomerId]) = @p0) ORDER BY [t0].[InvoicePrice] DESC -- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [186] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1 The question is why there are two queries and how can I fetch LINQ objects without such hacks?

    Read the article

  • Create custom component based on LinearLayout, declaring layout in XML

    - by pheelicks
    I've been trying to create a Compound Control in Android 1.5 (as described here) but havn't been able to find any good examples on how to do this using an XML file to specify a layout. I'm fine with creating an Activity and then loading an xml file using the following in the constructor: setContentView(R.layout.main); However, I want to do this in subclass of LinearLayout - so I can use this compound component in other XML layouts. Something along the lines of: public class CustomView extends LinearLayout { public CustomView(Context context) { super(context); setupView(); } public CustomView(Context context, AttributeSet attrs) { super(context, attrs); setupView(); } public void setupView() { setContentView(R.layout.custom); // Not possible } } What is the correct way of going about doing this?

    Read the article

  • launch android activity from non-activity class

    - by Alberto Barrera
    im New on Android. I know theres a lot of similar Questions but anyone is helping. Im using a 3rd party app that just launch a class that extends their own class. So from that class i would like to launch an activity. public class SkyTest extends VtiUserExit { @Override public VtiUserExitResult execute() throws VtiExitException { // TODO Auto-generated method stub logInfo("TEST"); return null; } } How do i launch an activity named MainActivity from here. i tryed this: Context context = null; Intent intent = new Intent(context, MainActivity.class); context.startActivity(intent); but its not working, i know i cant use the null context, but how do i create a context o how it works? Thanks

    Read the article

  • Upgrading Entity Framework 1.0 to 4.0 to include foreign keys

    - by duthiega
    Currently I've been working with Entity Framework 1.0 which is located under a service façade. Below is one of the save methods I've created to either update or insert the device in question. This currently works but, I can't help feel that its a bit of a hack having to set the referenced properties to null then re-attach them just to get an insert to work. The changedDevice already holds these values, so why do I need to assign them again. So, I thought I'll update the model to EF4. That way I can just directly access the foreign keys. However, on doing this I've found that there doesn't seem to be an easy way to add the foreign keys except by removing the entity from the diagram and re-adding it. I don't want to do this as I've already been through all the entity properties renaming them from the DB column names. Can anyone help? /// <summary> /// Saves the non network device. /// </summary> /// <param name="nonNetworkDeviceDto">The non network device dto.</param> public void SaveNonNetworkDevice(NonNetworkDeviceDto nonNetworkDeviceDto) { using (var context = new AssetNetworkEntities2()) { var changedDevice = TransformationHelper.ConvertNonNetworkDeviceDtoToEntity(nonNetworkDeviceDto); if (!nonNetworkDeviceDto.DeviceId.Equals(-1)) { var originalDevice = context.NonNetworkDevices.Include("Status").Include("NonNetworkType").FirstOrDefault( d => d.DeviceId.Equals(nonNetworkDeviceDto.DeviceId)); context.ApplyAllReferencedPropertyChanges(originalDevice, changedDevice); context.ApplyCurrentValues(originalDevice.EntityKey.EntitySetName, changedDevice); } else { var maxNetworkDevice = context.NonNetworkDevices.OrderBy("it.DeviceId DESC").First(); changedDevice.DeviceId = maxNetworkDevice.DeviceId + 1; var status = changedDevice.Status; var nonNetworkType = changedDevice.NonNetworkType; changedDevice.Status = null; changedDevice.NonNetworkType = null; context.AttachTo("DeviceStatuses", status); if (nonNetworkType != null) { context.AttachTo("NonNetworkTypes", nonNetworkType); } changedDevice.Status = status; changedDevice.NonNetworkType = nonNetworkType; context.AddToNonNetworkDevices(changedDevice); } context.SaveChanges(); } }

    Read the article

< Previous Page | 45 46 47 48 49 50 51 52 53 54 55 56  | Next Page >