Snippets Collections
Microsoft.AspNetCore.Identity.EntityFrameworkCore  6.0.23
Microsoft.AspNetCore.Identity.UI  6.0.23
Microsoft.EntityFrameworkCore 7.0.9
Microsoft.EntityFrameworkCore.Sqlite 7.0.9
Microsoft.EntityFrameworkCore.SqlServer 7.0.9
Microsoft.EntityFrameworkCore.Tools 7.0.9
Microsoft.VisualStudio.Web.CodeGeneration.Design 6.0.16
dotnet swagger tofile --output .\wwwroot\swagger\v1.0\swagger.json .\bin\Debug\net6.0\[PROJECT NAME].dll [API VERSION]
import { Injectable } from '@angular/core';
import { Observable, map, of} from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { RegisterUser } from '../shared/register-user';
import { LoginUser } from '../shared/login-user';
import { User } from '../shared/user';
import { Product } from '../shared/product';

@Injectable({
  providedIn: 'root'
})

export class APIService {

apiUrl = 'http://localhost:5240/api/'

httpOptions ={
  headers: new HttpHeaders({
    ContentType: 'application/json'
  })
}
  constructor(private httpClient: HttpClient) {
  }

  RegisterUser(registerUser: RegisterUser){
    return this.httpClient.post(`${this.apiUrl}Authentication/Register`, registerUser, this.httpOptions)
  }

  getProducts() {
    return this.httpClient.get(`${this.apiUrl}Store/ProductListing`)
    .pipe(map(result => result))
  }

  LoginUser(loginUser: LoginUser){
    return this.httpClient.post<User>(`${this.apiUrl}Authentication/Login`, loginUser, this.httpOptions)
  }

  addProduct(file:FormData){
    
    return this.httpClient.post(`${this.apiUrl}Store/AddProduct`, file)
  }

  getBrands(): Observable<any>
  {
    return this.httpClient.get(`${this.apiUrl}Store/Brands`)
    .pipe(map(result => result))
  }

  getProductTypes(): Observable<any>
  {
    return this.httpClient.get(`${this.apiUrl}Store/ProductTypes`)
    .pipe(map(result => result))
  }
}
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { APIService } from '../services/api.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {

  registerFormGroup: FormGroup = this.fb.group({
    emailaddress: ['', [Validators.required, Validators.email]],
    password: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(16)]],
  })

  constructor(private router: Router, private apiService: APIService, private fb: FormBuilder, private snackBar: MatSnackBar) { 

    
  }

  ngOnInit(): void {
  }

  RegisterUser(){

    if(this.registerFormGroup.valid)
    {
        this.apiService.RegisterUser(this.registerFormGroup.value).subscribe(() => {
        this.registerFormGroup.reset();
        this.router.navigate(['']).then((navigated: boolean) => {
          if(navigated) {
            this.snackBar.open(`Registered successfully`, 'X', {duration: 5000});
          }
       });
      })
    }

    // if(this.registerFormGroup.valid)
    // {
    //   this.apiService.RegisterUser(this.registerFormGroup.value).subscribe(() => {
    //     this.registerFormGroup.reset();
    //     this.router.navigate(['']).then((navigated: boolean) => {
    //       if(navigated) {
    //         this.snackBar.open(`Registered successfully`, 'X', {duration: 5000});
    //       }
    //    });
    //   }, (response: HttpErrorResponse) => {
    //     if (response.status === 403) {
    //       this.snackBar.open(response.error, 'X', {duration: 5000});
    //     }
    //     if (response.status === 500){
    //       this.snackBar.open(response.error, 'X', {duration: 5000});
    //     }
    //   })
    // }
  }

}
<div class="login-wrapper" fxLayout="row" fxLayoutAlign="center center">
    <mat-card class="box">
      <mat-card-header>
        <mat-card-title>Register</mat-card-title>
      </mat-card-header>
      <form class="form" [formGroup]="registerFormGroup">
        <mat-card-content>
          <mat-form-field class="full-width">
            <mat-label>Email Address</mat-label>
            <input matInput placeholder="Enter a valid Email address" formControlName="emailaddress">
          </mat-form-field>
          <mat-form-field class="full-width">
              <mat-label>Password</mat-label>
            <input type="password" matInput placeholder="Enter between 6 to 16 characters" formControlName="password">
          </mat-form-field>
        </mat-card-content>
        <button mat-stroked-button color="primary" class="btn-block" (click)="RegisterUser()">Register</button>
      </form>
    </mat-card>
  </div>
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { APIService } from '../services/api.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatSnackBar } from '@angular/material/snack-bar';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  loginFormGroup: FormGroup = this.fb.group({
    emailaddress: ['', [Validators.required, Validators.email]],
    password: ['', Validators.required],
  })

  isLoading:boolean = false

  constructor(private router: Router, private apiService: APIService, private fb: FormBuilder, private snackBar: MatSnackBar) { }

  ngOnInit(): void {
  }

  async LoginUser(){
    if(this.loginFormGroup.valid)
    {
      this.isLoading = true

      await this.apiService.LoginUser(this.loginFormGroup.value).subscribe(result => {
        localStorage.setItem('User', JSON.stringify(result))
        this.loginFormGroup.reset();
        this.router.navigateByUrl('productListing');
      })
    }
  }

}
<div class="login-wrapper" fxLayout="row" fxLayoutAlign="center center">
    <mat-card class="box" *ngIf="!isLoading">
      <mat-card-header>
        <mat-card-title>Log in</mat-card-title>
      </mat-card-header>
      <form class="form" [formGroup]="loginFormGroup">
        <mat-card-content>
          <mat-form-field class="full-width">
            <mat-label>Username</mat-label>
            <input matInput placeholder="Enter the User's Email address" formControlName="emailaddress">
          </mat-form-field>
          <mat-form-field class="full-width">
            <mat-label>Password</mat-label>
            <input matInput type="password" placeholder="Enter the User's Password" formControlName="password">
          </mat-form-field>
        </mat-card-content>
        <button mat-stroked-button color="primary" class="btn-block" (click)="LoginUser()">Log in</button>
        <div>Don't have an account? Register <a [routerLink]="['../register']">here</a></div>
      </form>
    </mat-card>
    <mat-progress-spinner mode="indeterminate" value="50" *ngIf="isLoading">
    </mat-progress-spinner>
  </div>
<div class="login-wrapper" fxLayout="row" fxLayoutAlign="center center">
    <mat-card class="box" *ngIf="!isLoading">
      <mat-card-header>
        <mat-card-title>Log in</mat-card-title>
      </mat-card-header>
      <form class="form" [formGroup]="loginFormGroup">
        <mat-card-content>
          <mat-form-field class="full-width">
            <mat-label>Username</mat-label>
            <input matInput placeholder="Enter the User's Email address" formControlName="emailaddress">
          </mat-form-field>
          <mat-form-field class="full-width">
            <mat-label>Password</mat-label>
            <input matInput type="password" placeholder="Enter the User's Password" formControlName="password">
          </mat-form-field>
        </mat-card-content>
        <button mat-stroked-button color="primary" class="btn-block" (click)="LoginUser()">Log in</button>
        <div>Don't have an account? Register <a [routerLink]="['../register']">here</a></div>
      </form>
    </mat-card>
    <mat-progress-spinner mode="indeterminate" value="50" *ngIf="isLoading">
    </mat-progress-spinner>
  </div>
using Assignment3_Backend.Factory;
using Assignment3_Backend.Models;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.


builder.Services.AddCors(options => options.AddDefaultPolicy(
    include =>
    {
        include.AllowAnyHeader();
        include.AllowAnyMethod();
        include.AllowAnyOrigin();
    }));

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddIdentity<AppUser, IdentityRole>(options =>
{
    options.Password.RequireUppercase = false;
    options.Password.RequireLowercase = false;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequireDigit = true;
    options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();

builder.Services.AddAuthentication()
                .AddCookie()
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidIssuer = builder.Configuration["Tokens:Issuer"],
                        ValidAudience = builder.Configuration["Tokens:Audience"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Tokens:Key"]))
                    };
                });

builder.Services.Configure<FormOptions>(o =>
{
    o.ValueLengthLimit = int.MaxValue;
    o.MultipartBodyLengthLimit = int.MaxValue;
    o.MemoryBufferThreshold = int.MaxValue;
});

builder.Services.AddScoped<IUserClaimsPrincipalFactory<AppUser>, AppUserClaimsPrincipalFactory>();

builder.Services.Configure<DataProtectionTokenProviderOptions>(options => options.TokenLifespan = TimeSpan.FromHours(3));

builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IRepository, Repository>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors();
app.UseAuthorization();
app.UseAuthentication();



app.MapControllers();

app.Run();

using Microsoft.EntityFrameworkCore;

namespace Assignment3_Backend.Models
{
    public class Repository:IRepository
    {
        private readonly AppDbContext _appDbContext;

        public Repository(AppDbContext appDbContext)
        {
            _appDbContext = appDbContext;
        }

        public void Add<T>(T entity) where T : class
        {
            _appDbContext.Add(entity);
        }
        public async Task<bool> SaveChangesAsync()
        {
            return await _appDbContext.SaveChangesAsync() > 0;
        }

        public async Task<Product[]> GetProductsAsync()
        {
            IQueryable<Product> query = _appDbContext.Products.Include(p => p.Brand).Include(p => p.ProductType);

            return await query.ToArrayAsync();
        }

        public async Task<Brand[]> GetBrandsAsync()
        {
            IQueryable<Brand> query = _appDbContext.Brands;

            return await query.ToArrayAsync();
        }

        public async Task<ProductType[]> GetProductTypesAsync()
        {
            IQueryable<ProductType> query = _appDbContext.ProductTypes;

            return await query.ToArrayAsync();
        }
    }
}
namespace Assignment3_Backend.Models
{
    public interface IRepository
    {
        Task<bool> SaveChangesAsync();
        Task<Product[]> GetProductsAsync();
        Task<ProductType[]> GetProductTypesAsync();
        Task<Brand[]> GetBrandsAsync();

        void Add<T>(T entity) where T : class;
    }
}
using Assignment3_Backend.Models;
using Assignment3_Backend.ViewModels;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Assignment3_Backend.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase
{
private readonly UserManager<AppUser> _userManager;
    private readonly IUserClaimsPrincipalFactory<AppUser> _claimsPrincipalFactory;
        private readonly IRepository _repository;
        private readonly IConfiguration _configuration;

        public AuthenticationController(UserManager<AppUser> userManager, IUserClaimsPrincipalFactory<AppUser> claimsPrincipalFactory, IRepository repository, IConfiguration configuration)
                {
                _repository = repository;
                _userManager = userManager;
                _claimsPrincipalFactory = claimsPrincipalFactory;
                _configuration = configuration;
                }

                [HttpPost]
                [Route("Register")]
                public async Task<IActionResult> Register(UserViewModel uvm)
                    {
                    var user = await _userManager.FindByIdAsync(uvm.emailaddress);

                    if (user == null)
                    {
                    user = new AppUser
                    {
                    Id = Guid.NewGuid().ToString(),
                    UserName = uvm.emailaddress,
                    Email = uvm.emailaddress
                    };

                    var result = await _userManager.CreateAsync(user, uvm.password);

                    if (result.Errors.Count() > 0) return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
                    }
                    else
                    {
                    return Forbid("Account already exists.");
                    }

                    return Ok();
                    }

                    [HttpPost]
                    [Route("Login")]
                    public async Task<ActionResult> Login(UserViewModel uvm)
                        {
                        var user = await _userManager.FindByNameAsync(uvm.emailaddress);

                        if (user != null && await _userManager.CheckPasswordAsync(user, uvm.password))
                        {
                        try
                        {
                        var principal = await _claimsPrincipalFactory.CreateAsync(user);
                        return GenerateJWTToken(user);
                        }
                        catch (Exception)
                        {
                        return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
                        }
                        }
                        else
                        {
                        return NotFound("Does not exist");
                        }
                        }

                        [HttpGet]
                        private ActionResult GenerateJWTToken(AppUser user)
                        {
                        // Create JWT Token
                        var claims = new[]
                        {
                        new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                        new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
                        };

                        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"]));
                        var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                        var token = new JwtSecurityToken(
                        _configuration["Tokens:Issuer"],
                        _configuration["Tokens:Audience"],
                        claims,
                        signingCredentials: credentials,
                        expires: DateTime.UtcNow.AddHours(3)
                        );

                        return Created("", new
                        {
                        token = new JwtSecurityTokenHandler().WriteToken(token),
                        user = user.UserName
                        });
                        }

                        }
                        }
<input type="button" value="Some text" onclick="@("window.location.href='" + @Url.Action("actionName", "controllerName") + "'");" />
<?xml version="1.0" encoding="UTF-8" ?>
<resources xmlns:tools="http://schemas.android.com/tools">
  <dimen name="design_bottom_navigation_text_size" tools:override="true">14sp</dimen>
  <dimen name="design_bottom_navigation_active_text_size" tools:override="true">14sp</dimen>
  <dimen name="design_bottom_navigation_icon_size">20dp</dimen>
  <dimen name="design_bottom_navigation_height">60dp</dimen>
</resources>
using System;
using MMEA.MessageCenter.Events;
using Xamarin.Essentials;

namespace MMEA.MessageCenter
{
    /// <summary>
    ///     Wrapper used to communicate with classes through the Xamarin.MessagingCenter
    /// </summary>
    /// <remarks>
    ///     Made for easier debugging
    /// </remarks>
    public interface IApplicationMessageCenter
    {
        /// <summary>
        ///     Listen to messages send through the Messaging Center
        /// </summary>
        /// <param name="subscribableMessage"></param>
        /// <param name="callback"></param>
        /// <typeparam name="T">Type of the content that is within the message</typeparam>
        void Subscribe<T>(SubscribableMessage<T> subscribableMessage, Action<IApplicationMessageCenter, T> callback);

        /// <summary>
        ///     Send a message to the MessagingCenter
        /// </summary>
        /// <param name="message"></param>
        /// <typeparam name="T">Type of the content send</typeparam>
        void Send<T>(SubscribableMessage<T> message);
    }
  
    /// <inheritdoc />
    public class ApplicationMessageCenter : IApplicationMessageCenter
    {
        private readonly IMessagingCenter _messageCenter;

        /// <summary>
        ///     Default constructor
        /// </summary>
        /// <param name="messagingCenter"></param>
        public ApplicationMessageCenter(IMessagingCenter messagingCenter)
        {
            _messageCenter = messagingCenter;
        }

        /// <inheritdoc />
        public void Subscribe<T>(SubscribableMessage<T> subscribableMessage,
            Action<IApplicationMessageCenter, T> callback)
        {
            _messageCenter.Subscribe(this, subscribableMessage.MessageName, callback);
        }

        /// <inheritdoc />
        public void Send<T>(SubscribableMessage<T> message)
        {
            _messageCenter.Send<IApplicationMessageCenter, T>(this, message.MessageName, message.Content);
        }
    }

    public static class Messages
    {
        public static SubscribableMessage<ConnectivityChangedEventArgs> ConnectivityChanged(
            ConnectivityChangedEventArgs eventArgs = null)
        {
            return new SubscribableMessage<ConnectivityChangedEventArgs>
            {
                MessageName = "ConnectivityChanged",
                Content = eventArgs
            };
        }

        public static SubscribableMessage<float?> ButtonOpacityChange(float? opacity)
        {
            return new SubscribableMessage<float?>
            {
                MessageName = "ButtonOpacityChange",
                Content = opacity
            };
        }

        public static SubscribableMessage<object> MonitorActivation()
        {
            return new SubscribableMessage<object>
            {
                MessageName = "MonitorActivation",
                Content = null
            };
        }

        public static SubscribableMessage<LoadMessageCarouselEvent> OpenMessageCarousel(
            LoadMessageCarouselEvent carouselEvent = null)
        {
            return new SubscribableMessage<LoadMessageCarouselEvent>
            {
                MessageName = "OpenMessageCarousel",
                Content = carouselEvent
            };
        }

        public static SubscribableMessage<int?> NotificationOpened(int? remoteMessageId = null)
        {
            return new SubscribableMessage<int?>
            {
                MessageName = "NotificationOpened",
                Content = remoteMessageId
            };
        }

        public static SubscribableMessage<object> DeviceActivated()
        {
            return new SubscribableMessage<object>
            {
                MessageName = "DeviceActivated",
                Content = null
            };
        }

        public static SubscribableMessage<Guid?> MessageViewed(Guid? messageId = null)
        {
            return new SubscribableMessage<Guid?>
            {
                MessageName = "MessageViewed",
                Content = messageId
            };
        }

        public static SubscribableMessage<LikedMessageEvent> MessageLiked(LikedMessageEvent linkedMessageEvent = null)
        {
            return new SubscribableMessage<LikedMessageEvent>
            {
                MessageName = "MessageLiked",
                Content = linkedMessageEvent
            };
        }

        public static SubscribableMessage<object> RefreshTranslationLabels()
        {
            return new SubscribableMessage<object>
            {
                MessageName = "RefreshTranslationLabels",
                Content = null
            };
        }

        public static SubscribableMessage<string> SearchExecuted(string content = null)
        {
            return new SubscribableMessage<string>
            {
                MessageName = "SearchExecuted",
                Content = content
            };
        }

        public static SubscribableMessage<bool> ChangeOrientationAllowance(bool allowed = false)
        {
            return new SubscribableMessage<bool>
            {
                MessageName = "ChangeOrientationAllowance",
                Content = allowed
            };
        }

        public static SubscribableMessage<bool> SyncLocalMessages(bool forceRefresh = false)
        {
            return new SubscribableMessage<bool>
            {
                MessageName = "SyncLocalMessages",
                Content = forceRefresh
            };
        }

        public static SubscribableMessage<bool> LocalMessagesSynced(bool forceRefresh = false)
        {
            return new SubscribableMessage<bool>
            {
                MessageName = "LocalMessagesSynced",
                Content = forceRefresh
            };
        }

        public static SubscribableMessage<int?> AddMessage(int? messageId = null)
        {
            return new SubscribableMessage<int?>
            {
                MessageName = "AddMessage",
                Content = messageId
            };
        }
    }

    public class SubscribableMessage<T>
    {
        public string MessageName { get; set; }

        public T Content { get; set; }
    }
}
using System;
using System.Globalization;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace MMEA.Converters
{
    /// <summary>
    ///     Converter to inverse the boolean value for views
    /// </summary>
    public class InverseBoolConverter : IValueConverter, IMarkupExtension
    {
        /// <inheritdoc />
        public object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }

        /// <inheritdoc />
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return !(bool) value;
        }

        /// <inheritdoc />
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return !(bool) value;
        }
    }
}
using System;
using System.Globalization;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace MMEA.Converters
{
    /// <summary>
    ///     Converter to change bool to a opacity
    /// </summary>
    public class BoolToOpacityConverter : IValueConverter, IMarkupExtension
    {
        /// <inheritdoc />
        public object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }

        /// <inheritdoc />
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var hasRead = (bool) value;
            if (hasRead)
                return 0.4;
            return 1;
        }

        /// <inheritdoc />
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Generic.Agents
{
    /// <summary>
    ///     Base http caller
    /// </summary>
    public class BaseHttpAgent
    {
        /// <summary>
        ///     Sends a get request with the latest token found in the local database
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="token"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        protected static async Task<T> GetWithAuthAsync<T>(string uri, string token)
        {
            var clientHandler = new HttpClientHandler();


#if DEBUG //  When we connect to localhost with https this workaround is used for ignoring certificate problems
            clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
            {
                return true;
            };
#endif

            using var httpclient = new HttpClient(clientHandler);
            httpclient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", token);

            var url = $"{Constants.ApiUri}{uri}";
            var result = await httpclient.GetAsync(url);

            if (!result.IsSuccessStatusCode)
                throw new ApiException(
                    $"[{result.StatusCode}] Error sending get request to {uri}",
                    await result.Content.ReadAsStringAsync().ConfigureAwait(false),
                    result.StatusCode
                );

            var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
            return JsonConvert.DeserializeObject<T>(content);
        }

        /// <summary>
        ///     Retrieve a stream for the api
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        protected static async Task<MemoryStream> GetStreamWithAuthAsync(string uri, string token)
        {
            var clientHandler = new HttpClientHandler();


#if DEBUG //  When we connect to localhost with https this workaround is used for ignoring certificate problems
            clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
#endif

            using var httpclient = new HttpClient(clientHandler);

            if (!string.IsNullOrEmpty(token))
                httpclient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", token);

            var url = uri;
            var result = await httpclient.GetAsync(url);

            if (!result.IsSuccessStatusCode)
                throw new ApiException(
                    $"[{result.StatusCode}] Error sending get request to {uri}",
                    await result.Content.ReadAsStringAsync().ConfigureAwait(false),
                    result.StatusCode
                );

            var ms = new MemoryStream();
            await result.Content.CopyToAsync(ms);
            return ms;
        }

        /// <summary>
        ///     Generic method for posting data
        /// </summary>
        /// <param name="httpContent"></param>
        /// <param name="uri"></param>
        /// <param name="token"></param>
        /// <typeparam name="T">Object type that will be given back after the post</typeparam>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        protected static async Task<T> PostAsync<T>(HttpContent httpContent, string uri, string token)
        {
            var clientHandler = new HttpClientHandler();

#if DEBUG //  When we connect to localhost with https this workaround is used for ignoring certificate problems
            clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
#endif

            using var httpclient = new HttpClient(clientHandler);

            if (!string.IsNullOrEmpty(token))
                httpclient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", token);

            var url = $"{Constants.ApiUri}{uri}";
            var result = await httpclient.PostAsync(url, httpContent);

            if (!result.IsSuccessStatusCode)
                throw new ApiException(
                    $"[{result.StatusCode}] Error sending post request to {uri} with following httpContent:{httpContent.ReadAsStringAsync().Result}",
                    await result.Content.ReadAsStringAsync().ConfigureAwait(false),
                    result.StatusCode
                );

            var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
            return string.IsNullOrEmpty(content) ? default : JsonConvert.DeserializeObject<T>(content);
        }

        /// <summary>
        ///     Generic method for posting data
        /// </summary>
        /// <param name="id"></param>
        /// <param name="uri"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        protected static async Task DeleteAsync(HttpContent httpContent, string uri, string token)
        {
            var clientHandler = new HttpClientHandler();

#if DEBUG //  When we connect to localhost with https this workaround is used for ignoring certificate problems
            clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
#endif

            using var httpclient = new HttpClient(clientHandler);

            if (!string.IsNullOrEmpty(token))
                httpclient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", token);

            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Delete,
                RequestUri = new Uri($"{Constants.ApiUri}{uri}"),
                Content = httpContent
            };
            var result = await httpclient.SendAsync(request);
            if (!result.IsSuccessStatusCode)
                throw new ApiException(
                    $"[{result.StatusCode}] Error sending post request to {uri}",
                    await result.Content.ReadAsStringAsync().ConfigureAwait(false),
                    result.StatusCode
                );
        }

        /// <summary>
        ///     Generic method for posting data
        /// </summary>
        /// <param name="httpContent"></param>
        /// <param name="uri"></param>
        /// <param name="token"></param>
        /// <typeparam name="T">Object type that will be given back after the post</typeparam>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        protected static async Task<T> PutAsync<T>(HttpContent httpContent, string uri, string token)
        {
            var clientHandler = new HttpClientHandler();

#if DEBUG //  When we connect to localhost with https this workaround is used for ignoring certificate problems
            clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
#endif

            using var httpclient = new HttpClient(clientHandler);

            if (!string.IsNullOrEmpty(token))
                httpclient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", token);

            var url = $"{Constants.ApiUri}{uri}";
            var result = await httpclient.PutAsync(url, httpContent);

            if (!result.IsSuccessStatusCode)
                throw new ApiException(
                    $"[{result.StatusCode}] Error sending post request to {uri} with following httpContent:{httpContent.ReadAsStringAsync().Result}",
                    await result.Content.ReadAsStringAsync().ConfigureAwait(false),
                    result.StatusCode
                );

            var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
            return JsonConvert.DeserializeObject<T>(content);
        }

        /// <summary>
        ///     Generic method for posting data
        /// </summary>
        /// <param name="id"></param>
        /// <param name="uri"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        protected static async Task DeleteAsync(string id, string uri, string token)
        {
            var clientHandler = new HttpClientHandler();

#if DEBUG //  When we connect to localhost with https this workaround is used for ignoring certificate problems
            clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
#endif

            using var httpclient = new HttpClient(clientHandler);

            if (!string.IsNullOrEmpty(token))
                httpclient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", token);

            var url = $"{Constants.ApiUri}{uri}/{id}";

            var result = await httpclient.DeleteAsync(url, CancellationToken.None);
            if (!result.IsSuccessStatusCode)
                throw new ApiException(
                    $"[{result.StatusCode}] Error sending post request to {uri}",
                    await result.Content.ReadAsStringAsync().ConfigureAwait(false),
                    result.StatusCode
                );
        }
    }
}
    public class Centreon
    {
        private String url = @"";
        private String user = "";
        private String password = "";
        private String token = "";
        public CentreonErrors result;

        public async Task<bool> setToken()
        {
            HttpClient client = new HttpClient();
            HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(url + "/api/v2/login"));
            requestMessage.Content = new StringContent("{\"security\":{\"credentials\":{\"login\":\"" + user + "\",\"password\":\"" + password + "\"}}}", Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.SendAsync(requestMessage);
            String responseString = await response.Content.ReadAsStringAsync();

            token = responseString.Split(':').Last().Replace("\"", "").Replace("}", ""); //etwas unschön

            return true; //TODO
        }

        public async Task<bool> getErrors()
        {
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("x-auth-token", token);
            HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, new Uri(url + "/api/beta/monitoring/services?limit=100&search={\"service.state\":{\"$gt\":\"0\"}}"));

            HttpResponseMessage response = await client.SendAsync(requestMessage);
            String responseString = await response.Content.ReadAsStringAsync();

            result = Newtonsoft.Json.JsonConvert.DeserializeObject<CentreonErrors>(responseString); //etas unschön

            return true; //TODO
        }
    }

    public class CentreonErrors
    {
        public List<CentreonResult> result = new List<CentreonResult>();
        public CentreonMeta meta = new CentreonMeta();
    }

    public class CentreonResult
    {
        public int id;
        public int check_attempt;
        public String description;
        public String display_name;
        public CentreonHost host;
        public DateTime last_check;
        public String output;
        public int state;
        public int state_type;
        public CentreonStatus status;
    }

    public class CentreonHost
    {
        public int id;
        public String name;
        public String alias;
        public String display_name;
        public int state;
    }

    public class CentreonStatus
    {
        public int code;
        public String name;
        public int severity_code;
    }

    //wird vmtl. nicht benötigt
    public class CentreonMeta
    {
        public int page;
        public int limit;
        public int total;
    }
public static async void downloadAllFiles() {

    var credentials = new NetworkCredential("USERNAME", "PASSWORD");
    var webDavSession = new WebDavSession(@"https://cp.DOMAIN/remote.php/dav/files/USERNAME/", credentials);
    var items = await webDavSession.ListAsync(@"APK-Test/");

    foreach (var item in items)
    {
        //await webDavSession.DownloadFileAsync(item.Uri, STREAM);

        WebClient myWebClient = new WebClient();
        myWebClient.Credentials = credentials;
        myWebClient.DownloadFile(item.Uri, @"C:\temp" + item.Name);

        Console.WriteLine(item.Name);
    }

}
star

Sat Jan 20 2024 16:23:46 GMT+0000 (Coordinated Universal Time)

#asp.net #packages
star

Mon Sep 04 2023 16:12:25 GMT+0000 (Coordinated Universal Time)

#c# #swagger #asp.net
star

Wed Aug 23 2023 18:51:45 GMT+0000 (Coordinated Universal Time) undefined

#c# #asp.net
star

Fri Jun 23 2023 08:30:33 GMT+0000 (Coordinated Universal Time)

#c# #asp.net #identities #typescript
star

Fri Jun 23 2023 08:28:45 GMT+0000 (Coordinated Universal Time)

#c# #asp.net #identities #angular
star

Fri Jun 23 2023 08:28:00 GMT+0000 (Coordinated Universal Time)

#c# #asp.net #identities #angular
star

Fri Jun 23 2023 08:27:23 GMT+0000 (Coordinated Universal Time)

#c# #asp.net #identities #typescript
star

Fri Jun 23 2023 08:26:17 GMT+0000 (Coordinated Universal Time)

#c# #asp.net #identities #angular
star

Fri Jun 23 2023 08:23:54 GMT+0000 (Coordinated Universal Time)

#c# #asp.net #identities
star

Fri Jun 23 2023 08:22:37 GMT+0000 (Coordinated Universal Time)

#c# #asp.net #identities
star

Fri Jun 23 2023 08:22:05 GMT+0000 (Coordinated Universal Time)

#c# #asp.net #identities
star

Fri Jun 23 2023 08:20:57 GMT+0000 (Coordinated Universal Time)

#c# #asp.net #identities
star

Sun Oct 09 2022 06:19:04 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/7035437/how-to-fix-namespace-x-already-contains-a-definition-for-x-error-happened-aft

#c# #asp.net
star

Thu Apr 07 2022 07:25:07 GMT+0000 (Coordinated Universal Time)

#html #asp.net
star

Tue Mar 15 2022 10:32:24 GMT+0000 (Coordinated Universal Time)

#c# #asp.net #xamarin
star

Mon Mar 14 2022 15:13:30 GMT+0000 (Coordinated Universal Time)

#c# #asp.net
star

Mon Mar 14 2022 15:11:43 GMT+0000 (Coordinated Universal Time)

#c# #asp.net
star

Mon Mar 14 2022 15:11:04 GMT+0000 (Coordinated Universal Time)

#c# #asp.net
star

Mon Mar 14 2022 14:53:25 GMT+0000 (Coordinated Universal Time)

#c# #asp.net
star

Mon Jun 28 2021 06:30:36 GMT+0000 (Coordinated Universal Time)

#c# #asp.net #centreon
star

Wed Jun 23 2021 05:32:19 GMT+0000 (Coordinated Universal Time)

#c# #nextcloud #asp.net #webdav

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension