public override void LoadModelParameters(string parameters)
		{
			var url = new UrlParser(UrlUtil.Url);

			if (url.GetQueryParam("mode") == "new")
			{
				Mode = DocumentMode.New;
				return;
			}

			var docId = url.GetQueryParam("id");
			var neighbors = url.GetQueryParam("neighbors");
			if (neighbors != null)
				NeighborIds = neighbors.Split(',').ToList();
			if (string.IsNullOrWhiteSpace(docId) == false)
			{
				Mode = DocumentMode.DocumentWithId;
				LocalId = docId;
				SetCurrentDocumentKey(docId);
				DatabaseCommands.GetAsync(docId)
					.ContinueOnSuccessInTheUIThread(newdoc =>
														{
															if (newdoc == null)
															{
																HandleDocumentNotFound();
																return;
															}
															document.Value = newdoc;
															isLoaded = true;
														})
					.Catch();
				return;
			}

			projectionId = url.GetQueryParam("projection");
			if (string.IsNullOrWhiteSpace(projectionId) == false)
			{
				Mode = DocumentMode.Projection;
				try
				{
					ViewableDocument viewableDocument;
					ProjectionData.Projections.TryGetValue(projectionId, out viewableDocument);

					var ravenJObject = RavenJObject.Parse(viewableDocument.InnerDocument.ToJson().ToString(Formatting.None));
					var newdoc = ravenJObject.ToJsonDocument();
					document.Value = newdoc;
					LocalId = projectionId;
				}
				catch
				{
					HandleDocumentNotFound();
					throw; // Display why we couldn't parse the projection from the URL correctly
				}
			}
		}
        public static DocumentNavigator FromUrl(UrlParser parser)
        {
            var mode = parser.GetQueryParam("navigationMode");

            if (mode == "allDocs")
                return AllDocumentsNavigator.AllDocumentsFromUrl(parser);
            
            if (mode == "index")
                return IndexDocumentsNavigator.IndexNavigatorFromUrl(parser);

            return new SingleDocumentNavigator(parser.GetQueryParam("id"));
        }
		public override void LoadModelParameters(string parameters)
		{
			var urlParser = new UrlParser(parameters);
			if (urlParser.GetQueryParam("mode") == "new")
			{
				IsNewTransformer = true;
				Header = "New Transformer";

				UpdateFromTransformer(new TransformerDefinition());

				return;
			}

			var name = urlParser.Path;
			if (string.IsNullOrWhiteSpace(name))
				HandleTransformerNotFound(null);

			Header = name;
			OriginalName = name;
			IsNewTransformer = false;

			DatabaseCommands.GetTransformerAsync(name)
				.ContinueOnUIThread(task =>
				{
					if (task.IsFaulted || task.Result == null)
					{
						HandleTransformerNotFound(name);
						return;
					}

					UpdateFromTransformer(task.Result);
				}).Catch();
		}
		public override void Execute(object parameter)
		{
			bool shouldRedirect = true;

			var urlParser = new UrlParser(UrlUtil.Url);
			if (urlParser.GetQueryParam("database") == databaseName)
				shouldRedirect = false;

			urlParser.SetQueryParam("database", databaseName);

			var server = ApplicationModel.Current.Server.Value;
			server.SetCurrentDatabase(urlParser);
			server.SelectedDatabase.Value.AsyncDatabaseCommands
				.EnsureSilverlightStartUpAsync()
				.Catch();

			var updateAllFromServer = View.UpdateAllFromServer();
			refreshStaticModels
				.Except(updateAllFromServer.Select(x=>x.GetType()))
				.Select(model => (Model) Activator.CreateInstance(model))
				.ForEach(model => model.ForceTimerTicked());
			
			
			if (shouldRedirect)
			{
				UrlUtil.Navigate(urlParser.BuildUrl());
			}
		}
		public override void LoadModelParameters(string parameters)
		{
			var url = new UrlParser(UrlUtil.Url);

			if (url.GetQueryParam("mode") == "new")
			{
				Mode = DocumentMode.New;
				return;
			}

			var docId = url.GetQueryParam("id");
			if (string.IsNullOrWhiteSpace(docId) == false)
			{
				Mode = DocumentMode.DocumentWithId;
				SetCurrentDocumentKey(docId);
				DatabaseCommands.GetAsync(docId)
					.ContinueOnSuccessInTheUIThread(newdoc =>
									   {
										   if (newdoc == null)
										   {
											   HandleDocumentNotFound();
											   return;
										   }
										   document.Value = newdoc;
										   isLoaded = true;
									   	originalId = docId;
									   })
					.Catch();
				return;
			}

			var projection = url.GetQueryParam("projection");
			if (string.IsNullOrWhiteSpace(projection) == false)
			{
				Mode = DocumentMode.Projection;
				try
				{
					var newdoc = RavenJObject.Parse(projection).ToJsonDocument();
					document.Value = newdoc;
				}
				catch
				{
					HandleDocumentNotFound();
					throw; // Display why we couldn't parse the projection from the URL correctly
				}
			}
		}
Exemple #6
0
		public override void LoadModelParameters(string parameters)
		{
			var urlParser = new UrlParser(parameters);
			var name = urlParser.GetQueryParam("name");
			if (SelectedCollection.Value != null && SelectedCollection.Value.Documents.Value != null)
			{
				SelectedCollection.Value.Documents.Value.Pager.SetSkip(urlParser);
				ForceTimerTicked();
			}
			initialSelectedDatabaseName = name;
		}
Exemple #7
0
		private void PutCollectionNameInTheUrl()
		{
			var urlParser = new UrlParser(UrlUtil.Url);
			var collection = SelectedCollection.Value;
			if (collection == null)
				return;
			var name = collection.Name;
			initialSelectedDatabaseName = name;
			if (urlParser.GetQueryParam("name") != name)
			{
				urlParser.SetQueryParam("name", name);
				UrlUtil.Navigate(urlParser.BuildUrl());
			}
		}
		public override void Execute(object parameter)
		{
			var urlParser = new UrlParser(UrlUtil.Url);
			if (urlParser.GetQueryParam("database") == databaseName)
			{
			    return;
			}
			if (navigateAfter) 
				urlParser = new UrlParser("/documents");

			urlParser.SetQueryParam("database", databaseName);
			// MainPage.ContentFrame_Navigated takes care of actually responding to the db name change
			UrlUtil.Navigate(urlParser.BuildUrl());
		}
Exemple #9
0
        // EnsureDatabaseParameterIncluded
        private void ContentFrame_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            if (navigationMode != NavigationMode.New) return;

            var urlParser = new UrlParser(e.Uri.ToString());
            if (urlParser.GetQueryParam("database") != null)
                return;

            e.Cancel = true;
            navigationMode = NavigationMode.Refresh;
            urlParser.SetQueryParam("database", ApplicationModel.Current.Server.Value.SelectedDatabase.Value.Name);
            urlParser.NavigateTo();
            navigationMode = NavigationMode.New;
        }
Exemple #10
0
		private void Initialize()
		{
            if (DesignerProperties.IsInDesignTool)
            {
                return;
            }

			documentStore = new DocumentStore
			{
				Url = Url
			};

			var urlParser = new UrlParser(UrlUtil.Url);
			var apiKey = urlParser.GetQueryParam("api-key");
			if (string.IsNullOrEmpty(apiKey) == false)
				documentStore.ApiKey = apiKey;

			documentStore.Initialize();

			// We explicitly enable this for the Studio, we rely on SL to actually get us the credentials, and that 
			// already gives the user a clear warning about the dangers of sending passwords in the clear. I think that 
			// this is sufficient warning and we don't require an additional step, so we can disable this check safely.
			documentStore.JsonRequestFactory.
				EnableBasicAuthenticationOverUnsecureHttpEvenThoughPasswordsWouldBeSentOverTheWireInClearTextToBeStolenByHackers =
				true;
			
			documentStore.JsonRequestFactory.ConfigureRequest += (o, eventArgs) =>
			{
				if (onWebRequest != null)
					onWebRequest(eventArgs.Request);
			};

			defaultDatabase = new[] { new DatabaseModel(DatabaseModel.DefaultDatabaseName, documentStore) };
			Databases.Set(defaultDatabase);
			SetCurrentDatabase(new UrlParser(UrlUtil.Url));

			DisplayBuildNumber();
			DisplyaLicenseStatus();

			var changeDatabaseCommand = new ChangeDatabaseCommand();
			SelectedDatabase.PropertyChanged += (sender, args) =>
			{
				if (SelectedDatabase.Value == null)
					return;
				var databaseName = SelectedDatabase.Value.Name;
				Command.ExecuteCommand(changeDatabaseCommand, databaseName);
			};
		}
		public override void Execute(object parameter)
		{
			bool shouldRedirect = true;

			var urlParser = new UrlParser(UrlUtil.Url);
			if (urlParser.GetQueryParam("database") == databaseName)
				shouldRedirect = false;

			urlParser.SetQueryParam("database", databaseName);

			var server = ApplicationModel.Current.Server.Value;
			server.SetCurrentDatabase(urlParser);
			server.SelectedDatabase.Value.AsyncDatabaseCommands
				.EnsureSilverlightStartUpAsync()
				.Catch();

			if (shouldRedirect)
			{
				UrlUtil.Navigate(urlParser.BuildUrl());
			}
		}
Exemple #12
0
		private void Initialize()
		{
			if (DesignerProperties.IsInDesignTool)
				return;

			documentStore = new DocumentStore
			{
				Url = Url
			};

			var urlParser = new UrlParser(UrlUtil.Url);
			var apiKey = urlParser.GetQueryParam("api-key");
			if (string.IsNullOrEmpty(apiKey) == false)
				documentStore.ApiKey = apiKey;

			documentStore.Initialize();

			// We explicitly enable this for the Studio, we rely on SL to actually get us the credentials, and that 
			// already gives the user a clear warning about the dangers of sending passwords in the clear. I think that 
			// this is sufficient warning and we don't require an additional step, so we can disable this check safely.
			documentStore.JsonRequestFactory.
			              EnableBasicAuthenticationOverUnsecuredHttpEvenThoughPasswordsWouldBeSentOverTheWireInClearTextToBeStolenByHackers
				=
				true;

			documentStore.JsonRequestFactory.ConfigureRequest += (o, eventArgs) =>
			{
				if (onWebRequest != null)
					onWebRequest(eventArgs.Request);
			};

			defaultDatabase = new[] {Constants.SystemDatabase};
			Databases.Set(defaultDatabase);
			SetCurrentDatabase(new UrlParser(UrlUtil.Url));

			//DisplayRawUrl();
			DisplayBuildNumber();
			DisplayLicenseStatus();
			TimerTickedAsync();
		}
	    private void PutCollectionNameInTheUrl()
		{
			var urlParser = new UrlParser(UrlUtil.Url);
			var collection = SelectedCollection.Value;
			if (collection == null)
				return;
			var name = collection.Name;
			initialSelectedCollectionName = name;
			if (urlParser.GetQueryParam("collection") != name)
			{
			    if (name != "")
			    {
			        urlParser.SetQueryParam("collection", name);
			    }
			    else
			    {
			        urlParser.RemoveQueryParam("collection");
			    }

			    UrlUtil.Navigate(urlParser.BuildUrl());
			}
		}
Exemple #14
0
	    protected override async void OnViewLoaded()
	    {
			if (firstLoad)
				RegisterToDatabaseChange();

			firstLoad = false;

			Status.Sections.Clear();
			OnPropertyChanged(() => CurrentDatabase);
		    await DatabaseCommands.GetStatisticsAsync();

		    Status.Sections.Add(new StatisticsStatusSectionModel());
			Status.Sections.Add(new LogsStatusSectionModel());
			Status.Sections.Add(new AlertsStatusSectionModel());
			Status.Sections.Add(new IndexesErrorsStatusSectionModel());
			Status.Sections.Add(new ReplicationStatisticsStatusSectionModel());
			Status.Sections.Add(new UserInfoStatusSectionModel());

			var url = new UrlParser(UrlUtil.Url);

			var id = url.GetQueryParam("id");
			if (string.IsNullOrWhiteSpace(id) == false)
			{
				switch (id)
				{
					case "indexes-errors":
						Status.SelectedSection.Value = Status.Sections[3];
						break;
					case "replication":
						Status.SelectedSection.Value = Status.Sections[4];
						break;
					default:
						Status.SelectedSection.Value = Status.Sections[0];
						break;
				}
			}
			else
				Status.SelectedSection.Value = Status.Sections[0];
	    }
Exemple #15
0
		public void SetCurrentDatabase(UrlParser urlParser)
		{
			var databaseName = urlParser.GetQueryParam("database");
			if (databaseName == null)
			{
				SelectedDatabase.Value = defaultDatabase[0];
				return;
			}
			if (SelectedDatabase.Value != null && SelectedDatabase.Value.Name == databaseName)
				return;
			var database = Databases.FirstOrDefault(x => x.Name == databaseName);
			if (database != null)
			{
				SelectedDatabase.Value = database;
				return;
			}
			singleTenant = urlParser.GetQueryParam("api-key") != null;
			var databaseModel = new DatabaseModel(databaseName, documentStore);
			Databases.Add(databaseModel);
			SelectedDatabase.Value = databaseModel;
		}
Exemple #16
0
		public void SetSkip(UrlParser urlParser)
		{
			short s;
			short.TryParse(urlParser.GetQueryParam("skip"), out s);
			Skip = s;
		}
Exemple #17
0
	    protected override async void OnViewLoaded()
	    {
			if(firstLoad)
				RegisterToDatabaseChange();

		    firstLoad = false;

		    var databaseName = ApplicationModel.Current.Server.Value.SelectedDatabase.Value.Name;
			Settings.Sections.Clear();
			OnPropertyChanged(() => CurrentDatabase);
		    if (databaseName == Constants.SystemDatabase)
		    {
			    var apiKeys = new ApiKeysSectionModel();
			    Settings.Sections.Add(apiKeys);
			    Settings.SelectedSection.Value = apiKeys;
			    Settings.Sections.Add(new WindowsAuthSettingsSectionModel());

			    return;
		    }

		    var debug = await ApplicationModel.DatabaseCommands.CreateRequest("/debug/config".NoCache(), "GET").ReadResponseJsonAsync();
		    var bundles = ApplicationModel.CreateSerializer()
		                                  .Deserialize<List<string>>(
			                                  new RavenJTokenReader(debug.SelectToken("ActiveBundles")));
		    var addedVersioning = false;
		    if (ApplicationModel.Current.Server.Value.UserInfo.IsAdminGlobal)
		    {
			    var doc = await ApplicationModel.Current.Server.Value.DocumentStore
			                                    .AsyncDatabaseCommands
			                                    .ForSystemDatabase()
			                                    .CreateRequest("/admin/databases/" + databaseName, "GET")
			                                    .ReadResponseJsonAsync();

			    if (doc != null)
			    {
				    var databaseDocument =
					    ApplicationModel.CreateSerializer().Deserialize<DatabaseDocument>(new RavenJTokenReader(doc));
				    Settings.DatabaseDocument = databaseDocument;

				    var databaseSettingsSectionViewModel = new DatabaseSettingsSectionViewModel();
				    Settings.Sections.Add(databaseSettingsSectionViewModel);
				    Settings.SelectedSection.Value = databaseSettingsSectionViewModel;
				    Settings.Sections.Add(new PeriodicBackupSettingsSectionModel());

					//Bundles that need the database document
				    if (bundles.Contains("Quotas"))
					    Settings.Sections.Add(new QuotaSettingsSectionModel());

				    if (bundles.Contains("Versioning"))
				    {
					    AddModel(new VersioningSettingsSectionModel());
					    addedVersioning = true;
				    }

				    foreach (var settingsSectionModel in Settings.Sections)
				    {
					    settingsSectionModel.LoadFor(databaseDocument);
				    }
			    }
		    }

			//Bundles that don't need the database document
		    if (bundles.Contains("Replication"))
			    AddModel(new ReplicationSettingsSectionModel());

			 if (bundles.Contains("Versioning") && addedVersioning == false)
				 AddModel(new VersioningSettingsSectionModel());

		    if (bundles.Contains("SqlReplication"))
			    AddModel(new SqlReplicationSettingsSectionModel());

		    if (bundles.Contains("ScriptedIndexResults"))
			    AddModel(new ScriptedIndexSettingsSectionModel());

		    if (bundles.Contains("Authorization"))
		    {
			    var triggers = ApplicationModel.Current.Server.Value.SelectedDatabase.Value.Statistics.Value.Triggers;
			    if (triggers.Any(info => info.Name.Contains("Authorization")))
			    {
				    var authModel = new AuthorizationSettingsSectionModel();
				    Settings.Sections.Add(authModel);
					authModel.LoadFor(null);
			    }
		    }

		    if (Settings.Sections.Count == 0)
			    Settings.Sections.Add(new NoSettingsSectionModel());

			var url = new UrlParser(UrlUtil.Url);

			var id = url.GetQueryParam("id");
			if (string.IsNullOrWhiteSpace(id) == false)
			{
				switch (id)
				{
					case "scripted":
						if(Settings.Sections.Any(model => model is ScriptedIndexSettingsSectionModel))
							Settings.SelectedSection.Value = Settings.Sections.FirstOrDefault(model => model is ScriptedIndexSettingsSectionModel);
						break;
				}
			}
			else
				Settings.SelectedSection.Value = Settings.Sections[0];
	    }
Exemple #18
0
		public override void LoadModelParameters(string parameters)
		{
			var urlParser = new UrlParser(parameters);
			var name = urlParser.GetQueryParam("name");
			initialSelectedDatabaseName = name;
		}
		public override void LoadModelParameters(string parameters)
		{
			var url = new UrlParser(UrlUtil.Url);
			documentIdManager.Clear();

			if (url.GetQueryParam("mode") == "new")
			{
				Mode = DocumentMode.New;
				InitialiseDocument();
				Navigator = null;
				CurrentIndex = 0;
				TotalItems = 0;
				SetCurrentDocumentKey(null);
				ParentPathSegments.Clear();
				ParentPathSegments.Add(new PathSegment() { Name = "Documents", Url = "/documents" });
				return;
			}

			var database = url.GetQueryParam("databaseid");
			if(database != null)
			{
				EditDatabaseDocument(database);
				return;
			}

			Navigator = DocumentNavigator.FromUrl(url);

			Navigator.GetDocument().ContinueOnSuccessInTheUIThread(
				result =>
				{
					if (result.Document == null)
					{
						HandleDocumentNotFound();
						return;
					}

					if (string.IsNullOrEmpty(result.Document.Key))
					{
						Mode = DocumentMode.Projection;
						LocalId = Guid.NewGuid().ToString();
					}
					else
					{
						Mode = DocumentMode.DocumentWithId;
						result.Document.Key = Uri.UnescapeDataString(result.Document.Key);
						LocalId = result.Document.Key;
						SetCurrentDocumentKey(result.Document.Key);
					}

					urlForFirst = result.UrlForFirst;
					urlForPrevious = result.UrlForPrevious;
					urlForLast = result.UrlForLast;
					urlForNext = result.UrlForNext;

					IsLoaded = true;
					document.Value = result.Document;
					CurrentIndex = (int)result.Index;
					TotalItems = (int)result.TotalDocuments;

					ParentPathSegments.Clear();
					ParentPathSegments.AddRange(result.ParentPath);

					WhenParsingComplete(dataSection.Document)
						.ContinueOnUIThread(t => ApplyOutliningMode());

					HandleDocumentChanged();
				})
				.Catch(exception =>
				{
					var conflictExeption = exception.GetBaseException() as ConflictException;

					if (conflictExeption != null)
					{
						ApplicationModel.Current.Server.Value.SelectedDatabase.Value
							.AsyncDatabaseCommands
							.GetAsync(conflictExeption.ConflictedVersionIds, null)
							.ContinueOnSuccessInTheUIThread(doc =>
							{
								var docs = new List<RavenJObject>();
								var metadatas = new List<RavenJObject>();
								foreach (var result in doc.Results)
								{
									metadatas.Add(result.Value<RavenJObject>("@metadata"));
									result.Remove("@metadata");
									docs.Add(result);
								}

								ClearMetadatas(metadatas);

								var docsConflictsResolver = new ConflictsResolver(docs.ToArray());
								var metadataConflictsResolver = new ConflictsResolver(metadatas.ToArray());

								Key = url.GetQueryParam("id");
								DocumentKey = Key;
								OnPropertyChanged(() => DisplayId);
								Etag = conflictExeption.Etag;
	
								ResolvingConflict = true;

								dataSection.Document.DeleteText(TextChangeTypes.Custom, 0, dataSection.Document.CurrentSnapshot.Length);
								dataSection.Document.AppendText(TextChangeTypes.Custom, docsConflictsResolver.Resolve());

								metaDataSection.Document.DeleteText(TextChangeTypes.Custom, 0, metaDataSection.Document.CurrentSnapshot.Length);
								metaDataSection.Document.AppendText(TextChangeTypes.Custom, metadataConflictsResolver.Resolve());

								OnPropertyChanged(() => dataSection);
								OnPropertyChanged(() => document);
							});
						return true;
					}

					return false;
				});
		}
	    public override void LoadModelParameters(string parameters)
		{
			ApplicationModel.Current.Refresh();
			var urlParser = new UrlParser(parameters);
			var name = urlParser.GetQueryParam("collection");
			initialSelectedCollectionName = name;
            RefreshCollectionsList();
		}
Exemple #21
0
        public override void LoadModelParameters(string parameters)
        {
            var urlParser = new UrlParser(parameters);

            ClearCurrentQuery();

            if (urlParser.GetQueryParam("mode") == "dynamic")
            {
                var collection = urlParser.GetQueryParam("collection");

                IsDynamicQuery = true;
                DatabaseCommands.GetTermsAsync("Raven/DocumentsByEntityName", "Tag", "", 100)
                    .ContinueOnSuccessInTheUIThread(collections =>
                    {
                        DynamicOptions.Match(new[] { "AllDocs" }.Concat(collections).ToArray());

                        string selectedOption = null;
                        if (!string.IsNullOrEmpty(collection))
                            selectedOption = DynamicOptions.FirstOrDefault(s => s.Equals(collection));

                        if (selectedOption == null)
                            selectedOption = DynamicOptions[0];

                        DynamicSelectedOption = selectedOption;
                        DocumentsResult.SetChangesObservable(null);
                    });

                return;
            }

            IsDynamicQuery = false;
            IndexName = urlParser.Path.Trim('/');

            DatabaseCommands.GetIndexAsync(IndexName)
                .ContinueOnUIThread(task =>
                {
                    if (task.IsFaulted || task.Result == null)
                    {
                        IndexDefinitionModel.HandleIndexNotFound(IndexName);
                        return;
                    }
                    var fields = task.Result.Fields;
                    QueryIndexAutoComplete = new QueryIndexAutoComplete(fields, IndexName, QueryDocument);

                    const string spatialindexGenerateLegacy = "SpatialIndex.Generate";
					const string spatialindexGenerate = "SpatialGenerate";

                    IsSpatialQuerySupported =
						task.Result.Maps.Any(x => x.Contains(spatialindexGenerate) || x.Contains(spatialindexGenerateLegacy)) ||
						(task.Result.Reduce != null && (task.Result.Reduce.Contains(spatialindexGenerate) || task.Result.Reduce.Contains(spatialindexGenerateLegacy)));
                    HasTransform = !string.IsNullOrEmpty(task.Result.TransformResults);

                    DocumentsResult.SetChangesObservable(
                        d => d.IndexChanges
                                 .Where(n =>n.Name.Equals(indexName,StringComparison.InvariantCulture))
                                 .Select(m => Unit.Default));
		
                    SetSortByOptions(fields);
                    RestoreHistory();
                }).Catch();
        }
Exemple #22
0
        public override void LoadModelParameters(string parameters)
        {
            var urlParser = new UrlParser(parameters);

            UpdateAvailableIndexes();
            ClearCurrentQuery();

            if (urlParser.GetQueryParam("mode") == "dynamic")
            {
                var collection = urlParser.GetQueryParam("collection");

                IsDynamicQuery = true;
                DatabaseCommands.GetTermsAsync("Raven/DocumentsByEntityName", "Tag", "", 100)
                    .ContinueOnSuccessInTheUIThread(collections =>
                    {
                        DynamicOptions.Match(new[] { "AllDocs" }.Concat(collections).ToArray());

                        string selectedOption = null;
                        if (!string.IsNullOrEmpty(collection))
                            selectedOption = DynamicOptions.FirstOrDefault(s => s.Equals(collection));

                        if (selectedOption == null)
                            selectedOption = DynamicOptions[0];

                        DynamicSelectedOption = selectedOption;
                        DocumentsResult.SetChangesObservable(null);
                    });

                return;
            }

            IsDynamicQuery = false;
            var newIndexName = urlParser.Path.Trim('/');

            if (string.IsNullOrEmpty(newIndexName))
            {
                if (AvailableIndexes.Any())
                {
                    NavigateToIndexQuery(AvailableIndexes.FirstOrDefault());
                    return;
                }
            }

            IndexName = newIndexName;

	        if (Database.Value.Statistics.Value.Errors.Any(error => error.Index == IndexName))
	        {
		        QueryErrorMessage.Value = "The index " + IndexName + " has errors";
		        IsErrorVisible.Value = true;
	        }

	        DatabaseCommands.GetIndexAsync(IndexName)
                .ContinueOnUIThread(task =>
                {
                    if (task.IsFaulted || task.Result == null)
                    {
                        if (AvailableIndexes.Any())
                        {

                            NavigateToIndexQuery(AvailableIndexes.FirstOrDefault());
                        }
                        else
                        {
                            NavigateToIndexesList();
                        }
                        return;
                    }

                    var fields = task.Result.Fields;
                    QueryIndexAutoComplete = new QueryIndexAutoComplete(fields, IndexName, QueryDocument);

	                var regex1 = new Regex(@"(?:SpatialIndex\.Generate|SpatialGenerate)");
	                var regex2 = new Regex(@"(?:SpatialIndex\.Generate|SpatialGenerate)\(@?\""([^\""]+)\""");

	                var strs = task.Result.Maps.ToList();
					if (task.Result.Reduce != null)
						strs.Add(task.Result.Reduce);
					
					var legacyFields = new HashSet<string>();
					foreach (var map in task.Result.Maps)
					{
						var count = regex1.Matches(map).Count;
						var matches = regex2.Matches(map).Cast<Match>().Select(x => x.Groups[1].Value).ToList();
						if (matches.Count < count)
							legacyFields.Add(Constants.DefaultSpatialFieldName);

						matches.ForEach(x => legacyFields.Add(x));
					}

					var spatialFields = task.Result.SpatialIndexes
						.Select(x => new SpatialQueryField
						{
							Name = x.Key,
							IsGeographical = x.Value.Type == SpatialFieldType.Geography,
							Units = x.Value.Units
						})
						.ToList();

					legacyFields.ForEach(x => spatialFields.Add(new SpatialQueryField
						{
							Name = x,
							IsGeographical = true,
							Units = SpatialUnits.Kilometers
						}));

					UpdateSpatialFields(spatialFields);

                    HasTransform = !string.IsNullOrEmpty(task.Result.TransformResults);

                    DocumentsResult.SetChangesObservable(
                        d => d.IndexChanges
                                 .Where(n =>n.Name.Equals(indexName,StringComparison.InvariantCulture))
                                 .Select(m => Unit.Default));
		
                    SetSortByOptions(fields);
                    RestoreHistory();
                }).Catch();


        }
			private void SaveDocument()
			{
				RavenJObject doc;
				RavenJObject metadata;

				try
				{
					doc = RavenJObject.Parse(document.JsonData);
					metadata = RavenJObject.Parse(document.JsonMetadata);
					if (document.Key != null && Seperator != null && metadata.Value<string>(Constants.RavenEntityName) == null)
					{
						var entityName = document.Key.Split(new[] { Seperator }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();

						if (entityName != null && entityName.Length > 1)
						{
							metadata[Constants.RavenEntityName] = char.ToUpper(entityName[0]) + entityName.Substring(1);
						}
						else
						{
							metadata[Constants.RavenEntityName] = entityName;
						}
					}
				}
				catch (JsonReaderException ex)
				{
					ErrorPresenter.Show(ex.Message);
					return;
				}

				document.UpdateMetadata(metadata);
				ApplicationModel.Current.AddNotification(new Notification("Saving document " + document.Key + " ..."));
				var url = new UrlParser(UrlUtil.Url);
				var docId = url.GetQueryParam("id");
				Guid? etag = string.Equals(docId , document.Key, StringComparison.InvariantCultureIgnoreCase) ? 
					document.Etag : Guid.Empty;
			
				DatabaseCommands.PutAsync(document.Key, etag, doc, metadata)
					.ContinueOnSuccess(result =>
					{
						ApplicationModel.Current.AddNotification(new Notification("Document " + result.Key + " saved"));
						document.Etag = result.ETag;
						document.SetCurrentDocumentKey(result.Key, dontOpenNewTag: true);
					})
					.ContinueOnSuccess(() => new RefreshDocumentCommand(document).Execute(null))
					.Catch(exception => ApplicationModel.Current.AddNotification(new Notification(exception.Message)));
			}
        public static DocumentNavigator AllDocumentsFromUrl(UrlParser parser)
        {
            var id = parser.GetQueryParam("id");

            int itemIndex;
            int.TryParse(parser.GetQueryParam("itemIndex"), out itemIndex);

            return new AllDocumentsNavigator(id, itemIndex);
        }
		public override void LoadModelParameters(string parameters)
		{
			var url = new UrlParser(UrlUtil.Url);
			documentIdManager.Clear();

			if (url.GetQueryParam("mode") == "new")
			{
				Mode = DocumentMode.New;
				InitializeDocument();
				Navigator = null;
				CurrentIndex = 0;
				TotalItems = 0;
			    ResolvingConflict = false;
				SetCurrentDocumentKey(null);
				ParentPathSegments.Clear();
				ParentPathSegments.Add(new PathSegment { Name = "Documents", Url = "/documents" });
				return;
			}

			var database = url.GetQueryParam("databaseid");
			if (database != null)
			{
				EditDatabaseDocument(database);
				return;
			}

			Navigator = DocumentNavigator.FromUrl(url);

			Navigator.GetDocument().ContinueOnSuccessInTheUIThread(
				result =>
				{
				    if (result.IsConflicted)
				    {
                        ApplicationModel.Current.Server.Value.SelectedDatabase.Value
                                             .AsyncDatabaseCommands
                                             .GetAsync(result.ConflictingVersionIds.ToArray(), null)
                                             .ContinueOnSuccessInTheUIThread(loadResult =>
                                             {
                                                 var docs = new List<RavenJObject>();
                                                 var metadatas = new List<RavenJObject>();
                                                 foreach (var doc in loadResult.Results)
                                                 {
                                                     metadatas.Add(doc.Value<RavenJObject>("@metadata"));
                                                     doc.Remove("@metadata");
                                                     docs.Add(doc);
                                                 }

                                                 ClearMetadatas(metadatas);

                                                 var docsConflictsResolver = new ConflictsResolver(docs.ToArray());
                                                 var metadataConflictsResolver = new ConflictsResolver(metadatas.ToArray());

                                                 SetCurrentDocumentKey(result.ConflictDocumentId);

                                                 OnPropertyChanged(() => DisplayId);
                                                 Etag = result.ConflictEtag;

                                                 ResolvingConflict = true;

                                                 JsonData = docsConflictsResolver.Resolve();
                                                 JsonMetadata = metadataConflictsResolver.Resolve();

                                                 HasUnsavedChanges = false;

                                                 OnPropertyChanged(() => dataSection);
                                                 OnPropertyChanged(() => document);
                                             });
				    }
				    else
				    {
				        if (result.Document == null)
				        {
				            HandleDocumentNotFound();
				            return;
				        }

				        ResolvingConflict = false;

				        if (string.IsNullOrEmpty(result.Document.Key))
				        {
				            Mode = DocumentMode.Projection;
				            LocalId = Guid.NewGuid().ToString();
				        }
				        else
				        {
				            AssertNoPropertyBeyondSize(result.Document.DataAsJson, 500*1000);
				            var recentQueue = ApplicationModel.Current.Server.Value.SelectedDatabase.Value.RecentDocuments;
				            ApplicationModel.Current.Server.Value.RawUrl = "databases/" +
				                                                           ApplicationModel.Current.Server.Value.SelectedDatabase
				                                                                           .Value.Name +
				                                                           "/docs/" + result.Document.Key;
				            recentQueue.Add(result.Document.Key);
				            Mode = DocumentMode.DocumentWithId;
				            result.Document.Key = Uri.UnescapeDataString(result.Document.Key);
				            LocalId = result.Document.Key;
				            SetCurrentDocumentKey(result.Document.Key);
				            var expiration = result.Document.Metadata["Raven-Expiration-Date"];
				            if (expiration != null)
				            {
				                ExpireAt.Value = DateTime.Parse(expiration.ToString());
				                EnableExpiration.Value = true;
				                HasExpiration = true;
				            }
				            else
				            {
				                HasExpiration = false;
				            }
				        }

                        document.Value = result.Document;
                        
                        WhenParsingComplete(dataSection.Document)
                            .ContinueOnUIThread(t => ApplyOutliningMode());

                        HandleDocumentChanged();
				    }

				    urlForFirst = result.UrlForFirst;
					urlForPrevious = result.UrlForPrevious;
					urlForLast = result.UrlForLast;
					urlForNext = result.UrlForNext;

					CurrentIndex = (int) result.Index;
					TotalItems = (int) result.TotalDocuments;

					ParentPathSegments.Clear();
					ParentPathSegments.AddRange(result.ParentPath);

				})
			    .Catch();
		}
Exemple #26
0
		public void SetCurrentDatabase(UrlParser urlParser, bool firstTime = false)
		{
			var databaseName = urlParser.GetQueryParam("database");

			if (SelectedDatabase.Value != null
				&& (SelectedDatabase.Value.Name == databaseName || (SelectedDatabase.Value.Name == Constants.SystemDatabase && databaseName == null)))
				return;

			if (SelectedDatabase.Value != null)
				SelectedDatabase.Value.Dispose();

			SelectedDatabase.Value = databaseName == null
				? new DatabaseModel(Constants.SystemDatabase, documentStore) : new DatabaseModel(databaseName, documentStore);

			SelectedDatabase.Value.AsyncDatabaseCommands
				.EnsureSilverlightStartUpAsync()
				.ContinueOnSuccess(() =>
				{
					if (databaseName != null && databaseName != Constants.SystemDatabase)
						Settings.Instance.SelectedDatabase = databaseName;
				})
				.Catch(exception =>
				{
					var webException = exception.ExtractSingleInnerException() as WebException;
					if (webException == null)
						return false;

					var httpWebResponse = webException.Response as HttpWebResponse;

					if (httpWebResponse == null)
						return false;

					if (firstTime && 
						httpWebResponse.StatusCode == HttpStatusCode.Forbidden &&
						databaseName == null)
					{
						return true; // we won't show error in this case
					}

					if (httpWebResponse.StatusCode != HttpStatusCode.ServiceUnavailable)
						return false;

					
					ApplicationModel.Current.Notifications.Add(new Notification("Database " + databaseName + " does not exist.", NotificationLevel.Error, webException));

					return true;
				});
		}
Exemple #27
0
		public void SetCurrentDatabase(UrlParser urlParser)
		{
			var databaseName = urlParser.GetQueryParam("database");
			if (databaseName == null)
			{
				defaultDatabase = new[] {new DatabaseModel(DefaultDatabaseName, documentStore.AsyncDatabaseCommands)};
				Databases.Set(defaultDatabase);
				SelectedDatabase.Value = defaultDatabase[0];
				return;
			}
			if (SelectedDatabase.Value != null && SelectedDatabase.Value.Name == databaseName)
				return;
			var database = Databases.FirstOrDefault(x => x.Name == databaseName);
			if (database != null)
			{
				SelectedDatabase.Value = database;
				return;
			}
			singleTenant = urlParser.GetQueryParam("api-key") != null;
			var databaseCommands = databaseName.Equals("default", StringComparison.OrdinalIgnoreCase)
			                       	? documentStore.AsyncDatabaseCommands.ForDefaultDatabase()
			                       	: documentStore.AsyncDatabaseCommands.ForDatabase(databaseName);
			var databaseModel = new DatabaseModel(databaseName, databaseCommands);
			Databases.Add(databaseModel);
			SelectedDatabase.Value = databaseModel;
		}
Exemple #28
0
		public override void LoadModelParameters(string parameters)
		{
			var urlParser = new UrlParser(parameters);

			if (urlParser.GetQueryParam("mode") == "dynamic")
			{
				IsDynamicQuery = true;
				DatabaseCommands.GetTermsAsync("Raven/DocumentsByEntityName", "Tag", "", 100)
					.ContinueOnSuccess(collections => DynamicOptions.Match(new[] { "AllDocs" }.Concat(collections).ToArray()));
				return;
			}

			IndexName = urlParser.Path.Trim('/');

			DatabaseCommands.GetIndexAsync(IndexName)
				.ContinueOnSuccessInTheUIThread(definition =>
				{
					if (definition == null)
					{
						IndexDefinitionModel.HandleIndexNotFound(IndexName);
						return;
					}
					var fields = definition.Fields;
					QueryIndexAutoComplete = new QueryIndexAutoComplete(IndexName, Query, fields);
					
					const string spatialindexGenerate = "SpatialIndex.Generate";
					IsSpatialQuerySupported =
						definition.Maps.Any(x => x.Contains(spatialindexGenerate)) ||
						(definition.Reduce != null && definition.Reduce.Contains(spatialindexGenerate));

					SetSortByOptions(fields);
					Execute.Execute(string.Empty);
				}).Catch();
		}
Exemple #29
0
		public void RestoreHistory()
		{
		    var url = new UrlParser(UrlUtil.Url);
		    var recentQueryHashCode = url.GetQueryParam("recentQuery");

            if (PerDatabaseState.QueryHistoryManager.IsHistoryLoaded)
            {
                ApplyQueryState(recentQueryHashCode);
            }
            else
            {
                PerDatabaseState.QueryHistoryManager.WaitForHistoryAsync()
                    .ContinueOnUIThread(_ => ApplyQueryState(recentQueryHashCode));
            }	    
		}
		public void SetCurrentDatabase(UrlParser urlParser)
		{
			var databaseName = urlParser.GetQueryParam("database");
			if (databaseName == null)
				return;
			if (SelectedDatabase.Value != null && SelectedDatabase.Value.Name == databaseName)
				return;
			var database = Databases.FirstOrDefault(x => x.Name == databaseName);
			if (database != null)
			{
				SelectedDatabase.Value = database;
			}
			else
			{
				var databaseModel = new DatabaseModel(databaseName, documentStore.AsyncDatabaseCommands.ForDatabase(databaseName));
				Databases.Add(databaseModel);
				SelectedDatabase.Value = databaseModel;
			}
		}