azure cosmos DB is not creating container under database with no errors in xamarin.forms
i was following this tutorial here youtubetutorial github
my code below(took out the key for obvious reasons)
using Microsoft.Azure.Cosmos;
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace azurebasics {
public partial class App: Application {
public App() {
InitializeComponent();
MainPage = new MainPage();
CreateItem().Wait();
}
private static async Task CreateItem() {
var cosmosUrl = "";
var cosmoskey = "";
var databaseName = "DemoDB";
CosmosClient client = new CosmosClient(cosmosUrl, cosmoskey);
Database database = await client.CreateDatabaseIfNotExistsAsync(databaseName);
Container container = await database.CreateContainerIfNotExistsAsync(
"MyContainerName", "/partitionKeyPath", 400);
dynamic testItem = new {
id = Guid.NewGuid().ToString(), partitionKeyPath = "MyTestPkValue", details = "it's working"
};
var response = await container.CreateItemAsync(testItem);
}
protected override void OnStart() {}
protected override void OnSleep() {}
protected override void OnResume() {}
}
}
so I would run this code and it would create the database with no container as shown here I'm confused because the connection works if it makes the database. and the only weird thing I found between the github and his tutorial is in the video he has
var response = await container.CreateItemAsync(testItem);
and the github has
ItemResponse<dynamic> response = await container.CreateItemAsync(testItem);
See also questions close to this topic
-
403 forbidden when posting to a url
I am posting a request to a website:
request = (HttpWebRequest)WebRequest.Create("https://www.footlocker.dk/api/users/carts/current/entries?timestamp=1611595223668"); request.Method = "POST"; using (var streamWriter = new StreamWriter(request.GetRequestStream())) { string json = "{\"user\":\"test\"," + "\"password\":\"bla\"}"; streamWriter.Write(json); } var httpResponse = (HttpWebResponse)request.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); }
When I submit this request, I am getting a 403 forbidden, with following html:
<html> <head> <title>footlocker.dk</title> <style> #cmsg{animation: A 1.5s;}@keyframes A{0%{opacity:0;}99%{opacity:0;}100%{opacity:1;}} </style> </head> <body style="margin:0"> <p id="cmsg">Please enable JS and disable any ad blocker</p> <script> var dd={'cid':'AHrlqAAAAAMA2k9UvgFgVkIAk04eSQ==','hsh':'A55FBF4311ED6F1BF9911EB71931D5','t':'fe','r':'b','s':17434,'host':'geo.captcha-delivery.com'}</script><script src="https://ct.captcha-delivery.com/c.js"> </script> </body> </html>
Are there anyway I can make the browser think that JS is enabled?
-
El programa no contiene un método 'Principal' estático adecuado para un punto de entrada
Estoy haciendo una prueba para ver como me imprime el valor de precio y obtengo el siguiente error
Error CS5001 Program does not contain a static 'Main' method suitable for an entry point
En mi clase Program.cs tengo el siguiente código
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Globalization; namespace N_D { class Program : Test { public void Main(string[] args) { var price = 1450.00; precio = Convert.ToDecimal(price.ToString("N", new CultureInfo("es-VE"))); Console.WriteLine("VALOR: " + precio); Console.Read(); } } }
Tengo otra clase llamada Test.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace N_D { public class Test { public Test() { precio = 0; } public decimal precio; } }
Cuando voy a compilar mi proyecto para posteriormente ejecutarlo me da el error que les indique arriba
Error CS5001 Program does not contain a static 'Main' method suitable for an entry point N_D
-
Returning references from Generic Arrays
I've got a class which holds a list of
ComponentBase
.Component
sub classesComponentBase
.public abstract class ComponentBase { public Type Type; public dynamic Value; public uint EntityID; } public class Component<T> : ComponentBase { public new Type Type; public new T Value; public new uint EntityID; }
I need a way to retrieve a
ref
to aComponent<T>.Value
in theGetComponentOnEntity
method and I can't seem to find it. Im not very good at generics so I'll put this question to the pros.public class ComponentDatabase { ComponentBase[] components; private int componentIndex; public T AddComponentToEntity<T>(T component, Entity entity) where T : new() { var x = component != null ? component : new T(); var comp = new Component<T> { EntityID = entity.Id, Type = typeof(T), Value = x }; components[componentIndex++] = comp; return x; } public ref T GetComponentOnEntity<T>(Entity entity) where T : new() { return ref components.Where(x => x.EntityID == entity.Id && x.Type == typeof(T)).First().Value; } }
Ive had a long night and I feel like there is a simple solution but I really can't find it. Any help would be greatly appreciated.
-
Cannot connect to SQL Database: 'westlakeserver', Database: 'westlake_schoolDB', User: 'westlake'
Check the linked service configuration is correct, and make sure the SQL Database firewall allows the integration runtime to access. A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server), SqlErrorNumber=53,Class=20,State=0, The network path was not found Activity ID: 101fe7a0-b348-4342-9e2b-cd2c3af3f525.
This issue was shown when i was working with data factory when creating a new connection. What might be the issue. database name, server name and username password are correct. I'm new to azure
-
Set legal hold on Azure storage account container with ARM template
How to set legal hold on Azure storage account container in ARM template?
When setting immutable blob storage policy Azure portal allows you to choose from legal hold and Time-base retention. According to doc arm template supports immutable blob storage. However only requests with immutabilityPeriodSinceCreationInDays are accepted. When trying without setting it, I am getting:
Missing at least one of the following properties 'immutabilityPeriodSinceCreationInDays,allowProtectedAppendWrites'
Or:
immutabilityPeriodSinceCreationInDays must be set before setting allowProtectedAppendWrites
Weirdest - without properties block in immutabilityPolicies (as below) request fails with InternalServerError:
{ "status": "Failed", "error": { "code": "UnexpectedException", "message": "The server was unable to complete your request." } }
{ "name": "testsa/default/testcontainer/default", "type": "Microsoft.Storage/storageAccounts/blobServices/containers/immutabilityPolicies", "apiVersion": "2019-06-01" // , // "properties": { // // "immutabilityPeriodSinceCreationInDays" : 10, // // "allowProtectedAppendWrites": false // } }
-
Azure blobfuse on Centos7
I tried to Attach Azure Blob Storage to CentOS 7? for this i have installed blobfuse, created Temporary Path, config file and directory for mount the drive. But when i run: sudo blobfuse /home/aleksey/projects/datagenerator/mycontainer --tmp_path=/mnt/resource/blobfusetmp --config_file=/home/aleksey/fuse_connection.cfg --container-name=containerName i still get error: No config file was specified and AZURE_STORAGE_ACCOUNT environment variable is empty. I checked all paths and credentials, they are all correct.
-
Application that uninstalls itself Xamarin.Forms C#
I wanted to create an application with a button to uninstall it or completely remove it from my mobile. I looked at many topics but nothing works with Xamarin.Forms, I wanted to know if anyone will have a solution thank you :)
we cannot do StartActivities with Xamarin.Forms
Do you have any suggestions? or it is not possible to delete files with xamarin.forms?
-
Objects in Binding not displayed in the ListView
I have a ListView with items in Binding via the ItemsSource property. I cannot understand why the DataTemplate data is not displayed. They are still downloaded correctly from the internet but are not displayed. I've tried both inserting the ItemsSource property from c # and xaml, but the result doesn't change
xaml
<yummy:PancakeView x:Name="ViewFrasi" IsVisible="False" Grid.Row="1" CornerRadius="30,30,0,0" BackgroundColor="White" VerticalOptions="FillAndExpand"> <yummy:PancakeView.Border> <yummy:Border Color="Blue" Thickness="4"/> </yummy:PancakeView.Border> <Grid Margin="15"> <ListView x:Name="Frasi" ItemsSource="{Binding FrasiJsonOnline1}"> <ListView.Header> <Grid> <Grid.RowDefinitions> <RowDefinition Height="40"/> </Grid.RowDefinitions> <BoxView CornerRadius="100" Grid.Row="0" HorizontalOptions="End" WidthRequest="40"> <BoxView.Background> <LinearGradientBrush StartPoint="1,0" EndPoint="1,1"> <GradientStop Color="Blue" Offset="0" /> <GradientStop Color="LightBlue" Offset="1.0" /> </LinearGradientBrush> </BoxView.Background> </BoxView> <Image Source="checked.png" Grid.Row="0" HorizontalOptions="End" HeightRequest="20" Margin="0,0,10,0"/> <Button x:Name="BtSave" IsVisible="False" Clicked="BtSave_Clicked" BackgroundColor="Transparent" Grid.Row="0" HorizontalOptions="End" HeightRequest="25"/> <ImageButton Source="close.png" Grid.Row="0" HorizontalOptions="Start" HeightRequest="20" Margin="5,0,0,0" Clicked="Close_Clicked" BackgroundColor="Transparent"/> </Grid> </ListView.Header> <ListView.ItemTemplate> <DataTemplate> <Grid> <ScrollView> <Grid> <Grid.RowDefinitions> <RowDefinition Height="50"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*"/> <ColumnDefinition Width="5*"/> </Grid.ColumnDefinitions> <ImageButton Grid.Row="0" Grid.Column="0" Source="IconCopy.png" Clicked="CopyClipboard_Clicked"/> <Label Grid.Row="0" Grid.Column="1" Text="Test" TextColor="Black" FontSize="15"/> </Grid> </ScrollView> </Grid> </DataTemplate> </ListView.ItemTemplate> </ListView> </Grid> </yummy:PancakeView>
c#
private async void CategoryView_SelectionChanged(object sender, SelectionChangedEventArgs e) { var selected = e.CurrentSelection; ClassCategory model = e.CurrentSelection.FirstOrDefault() as ClassCategory; WebClient clientw = new WebClient(); clientw.Credentials = new NetworkCredential("xxxxxxx", "xxxxxx"); string Frasi1 = "ftp://epiz_27426656@ftpupload.net/htdocs/" + model.Titolo + ".json"; string contents1 = await clientw.DownloadStringTaskAsync(Frasi1); ObservableCollection<FraseClass> FrasiJsonOnline1 = JsonConvert.DeserializeObject<ObservableCollection<FraseClass>>(contents1); ViewFrasi.IsVisible = true; ViewFrasi.TranslationY = 600; ViewFrasi.TranslateTo(0, 0, 500, Easing.SinInOut); }
-
Xamarin forms WebAuthenticator usage
I'm trying to implement Facebook Auth for Xamarin Forms App. I'm doing everything like in this tutorial https://docs.microsoft.com/en-us/xamarin/essentials/web-authenticator?tabs=android so I'm using server side auth. Here is my mobile app code:
public class WebAuthViewModel:ObservableObject { private const string AuthenticationUrl = "https://myapp.com/mobileauth/"; private string _accessToken = ""; private bool _isAuthenticated = false; public string AuthToken { get => _accessToken; set => SetProperty(ref _accessToken, value); } public ICommand FacebookCommand { get; } public WebAuthViewModel() { FacebookCommand = new Command(async()=>await OnAuthenticate("Facebook")); } async Task OnAuthenticate(string scheme) { try { WebAuthenticatorResult result = null; var authUrl = new Uri(AuthenticationUrl + scheme); var callbackUrl = new Uri("myapp://"); result = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl); AuthToken = string.Empty; if (result.Properties.TryGetValue("name", out var name) && !string.IsNullOrEmpty(name)) { AuthToken += $"Name: {name}{Environment.NewLine}"; } if (result.Properties.TryGetValue("email", out var email) && !string.IsNullOrEmpty(email)) { AuthToken += $"Email: {email}{Environment.NewLine}"; } AuthToken += result?.AccessToken ?? result?.IdToken; IsAuthenticated = true; } catch (Exception ex) { AuthToken = string.Empty; } } }
Also I have some back-end code. All this works fine, I'm getting access token, UserId and so on. But I still have some questions.
What is the right way to validate if login is still valid? How should I authorize app actions? And how could I implement Logout?
I will be grateful for advices or links.
-
Faster Query to fetch details from Cosmos DB
I am fetching the list of persons from Cosmos DB using a LINQ expression mentioned below from an array(
String[] getPersons
) as input.var container = db.GetContainer(containerId); var q = container.GetItemLinqQueryable<Person>(); var iterator = q.Where(p => getPersons.Contains(p.Name)).ToFeedIterator(); var results = await iterator.ReadNextAsync();
I could able to get result but it is taking more time(>15 sec) to retrieve data(more than 1K records) from CosmosDB. I need to get the data with in < 1 sec. Is there any way to optimise the above query to achieve this?
-
Cosmos DB Has An Integer Stored In A Document But .NET 3.1 Throws a Serialization Error Trying To Parse A Decimal
My document has a field:
"distanceInMetres": 17088,
My ASP.NETCORE API is returning a 400 bad request. On debugging the exception I see this error:
Input string '17088.0' is not a valid integer. Path '[0].distanceInMetres', line 1, position 2474.
The property "distanceInMetres is stored as an integer so why the error?
-
Why does this CosmosDB SubQuery fail?
I am trying to use a simple subquery to get a value but I get an error about cardinality
Query as follows:
SELECT va.variantId AS ItemNo, c.Season, SUBSTRING(va.variantId, 0, 7) AS ProductNo, SUBSTRING(va.variantId, 0, 10) AS ArticleNo, SUBSTRING(va.variantId, 0, 13) AS VariantNo, ( SELECT VALUE p["value"] FROM c JOIN p IN c.OriginalData.presentation.productNameLong WHERE c.ItemNo = '123456' AND p.locale = 'en-GB' AND c.Season = '201808' AND c.brand = 'xxx' ) AS Title FROM c JOIN sm IN c.OriginalData.base.sales.summary.salesMarkets JOIN ar IN sm.articles JOIN va IN ar.variants JOIN ch IN va.channels WHERE c.ItemNo = '123456' AND sm.salesMarket = 'SE' AND ch.channelName = 'xxx'
The error is as follows:
Failed to query item for container rawdata: Gateway Failed to Retrieve Query Plan: Message: {"errors":[{"severity":"Error","location":{"start":227,"end":498},"code":"SC2201","message":"The cardinality of a scalar subquery result set cannot be greater than one."}]} ActivityId: 11ff3b08-d8a7-4737-9111-81f319cf1dc5, Microsoft.Azure.Documents.Common/2.11.0, Microsoft.Azure.Documents.Common/2.11.0
The result of that subquery can only ever be 1 single result so I am not sure what it is complaining about