Search Results

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

Page 80/489 | < Previous Page | 76 77 78 79 80 81 82 83 84 85 86 87  | Next Page >

  • How To Update EF 4 Entity In ASP.NET MVC 3?

    - by Jason Evans
    Hi there. I have 2 projects - a class library containing an EDM Entity Framework model and a seperate ASP.NET MVC project. I'm having problems with how your suppose to edit and save changes to an entity using MVC. In my controller I have: public class UserController : Controller { public ActionResult Edit(int id) { var rep = new UserRepository(); var user = rep.GetById(id); return View(user); } [HttpPost] public ActionResult Edit(User user) { var rep = new UserRepository(); rep.Update(user); return View(user); } } My UserRepository has an Update method like this: public void Update(User user) { using (var context = new PDS_FMPEntities()) { context.Users.Attach(testUser); context.ObjectStateManager.ChangeObjectState(testUser, EntityState.Modified); context.SaveChanges(); } } Now, when I click 'Save' on the edit user page, the parameter user only contains two values populated: Id, and FirstName. I take it that is due to the fact that I'm only displaying those two properties in the view. My question is this, if I'm updating the user's firstname, and then want to save it, what am I suppose to do about the other User properties which were not shown on the view, since they now contain 0 or NULL values in the user object? I've been reading a lot about using stub entities, but I'm getting nowhere fast, in that none of the examples I've seen actually work. i.e. I keep getting EntityKey related exceptions. Can someone point me to a good tutorial/example of how to update EF 4 entities using a repository class, called by an MVC front-end? Cheers. Jas.

    Read the article

  • Different results between Android Geocoder and Google Geocoding web service

    - by user3571822
    I am creating an Android application and I need to use the geolocation. I have started by using the Geocoder API from Android (android.location.geocoder) but it causes some issues (timed out waiting for response from server) which seem to be common according to what I have read. To make my application work when this kind of error occurs, I use the Geocoding web service. Now, the application works every time. The problem is that the results returned by the geocoder from API and the geocoder from the web service are not the same. For example the web service returns only 3 addresses with only city name and country whereas the geocoding from the API returns about 8 addresses with the feature name, the thoroughfare, the locality... The question is: is there a way to make the results from the web service exactly the same than the ones from the API? EDIT Here is my MainGeocoder class: public class MainGeocoder { private Geocoder geocoderAPI; private GeocoderRest geocoderRest; public MainGeocoder(Context context) { geocoderAPI = new Geocoder(context); geocoderRest = new GeocoderRest(context); } public List<Address> getFromLocationName(String search, int maxResults) { List<Address> addresses; try { addresses = geocoderAPI.getFromLocationName(search, maxResults); return addresses; } catch (IOException e) { e.printStackTrace(); try { addresses = geocoderRest.getFromLocationName(search, maxResults); return addresses; } catch (IOException e1) { return null; } catch (LimitExceededException e1) { return null; } } } } It basically tries to get the list of addresses from the API Geocoder. If an IO exception is thrown it gets this list from the web service by using the GeocoderRest class which has been pasted from here: http://stackoverflow.com/a/15117087/3571822

    Read the article

  • Why does this threading approach not work?

    - by Tomas Lycken
    I have a wierd problem with threading in an ASP.NET application. For some reason, when I run the code in the request thread, everything works as expected. But when I run it in a separate thread, nothing happens. This is verified by calling the below handler with the three flags "on", "off" and "larma" respectively - in the two first cases everything works, but in the latter nothing happens. What am I doing wrong here? In the web project I have a generic handler with the following code: If task = "on" Then Alarm.StartaLarm(personId) context.Response.Write("Larmet är PÅ") ElseIf task = "off" Then Alarm.StoppaLarm(personId) context.Response.Write("Larmet är AV") ElseIf task = "larma" Then Alarm.Larma(personId) context.Response.Write("Larmar... (stängs av automagiskt)") Else context.Response.Write("inget hände - task: " & task) End If The Alarm class has the following methods: Private Shared Sub Larma_Thread(ByVal personId As Integer) StartaLarm(personId) Thread.Sleep(1000 * 30) StoppaLarm(personId) End Sub Public Shared Sub StartaLarm(ByVal personId As Integer) SandSMS(True, personId) End Sub Public Shared Sub StoppaLarm(ByVal personId As Integer) SandSMS(False, personId) End Sub Public Shared Sub SandSMS(ByVal setOn As Boolean, ByVal personId As Integer) ... End Sub

    Read the article

  • Beginner Question on traversing a EF4 model

    - by user564577
    I have a basic EF4 model with two entities. I'm using Self Tracking Entities Client has ClientAddresses relationship on clientkey = clientkey. (1 to many) How do i get a list/collection of client entities (STE) and their addresses (STE) but only ones where they live in a particular state or some such filter on the address??? This seems to filter and bring back clients but doesnt bring back addresses. var j = from client in context.Clients where client.ClientAddresses.All(c => c.ZIP == "80923") select client; I cant get this to create the Addresses because ClientAddresses is IEnumerable and it needs a TrackableCollection var query = from t1 in context.Clients join t2 in context.ClientAddresses on t1.ClientKey equals t2.ClientKey where t2.ZIP == "80923" select new Client { FirstName = t1.FirstName, LastName = t1.LastName, IsEnabled = t1.IsEnabled, ClientKey = t1.ClientKey, ChangeUser = t1.ChangeUser, ChangeDate = t1.ChangeDate, ClientAddresses = from a in t1.ClientAddresses select new ClientAddress { AddressKey = a.AddressKey, AddressLine1 = a.AddressLine1, AddressLine2 = a.AddressLine2, AddressTypeCode = a.AddressTypeCode, City = a.City, ClientKey = a.ClientKey, State = a.State, ZIP = a.ZIP } }; Any pointers would be appreciated. Thanks Edit: This seems to work.... var j = from client in context.Clients.Include("ClientAddresses") where client.ClientAddresses.Any(c => c.ZIP == "80923") select client;

    Read the article

  • How do I fix a "Request format is unrecognized for URL..." error in a web service running in IIS?

    - by Hary
    I am get the following error while running web service in IIS: Server Error in '/Inbox Sevice' Application. Request format is unrecognized for URL unexpectedly ending in '/GetMailsInfo'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/GetMailsInfo'. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/GetMailsInfo'.] System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +490982 System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +104 System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +127 System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +175 System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +120 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42 Does anyone know why I am seeing this error and if there is any way to fix it?

    Read the article

  • Web Audio API and mobile browsers

    - by Michael
    I've run into a problem while implementing sound and music into an HTML game that I'm building. I'm using the Web Audio API, loading all the sound files with XMLHttpRequests and decoding them into an AudioBufferSourceNode with AudioContext.prototype.decodeAudioData(). It looks something like this: var request = new XMLHttpRequest(); request.open("GET", "soundfile.ogg", true); request.responseType = "arraybuffer"; request.onload = function() { context.decodeAudioData(request.response) } request.send(); Everything plays fine, but on mobile the decodeAudioData takes an absurdly long time for the background music. I then tried using AudioContext.prototype.createMediaElementSource() to load the music from an HTML Audio object, since they support streaming and don't have to load the whole file into memory at once. It looked something like this: var audio = new Audio('soundfile.ogg'); var source = context.createMediaElementSource(audio); var mainVolume = context.createGain(); source.connect(mainVolume); mainVolume.connect(context.destination); This loads much faster, but the audio volume isn't affected by the gain node. Works fine on desktop, so I'm assuming this is a bug/limitation of mobile Chrome (testing on Android). Is there actually no good, well-performing way to handle sound on mobile browsers or am just I doing something stupid?

    Read the article

  • Calling NSFetchedResultsController & CoreData experts

    - by JK
    I am having a few nagging issues with NSFetchedResultsController and CoreData, any of which I would be very grateful to get help on. Issue 1 - Updates: I update my store on a background thread which results in certain rows being delete, inserted or updated. The changes are merged into the context on the main thread using the "mergeChangesFromContextDidSaveNotification:" method. Inserts and deletes are updated properly, but updates are not (e.g. the cell label is not updated with the change) although I have confirmed the updates to come through the contextDidSaveNotifcation, exactly like the inserts and deleted. My current workaround is to temporarily change the staleness interval of the context to 0, but this does not seem like the ideal solution. Issue 2 - Deleting objects: My fetch batch size is 20. If an object is deleted by the background thread which is in the first 20 rows, everything works fine. But if the object is after the first 20 rows and the table is scrolled down, a "CoreData could not fulfill a fault" error is raised. I have tried resaving the context and reperforming the frc fetch - all to no avail. Note: In this scenario, the frc delegate method "didChangeObject...." is not called for the delete - I assume this is because the object in question had not been faulted at that time (as it is was outside the initial fetch range). But for some reason, the context still thinks the object is around, although is has been deleted from the store. Issue 3 - Deleting sections : When the deletion of a row leads to the deletion of a section, I have gotten the "invalid number of rows in section???" error. I have worked around this by removing the "reloadSection" line from the NSFetchedResultsChangeMove: section and replacing it with "[tableView insertRowsAtIndexPaths...." This seems to work, but once again, I am not sure if this is the best solution. Any help would be greatly appreciated. Thank you!

    Read the article

  • Async task ASP.net HttpContext.Current.Items is empty - How do handle this?

    - by GuruC
    We are running a very large web application in asp.net MVC .NET 4.0. Recently we had an audit done and the performance team says that there were a lot of null reference exceptions. So I started investigating it from the dumps and event viewer. My understanding was as follows: We are using Asyn Tasks in our controllers. We rely on HttpContext.Current.Items hashtable to store a lot of Application level values. Task<Articles>.Factory.StartNew(() => { System.Web.HttpContext.Current = ControllerContext.HttpContext.ApplicationInstance.Context; var service = new ArticlesService(page); return service.GetArticles(); }).ContinueWith(t => SetResult(t, "articles")); So we are copying the context object onto the new thread that is spawned from Task factory. This context.Items is used again in the thread wherever necessary. Say for ex: public class SomeClass { internal static int StreamID { get { if (HttpContext.Current != null) { return (int)HttpContext.Current.Items["StreamID"]; } else { return DEFAULT_STREAM_ID; } } } This runs fine as long as number of parallel requests are optimal. My questions are as follows: 1. When the load is more and there are too many parallel requests, I notice that HttpContext.Current.Items is empty. I am not able to figure out a reason for this and this causes all the null reference exceptions. 2. How do we make sure it is not null ? Any workaround if present ? NOTE: I read through in StackOverflow and people have questions like HttpContext.Current is null - but in my case it is not null and its empty. I was reading one more article where the author says that sometimes request object is terminated and it may cause problems since dispose is already called on objects. I am doing a copy of Context object - its just a shallow copy and not a deep copy.

    Read the article

  • Update a portion UIView

    - by Brett
    Hi; I'm using -setNeedsDisplayinRect to update only a part of my UIView. However, all of my drawing done previously to calling this method is erased. Here is my code in the UIView subclass: -(void)drawRect:(CGRect)rect{ CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetRGBFillColor(context, r, g, b, 1); CGContextSetRGBStrokeColor(context, r, g, b, 1); CGRect arect = CGRectMake(x,y,1,1); CGContextFillRect(context, arect); NSLog(@"drawing"); } and in the view controller: -(void)drawView{ drawingView = [[DrawingView alloc]init]; x=10; y=10; r=0; g=0; b=0; [drawingView setNeedsDisplayInRect:CGRectMake(x, y, 1, 1)]; x=20; y=20; r=0; g=0; b=0; [drawingView setNeedsDisplayInRect:CGRectMake(x, y, 1, 1)]; } I end up with a screen where there is only one pixel at 20,20. Any help with this is so much appreciated. I am a beginner with XCode and am trying to complete a class project asap.

    Read the article

  • Rendering a CGPDFPage into a UIImage

    - by James Antrobus
    I'm trying to render a CGPDFPage (selected from a CGPDFDocument) into a UIImage to display on a view. I have the following code in MonoTouch which gets me part way there. RectangleF PDFRectangle = new RectangleF(0, 0, UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height); public override void ViewDidLoad () { UIGraphics.BeginImageContext(new SizeF(PDFRectangle.Width, PDFRectangle.Height)); CGContext context = UIGraphics.GetCurrentContext(); context.SaveState(); CGPDFDocument pdfDoc = CGPDFDocument.FromFile("test.pdf"); CGPDFPage pdfPage = pdfDoc.GetPage(1); context.DrawPDFPage(pdfPage); UIImage testImage = UIGraphics.GetImageFromCurrentImageContext(); pdfDoc.Dispose(); context.RestoreState(); UIImageView imageView = new UIImageView(testImage); UIGraphics.EndImageContext(); View.AddSubview(imageView); } A section of the CGPDFPage is displayed but rotated back-to-front and upside down. My question is, how do I select the full pdf page and flip it round to display correctly. I have seen a few examples using ScaleCTM and TranslateCTM but couldn't seem to get them working. Any examples in ObjectiveC are fine, I'll take all the help I can get :) Thanks

    Read the article

  • iOS - is it possible to cache CGContextDrawImage?

    - by woot586
    I used the timing profile tool to identify that 95% of the time is spent calling the function CGContextDrawImage. In my app there are a lot of duplicate images repeatably being chopped from a sprite map and drawn to the screen. I was wondering if it was possible to cache the output of CGContextDrawImage in an NSMutableDictionay, then if the same sprite is requested again it can be just pull it from the cache rather than doing all the work of clipping and rendering it again. This is what i’ve got but I have not been to successful: Definitions if(cache == NULL) cache = [[NSMutableDictionary alloc]init]; //Identifier based on the name of the sprite and location within the sprite. NSString* identifier = [NSString stringWithFormat:@"%@-%d",filename,frame]; Adding to cache CGRect clippedRect = CGRectMake(0, 0, clipRect.size.width, clipRect.size.height); CGContextClipToRect( context, clippedRect); //create a rect equivalent to the full size of the image //offset the rect by the X and Y we want to start the crop //from in order to cut off anything before them CGRect drawRect = CGRectMake(clipRect.origin.x * -1, clipRect.origin.y * -1, atlas.size.width, atlas.size.height); //draw the image to our clipped context using our offset rect CGContextDrawImage(context, drawRect, atlas.CGImage); [cache setValue:UIGraphicsGetImageFromCurrentImageContext() forKey:identifier]; UIGraphicsEndImageContext(); Rendering a cached sprite There is probably a better way to render CGImage which is my ultimate caching goal but at the moment I’m just looking to successfully render the cached image out however this has not been successful. UIImage* cachedImage = [cache objectForKey:identifier]; if(cachedImage){ NSLog(@"Cached %@",identifier); CGRect imageRect = CGRectMake(0, 0, cachedImage.size.width, cachedImage.size.height); if (NULL != UIGraphicsBeginImageContextWithOptions) UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, 0); else UIGraphicsBeginImageContext(imageRect.size); //Use draw for now just to see if the image renders out ok CGContextDrawImage(context, imageRect, cachedImage.CGImage); UIGraphicsEndImageContext(); }

    Read the article

  • iPhone - sorting the results of a core data entity

    - by Digital Robot
    I have a core data entity that represents the attributes of a product, as number, price, etc. The product number is a NSString property and follows the form X.y where X is a number variable of digits and Y is one digit. For example. 132.2, 99.4, etc. I am querying the database to obtain the list of product numbers in order: The code is like this: + (NSArray*)todosOsItens:(NSString *)pName inManagedObjectContext:(NSManagedObjectContext *)context { Product *aProduct = [Product productWithName:pName inManagedObjectContext:context]; NSArray *all = nil; NSFetchRequest *request = [[NSFetchRequest alloc] init]; request.entity = [NSEntityDescription entityForName:@"Attributes" inManagedObjectContext:context]; request.predicate = [NSPredicate predicateWithFormat: @"(belongsTo == %@)", aProduct]; [request setResultType:NSDictionaryResultType]; [request setReturnsDistinctResults:YES]; [request setPropertiesToFetch:[NSArray arrayWithObject:item]]; NSSortDescriptor *sortByItem = [NSSortDescriptor sortDescriptorWithKey:@"ProductNumber" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortByItem]; [request setSortDescriptors:sortDescriptors]; NSError *error = nil; all = [[context executeFetchRequest:request error:&error] mutableCopy]; [request release]; return all; } but this query is not returning the sorted results. The results are coming on their natural order on the database. How do I do that? thanks.

    Read the article

  • iphone: memory problems after refactor

    - by agilpwc
    I had a NIB with several view controllers in it. I modified the code and used Interface Builder decomose interface to get all the view controllers in their own Nib. But now with empty core data database, I'm getting "message sent to deallocated instance" errors. Here is the code flow: From the RootViewController this is called: if (self.dogController == nil) { DogViewController *controller = [[DogViewController alloc] initWithNibName:@"DogViewController" bundle:nil]; self.dogController = controller; [controller release]; } self.dogController.managedObjectContext = self.managedObjectContext; [self.navigationController pushViewController:self.dogController animated:YES]; Then in a dogController a button is pressed to insert a new object and the following code is excuted and the error hits on the save, according to the trace NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity]; NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context]; // If appropriate, configure the new managed object. [newManagedObject setValue:[NSDate date] forKey:@"birthDate"]; [newManagedObject setValue:@"-" forKey:@"callName"]; // Save the context. NSError *error = nil; if (![context save:&error]) { Then the error produced in the console is * -[JudgeViewController numberOfSectionsInTableView:]: message sent to deallocated instance 0x598e580 I'm racking my brain for hours and I can't figure out where my minor changes made something messed up. Any ideas?

    Read the article

  • Storing records in a dropdownlist from DB without using LINQ Data source

    - by user1318369
    I have a website for dance academy where Users can register and add/drop dance classes. In the web page to drop a particular dance, for a particular user, the dropdown displays her registered dances. Now I want to delete one of the dances from the list. So i'll remove the row from the table and also from the dropdownlist. The problem is that everytime the item with the lowest ID (index) is getting deleted, no matter which one the user selects. I think I am storing the DataTextField and DataValueField for the dropdown incorrectly. Can someone please help me out? The code is: private void PopulateDanceDropDown() { var registereddanceList = from dd in context.DANCER_AND_DANCE where dd.UserId == dancerId select new { Text = dd.DanceName, Value = dd.DanceId }; dances.DataSource = registereddanceList; dances.DataTextField = "Text"; dances.DataValueField = "Value"; dances.DataBind(); } protected void dropthedance(object o, EventArgs e) { String strDataValueField = dances.SelectedItem.Value; int danceIDFromDropDown = Convert.ToInt32(strDataValueField); var dancer_dance = from dd in context.DANCER_AND_DANCE where dd.DanceId == danceIDFromDropDown select dd; foreach (var dndd in dancer_dance) { context.DANCER_AND_DANCE.DeleteOnSubmit(dndd); } try { context.SubmitChanges(); } catch (Exception ex) { Console.WriteLine(ex); } PopulateDanceDropDown(); }

    Read the article

  • setImageViewResource Sometimes loads image and sometimes it doesn't.

    - by Niv
    Hi All, I'm writing a simple widget which has an imageview widget that is supposed to load an image dynamically. To do this, I'm starting a service in the onUpdate method of the service. I validated that the service is running, however, the image is loaded only once every 10 times. Here is the code: (In the Original extends AppWidgetProvider) @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Log.d(LOG_TAG, "onUpdate(): Starting Service..1"); context.startService(new Intent(context, UpdateService.class)); } (The service:) @Override public void onStart(Intent intent, int startId) { Log.d(LOG_TAG, "(OnStart) In On Start..!"); AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(this, Original.class)); for (int appWidgetId : appWidgetIds) { RemoteViews remoteView = new RemoteViews(this.getPackageName(), R.layout.widget); remoteView.setImageViewResource(R.id.widgetImage, R.drawable.let02); remoteView.setTextViewText(R.id.widget_textview_month, "aaa"); Log.d(LOG_TAG, "(OnUpdate) Set All Fields!"); appWidgetManager.updateAppWidget(appWidgetId, remoteView); } //super.onStart(intent, startId); return; }

    Read the article

  • LINQ to SQL Queries odd Materialization

    - by ptoinson
    I ran across an interesting Linq to SQL, uh, feature, the other day. Perhaps someone can give me a logical explanation for the reasoning behind the results. Take the code below as my example which utilizes the AdventureWorks database setup in a Linq to SQL DataContext. This is a clip from my unit test. The resulting customer returned from a call to both CustomerQuery_Test_01() and CustomerQuery_Test_02() is the same. However, the query executed on the SQLServer are different is a major way. The method CustomerQuery_Test_01 us causing the entire Customer table to be materialized, which the call to CustomerQuery_Test_02 is only causing the single customer to be materialized. The resulting SQL Queries are at the bottom of this post. Anyone have a good reason for this? To me, it was highly non-intuitive. protected virtual Customer GetByPrimaryKey(Func<Customer, bool> keySelection) { AdventureWorksDataContext context = new AdventureWorksDataContext(); return (from r in context.Customers select r).SingleOrDefault(keySelection); } [TestMethod] public void CustomerQuery_Test_01() { Customer customer = GetByPrimaryKey(c => c.CustomerID == 2); } [TestMethod] public void CustomerQuery_Test_02() { AdventureWorksDataContext context = new AdventureWorksDataContext(); Customer customer = (from r in context.Customers select r).SingleOrDefault(c => c.CustomerID == 2); } Query for CustomerQuery_Test_01 (notice the lack of a where clause) SELECT [t0].[CustomerID], [t0].[NameStyle], [t0].[Title], [t0].[FirstName], [t0].[MiddleName], [t0].[LastName], [t0].[Suffix], [t0].[CompanyName], [t0].[SalesPerson], [t0].[EmailAddress], [t0].[Phone], [t0].[PasswordHash], [t0].[PasswordSalt], [t0].[rowguid], [t0].[ModifiedDate] FROM [SalesLT].[Customer] AS [t0] Query for CustomerQuery_Test_02 (notice the where clause) SELECT [t0].[CustomerID], [t0].[NameStyle], [t0].[Title], [t0].[FirstName], [t0].[MiddleName], [t0].[LastName], [t0].[Suffix], [t0].[CompanyName], [t0].[SalesPerson], [t0].[EmailAddress], [t0].[Phone], [t0].[PasswordHash], [t0].[PasswordSalt], [t0].[rowguid], [t0].[ModifiedDate] FROM [SalesLT].[Customer] AS [t0] WHERE [t0].[CustomerID] = @p0

    Read the article

  • Using NHibernate's HQL to make a query with multiple inner joins

    - by Abu Dhabi
    The problem here consists of translating a statement written in LINQ to SQL syntax into the equivalent for NHibernate. The LINQ to SQL code looks like so: var whatevervar = from threads in context.THREADs join threadposts in context.THREADPOSTs on threads.thread_id equals threadposts.thread_id join posts1 in context.POSTs on threadposts.post_id equals posts1.post_id join users in context.USERs on posts1.user_id equals users.user_id orderby posts1.post_time where threads.thread_id == int.Parse(id) select new { threads.thread_topic, posts1.post_time, users.user_display_name, users.user_signature, users.user_avatar, posts1.post_body, posts1.post_topic }; It's essentially trying to grab a list of posts within a given forum thread. The best I've been able to come up with (with the help of the helpful users of this site) for NHibernate is: var whatevervar = session.CreateQuery("select t.Thread_topic, p.Post_time, " + "u.User_display_name, u.User_signature, " + "u.User_avatar, p.Post_body, p.Post_topic " + "from THREADPOST tp " + "inner join tp.Thread_ as t " + "inner join tp.Post_ as p " + "inner join p.User_ as u " + "where tp.Thread_ = :what") .SetParameter<THREAD>("what", threadid) .SetResultTransformer(Transformers.AliasToBean(typeof(MyDTO))) .List<MyDTO>(); But that doesn't parse well, complaining that the aliases for the joined tables are null references. MyDTO is a custom type for the output: public class MyDTO { public string thread_topic { get; set; } public DateTime post_time { get; set; } public string user_display_name { get; set; } public string user_signature { get; set; } public string user_avatar { get; set; } public string post_topic { get; set; } public string post_body { get; set; } } I'm out of ideas, and while doing this by direct SQL query is possible, I'd like to do it properly, without defeating the purpose of using an ORM. Thanks in advance! EDIT: The database looks like this: http://i41.tinypic.com/5agciu.jpg (Can't post images yet.)

    Read the article

  • Composable FLinq expressions

    - by Daniel
    When doing linq-to-sql in c#, you could do something like this: var data = context.MyTable.Where(x => x.Parameter > 10); var q1 = data.Take(10); var q2 = data.Take(3); q1.ToArray(); q2.ToArray(); This would generate 2 separate SQL queries, one with TOP 10, and the other with TOP 3. In playing around with Flinq, I see that: let data = query <@ seq { for i in context.MyTable do if x.Parameter > 10 then yield i } @> data |> Seq.take 10 |> Seq.toList data |> Seq.take 3 |> Seq.toList is not doing the same thing. Here it seems to do one full query, and then do the "take" calls on the client side. An alternative that I see used is: let q1 = query <@ for i in context.MyTable do if x.Param > 10 then yield i } |> Seq.take 10 @> let q2 = query <@ for i in context.MyTable do if x.Param > 10 then yield i } |> Seq.take 3 @> These 2 generate the SQL with the appropriate TOP N filter. My problem with this is that it doesn't seem composable. I'm basically having to duplicate the "where" clause, and potentially would have to duplicate other other subqueries that I might want to run on a base query. Is there a way to have F# give me something more composable? (I originally posted this question to hubfs, where I have gotten a few answers, dealing with the fact that C# performs the query transformation "at the end", i.e. when the data is needed, where F# is doing that transformation eagerly.)

    Read the article

  • URL Rewrite ASP.net

    - by wandos
    i have an asp.net website where i need to use URL re-write so i have written an HTTP module and i have implemented it and it works correctly the only problem is when the page redirect to its corresponding address the images and the styles are not loaded. here is the http module: // Your BeginRequest event handler. private void Application_BeginRequest(Object source, EventArgs e) { HttpApplication application = (HttpApplication)source; string URL = application.Request.Url.ToString(); //int pid = Convert.ToInt32(application.Request.QueryString["pid"]); if ((URL.ToLower().Contains(".aspx")) || (URL.ToLower().Contains(".js")) || (URL.ToLower().Contains(".css")) || (URL.ToLower().Contains(".gif")) || (URL.ToLower().Contains(".png")) || (URL.ToLower().Contains(".jpeg")) || (URL.ToLower().Contains(".jpe")) || (URL.ToLower().Contains(".jpg")) || (URL.ToLower().Contains(".ashx"))) return; else { string mname = URL.Substring(URL.LastIndexOf("/") + 1).ToString(); Merchand ms = merchantDB.GetMerchant(mname); HttpContext context = application.Context; if (ms != null) { string url = "~/pages/Merchant.aspx?mid=" + ms.MerchandID + "&catid=" + ms.MainCategory + "&subcatid=0"; context.RewritePath(VirtualPathUtility.ToAppRelative(url)); } else { //(""); string url = "~/pages/default.aspx"; context.RewritePath(VirtualPathUtility.ToAppRelative(url)); } } } when i open the page from it normal URL it opens fine, but when i use the url rewrite it open but with out images or styles. when i open firebug i get an error that the css and the javascript are not found

    Read the article

  • Debugging Widget causes ANR

    - by Salv0
    I'm trying to debug an AppWidget but I incurred in a problem :D I placed a breakpoint on the top of the method: public void onReceive(Context context, Intent intent) { Log.v(TAG, "onReceive 1"); // BP on this line super.onReceive(context, intent); String action = intent.getAction(); // Checks on action and computations ... Log.v(TAG, "onReceive 2"); updateWidget(context); Log.v(TAG, "onReceive 3"); } The breakpoint stops the execution as expected but then the process dies. The problem is that the breakpoint ( I guess xD ) cause an ANR and the ActivityManager kills the process. That's the Log: 01-07 14:32:38.886: ERROR/ActivityManager(72): ANR in com.salvo.wifiwidget 01-07 14:32:38.886: INFO/Process(72): Sending signal. PID: 475 SIG: 9 ...... ...... 01-07 14:32:38.906: INFO/ActivityManager(72): Process com.salvo.wifiwidget (pid 475) has died. This cause the debug to stop. So the question is: there's a way to debug the widget without incurring in the ANR?? thanks in advance for the answers

    Read the article

  • Associate activity with database ID

    - by Mohit Deshpande
    I have a main ListView that is based on an adapter from my database. Each database id is "assigned" to an Activity via the ListView. And in my AndroidManifest, each activity has an intent filter with a custom action. Now with this, I have had to create this class: public final class ActivityLauncher { private ActivityLauncher() { } public static void launch(Context c, int id) { switch(id) { case 1: Intent intent = new Intent(); intent.setAction(SomeActivity.ACTION_SOMEACTIVITY); c.startActivity(intent); break; case 2: ... break; ... } } private static void st(Context context, String action) { Intent intent = new Intent(); intent.setAction(action); context.startActivity(intent); } } So I have to manually create a new case for the switch statement. This would get troublesome if I have to rearrange or delete an id. Is there any way to get around this?

    Read the article

  • Database Tutorial: The method open() is undefined for the type MainActivity.DBAdapter

    - by user2203633
    I am trying to do this database tutorial on SQLite Eclipse: https://www.youtube.com/watch?v=j-IV87qQ00M But I get a few errors at the end.. at db.ppen(); i get error: The method open() is undefined for the type MainActivity.DBAdapter and similar for insert record and close. MainActivity: package com.example.studentdatabase; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.app.Activity; import android.app.ListActivity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { /** Called when the activity is first created. */ //DBAdapter db = new DBAdapter(this); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button addBtn = (Button)findViewById(R.id.add); addBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, addassignment.class); startActivity(i); } }); try { String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB"; File f = new File(destPath); if (!f.exists()) { CopyDB( getBaseContext().getAssets().open("mydb"), new FileOutputStream(destPath)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } DBAdapter db = new DBAdapter(); //---add an assignment--- db.open(); long id = db.insertRecord("Hello World", "2/18/2012", "DPR 224", "First Android Project"); id = db.insertRecord("Workbook Exercises", "3/1/2012", "MAT 100", "Do odd numbers"); db.close(); //---get all Records--- /* db.open(); Cursor c = db.getAllRecords(); if (c.moveToFirst()) { do { DisplayRecord(c); } while (c.moveToNext()); } db.close(); */ /* //---get a Record--- db.open(); Cursor c = db.getRecord(2); if (c.moveToFirst()) DisplayRecord(c); else Toast.makeText(this, "No Assignments found", Toast.LENGTH_LONG).show(); db.close(); */ //---update Record--- /* db.open(); if (db.updateRecord(1, "Hello Android", "2/19/2012", "DPR 224", "First Android Project")) Toast.makeText(this, "Update successful.", Toast.LENGTH_LONG).show(); else Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show(); db.close(); */ /* //---delete a Record--- db.open(); if (db.deleteRecord(1)) Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show(); else Toast.makeText(this, "Delete failed.", Toast.LENGTH_LONG).show(); db.close(); */ } private class DBAdapter extends BaseAdapter { private LayoutInflater mInflater; //private ArrayList<> @Override public int getCount() { return 0; } @Override public Object getItem(int arg0) { return null; } @Override public long getItemId(int arg0) { return 0; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { return null; } } public void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException { //---copy 1K bytes at a time--- byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } inputStream.close(); outputStream.close(); } public void DisplayRecord(Cursor c) { Toast.makeText(this, "id: " + c.getString(0) + "\n" + "Title: " + c.getString(1) + "\n" + "Due Date: " + c.getString(2), Toast.LENGTH_SHORT).show(); } public void addAssignment(View view) { Intent i = new Intent("com.pinchtapzoom.addassignment"); startActivity(i); Log.d("TAG", "Clicked"); } } DBAdapter code: package com.example.studentdatabase; public class DBAdapter { public static final String KEY_ROWID = "id"; public static final String KEY_TITLE = "title"; public static final String KEY_DUEDATE = "duedate"; public static final String KEY_COURSE = "course"; public static final String KEY_NOTES = "notes"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "AssignmentsDB"; private static final String DATABASE_TABLE = "assignments"; private static final int DATABASE_VERSION = 2; private static final String DATABASE_CREATE = "create table if not exists assignments (id integer primary key autoincrement, " + "title VARCHAR not null, duedate date, course VARCHAR, notes VARCHAR );"; private final Context context; private DatabaseHelper DBHelper; private SQLiteDatabase db; public DBAdapter(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { try { db.execSQL(DATABASE_CREATE); } catch (SQLException e) { e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS contacts"); onCreate(db); } } //---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } //---insert a record into the database--- public long insertRecord(String title, String duedate, String course, String notes) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_TITLE, title); initialValues.put(KEY_DUEDATE, duedate); initialValues.put(KEY_COURSE, course); initialValues.put(KEY_NOTES, notes); return db.insert(DATABASE_TABLE, null, initialValues); } //---deletes a particular record--- public boolean deleteContact(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //---retrieves all the records--- public Cursor getAllRecords() { return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_DUEDATE, KEY_COURSE, KEY_NOTES}, null, null, null, null, null); } //---retrieves a particular record--- public Cursor getRecord(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_DUEDATE, KEY_COURSE, KEY_NOTES}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---updates a record--- public boolean updateRecord(long rowId, String title, String duedate, String course, String notes) { ContentValues args = new ContentValues(); args.put(KEY_TITLE, title); args.put(KEY_DUEDATE, duedate); args.put(KEY_COURSE, course); args.put(KEY_NOTES, notes); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } } addassignment code: package com.example.studentdatabase; public class addassignment extends Activity { DBAdapter db = new DBAdapter(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add); } public void addAssignment(View v) { Log.d("test", "adding"); //get data from form EditText nameTxt = (EditText)findViewById(R.id.editTitle); EditText dateTxt = (EditText)findViewById(R.id.editDuedate); EditText courseTxt = (EditText)findViewById(R.id.editCourse); EditText notesTxt = (EditText)findViewById(R.id.editNotes); db.open(); long id = db.insertRecord(nameTxt.getText().toString(), dateTxt.getText().toString(), courseTxt.getText().toString(), notesTxt.getText().toString()); db.close(); nameTxt.setText(""); dateTxt.setText(""); courseTxt.setText(""); notesTxt.setText(""); Toast.makeText(addassignment.this,"Assignment Added", Toast.LENGTH_LONG).show(); } public void viewAssignments(View v) { Intent i = new Intent(this, MainActivity.class); startActivity(i); } } What is wrong here? Thanks in advance.

    Read the article

  • JNI Method not found

    - by Select Call
    I have been receiving this error for my JNI code while I tried find the method ,using GetMethodID, my Java method is in an Interface. Here is my interface public interface printReader { public printImg readerPrint(String selectedName) throws Exception; } Native code WprintImgIMPL.h class WprintImgIMPL: public IWprintReader { public: WprintImgIMPL(JNIEnv *env, jobject obj); ~WprintImgIMPL(void); virtual WprintImg readerPrint(char* readerName) ; ..... ..... private: JNIEnv *m_Env; jobject m_jObj; } WprintImgIMPL.cpp WprintImg WprintImgIMPL::readerPrint(char* readerName) { jclass cls = m_Env->GetObjectClass (m_jObj); jmethodID mid = m_Env->GetMethodID (cls, "readerPrint", "(Ljava/lang/String;)Lcom/site/name/printImg;"); ....... ....... } Java code public class printReaderIMPL implements printReader { static final String DEBUG_TAG = ""; android.net.wifi.WifiManager.MulticastLock lock; Context _context; public printReaderIMPL (Context context) { _context = context; } @Override public printImg readerPrint(String selectedName) throws Exception { Log.e(DEBUG_TAG, "readerPrint"); } } Constructor/destructor WprintImgIMPL(JNIEnv *env, jobject obj){ m_Env = env; m_jobj = env->NewGlobalRef(obj); } ~WprintImgIMPL(void) { m_Env->DeleteGlobalRef(m_jobj); } Error: GetMethodID: method not found: Lcom/site/name/NativeCode;.printImg:(Ljava/lang/String;)Lcom/site/name/printImg; Signature are checked twice , after failure I generated again using Javap tool . Thank you if you can input /comment and help in fixing this bug.

    Read the article

  • Core Data to-many relationship in code

    - by Jan Bezemer
    I have three entities: Session, User and Test. A session has 0-many users and a user can perform 0-6 tests. (I say 0 but in the real application always at least 1 is required, at least 1 user for a session and at least 1 test for a user. But I say 0 to express an empty start.) All entities have their own specific data attributes too. A user has a name, A session has a name, a test has six values to be filled in by the user, and so on. But my issue is with the relationships. How do I set multiple users and have them added to one session (same goes for multiple tests for one user). How do I show the content in a right way? How do I show a session that has multiple users and these users having completed multiple tests? Here's my code so far with regard to issue 1: Session *session = [NSEntityDescription insertNewObjectForEntityForName:@"Session" inManagedObjectContext:context]; session.name = @"Session 1"; User *users = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:context]; users.age = [NSNumber numberWithInt:28]; users.session = session; //sessie.users = users; [sessie addUserObject:users]; With regard to issue 2: I can log the session, but I can't get the user(s) logged from a session. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Session" inManagedObjectContext:context]; [fetchRequest setEntity:entity]; NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; for (Session *info in fetchedObjects) { NSLog(@"Name: %@", info.name); NSLog(@"Having problems with this: %@",info.user); //User *details = info.user; //NSLog(@"User: %@", details.age); }

    Read the article

  • Application widget with bundle?

    - by Varand pezeshk
    Hey guys, I have application widget, and I want to send some data to the intent that is attached to PendingIntent, by clicking the widget. here's my code final int N = appWidgetIds.length; for (int i = 0; i < N; i++) { int appWidgetId = appWidgetIds[i]; Intent intent = new Intent(context, UpComingBDays.class); if(bdaysAmount != 0){ Bundle bundle = new Bundle(); bundle.putIntegerArrayList("WIDGETIDS", tempAllIDS); intent.putExtras(bundle); System.out.println("bund insertedddddddddddddd....................."); } PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.widget_layout); remoteView.setTextViewText(R.id.widget_text, finalText4TextView); remoteView.setOnClickPendingIntent(R.id.WidgetImageButton, pendingIntent); appWidgetManager.updateAppWidget(appWidgetId, remoteView); } super.onUpdate(context, appWidgetManager, appWidgetIds); I realize always "bund insertedddddddddd......" is printed on CatLog, but the intent's bundle is null. what is incorrect? how can i send data by clicking on widget. plz dont offer to use services as my code does not have anything with it. many thanks.

    Read the article

< Previous Page | 76 77 78 79 80 81 82 83 84 85 86 87  | Next Page >