Snippets Collections
<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

Sun Oct 09 2022 06:19:04 GMT+0000 (UTC) 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 (UTC)

#html #asp.net
star

Mon Mar 14 2022 15:13:30 GMT+0000 (UTC)

#c# #asp.net
star

Mon Mar 14 2022 15:11:43 GMT+0000 (UTC)

#c# #asp.net
star

Mon Mar 14 2022 15:11:04 GMT+0000 (UTC)

#c# #asp.net
star

Mon Mar 14 2022 14:53:25 GMT+0000 (UTC)

#c# #asp.net
star

Mon Jun 28 2021 06:30:36 GMT+0000 (UTC)

#c# #asp.net #centreon
star

Wed Jun 23 2021 05:32:19 GMT+0000 (UTC)

#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