bhimavarapumurali / testAngular

0 stars 0 forks source link

Version 2 #2

Open bhimavarapumurali opened 1 year ago

bhimavarapumurali commented 1 year ago

using Microsoft.IdentityModel.Clients.ActiveDirectory; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks;

public class GraphApiHelper { private string _clientId; private string _authority; private string _resource; private string _clientSecret;

public GraphApiHelper(string clientId, string authority, string resource, string clientSecret)
{
    _clientId = clientId;
    _authority = authority;
    _resource = resource;
    _clientSecret = clientSecret;
}

public async Task<string> GetAccessTokenAsync()
{
    AuthenticationContext authContext = new AuthenticationContext(_authority);
    ClientCredential clientCredential = new ClientCredential(_clientId, _clientSecret);

    AuthenticationResult authResult = await authContext.AcquireTokenAsync(_resource, clientCredential);
    return authResult.AccessToken;
}

public async Task<string> CallGraphApiAsync(string accessToken)
{
    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        HttpResponseMessage response = await client.GetAsync("https://graph.microsoft.com/v1.0/me");
        if (response.IsSuccessStatusCode)
        {
            return await response.Content.ReadAsStringAsync();
        }
        else
        {
            return $"Error: {response.StatusCode}";
        }
    }
}

}

bhimavarapumurali commented 1 year ago

using Microsoft.Identity.Client;

// Set your Azure AD app registration information string clientId = "Your-Application-ID"; string clientSecret = "Your-Client-Secret"; string authority = "https://login.microsoftonline.com/Your-Tenant-ID"; string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

IConfidentialClientApplication app = ConfidentialClientApplicationBuilder .Create(clientId) .WithClientSecret(clientSecret) .WithAuthority(new Uri(authority)) .Build();

AuthenticationResult result = await app.AcquireTokenForClient(scopes) .ExecuteAsync();

string accessToken = result.AccessToken;

bhimavarapumurali commented 8 months ago

using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Linq;

public class RestrictedWordsFilterAttribute : ActionFilterAttribute { private readonly string[] restrictedWords = { "restricted1", "restricted2", "restricted3" };

public override void OnActionExecuting(ActionExecutingContext context)
{
    foreach (var argument in context.ActionArguments.Values)
    {
        if (argument is string data && ContainsRestrictedWords(data))
        {
            context.Result = new BadRequestObjectResult("Restricted words are not allowed.");
            return;
        }
    }

    base.OnActionExecuting(context);
}

private bool ContainsRestrictedWords(string data)
{
    return restrictedWords.Any(word => data.Contains(word, StringComparison.OrdinalIgnoreCase));
}

}

bhimavarapumurali commented 8 months ago

using Newtonsoft.Json; using Newtonsoft.Json.Linq;

class Program { static void Main(string[] args) { string jsonString = "{\"name\":\"John\",\"age\":30}";

    bool isValidJson = IsValidJson(jsonString);

    if (isValidJson)
    {
        Console.WriteLine("The given string is a valid JSON object.");
    }
    else
    {
        Console.WriteLine("The given string is not a valid JSON object.");
    }
}

static bool IsValidJson(string strInput)
{
    strInput = strInput.Trim();
    if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
        (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
    {
        try
        {
            JToken.Parse(strInput);
            return true;
        }
        catch (JsonReaderException)
        {
            return false;
        }
        catch (Exception)
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}

}

bhimavarapumurali commented 8 months ago

using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System;

class Program { static void Main(string[] args) { string jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

    JObject jsonObject = JObject.Parse(jsonString);

    // Iterate over properties and print values
    foreach (var property in jsonObject.Properties())
    {
        Console.WriteLine($"Key: {property.Name}, Value: {property.Value}");
    }
}

}

bhimavarapumurali commented 8 months ago

using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq;

class Program { static void Main(string[] args) { string jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

    JObject jsonObject = JObject.Parse(jsonString);

    List<object> propertyValues = jsonObject.Properties()
        .Select(p => p.Value)
        .ToList();

    // Print the values in the list
    Console.WriteLine("List of property values:");
    foreach (var value in propertyValues)
    {
        Console.WriteLine(value);
    }
}

}

bhimavarapumurali commented 8 months ago

using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq;

class Program { static void Main(string[] args) { string jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

    JObject jsonObject = JObject.Parse(jsonString);

    List<object> propertyValues = jsonObject.Properties()
        .Select(p => p.Value)
        .ToList();

    // Convert object values to string values
    List<string> stringValues = propertyValues
        .Select(value => value.ToString())
        .ToList();

    // List of restricted words
    List<string> restrictedWords = new List<string> { "John", "London" };

    // Compare the string values with the list of restricted words
    var matchedValues = stringValues
        .Where(value => restrictedWords.Contains(value));

    // Print the matched values
    Console.WriteLine("Matched values with restricted words:");
    foreach (var value in matchedValues)
    {
        Console.WriteLine(value);
    }
}

}

bhimavarapumurali commented 8 months ago

using Microsoft.AspNetCore.Mvc;

namespace YourNamespace { [Route("api/[controller]")] [ApiController] public class YourController : ControllerBase { [HttpPost] [Route("yourAction")] public IActionResult YourAction([FromBody] YourModel model) { // Check if the model is valid if (!ModelState.IsValid) { // You can customize the error code as per your requirement int errorCode = 400; // Bad request

            // Create a custom object with error information
            var errorResponse = new
            {
                ErrorCode = errorCode,
                ErrorMessage = "Invalid model",
                Model = model
            };

            // Return a bad request object result with the custom error object
            return new BadRequestObjectResult(errorResponse);
        }

        // Your logic here if the model is valid
        // return Ok(); or any other appropriate result
    }
}

}

bhimavarapumurali commented 8 months ago

using Microsoft.AspNetCore.Http; using System; using System.Linq; using System.Threading.Tasks;

public class RestrictedWordsMiddleware { private readonly RequestDelegate _next; private readonly string[] _restrictedWords = { "restricted1", "restricted2", "restricted3" }; // Define your restricted words here

public RestrictedWordsMiddleware(RequestDelegate next)
{
    _next = next;
}

public async Task Invoke(HttpContext context)
{
    // Check if the request path needs to be checked for restricted words
    if (context.Request.Path.HasValue && !IsPathExcluded(context.Request.Path))
    {
        // Check if request content contains restricted words
        if (ContainsRestrictedWords(context.Request))
        {
            context.Response.StatusCode = StatusCodes.Status403Forbidden;
            await context.Response.WriteAsync("Request contains restricted words.");
            return;
        }
    }

    await _next(context);
}

private bool ContainsRestrictedWords(HttpRequest request)
{
    // Check request content for restricted words
    // You may need to customize this based on your specific requirements
    var content = request.Body; // Access request body here
    // Implement your logic to check for restricted words
    // For example:
    // return content.Contains("restricted1") || content.Contains("restricted2") || ...
    return false;
}

private bool IsPathExcluded(PathString path)
{
    // Add paths that should be excluded from the restricted words check
    // For example:
    // return path.StartsWithSegments("/public");
    return false;
}

}

bhimavarapumurali commented 8 months ago

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Other middleware configurations

app.UseMiddleware<RestrictedWordsMiddleware>();

// Other middleware configurations

}

bhimavarapumurali commented 8 months ago

using System; using System.Linq; using System.Collections.Generic;

class Program { static void Main(string[] args) { List restrictedWords = new List { "bad", "illegal", "dangerous" }; List stringsList = new List { "This is a bad idea", "This is not illegal", "This is dangerous" };

    List<string> matchedStrings = stringsList
        .Where(str => restrictedWords.Any(word => str.ToLower().Contains(word)))
        .ToList();

    Console.WriteLine("Matched strings:");
    foreach (string str in matchedStrings)
    {
        Console.WriteLine(str);
    }
}

}

bhimavarapumurali commented 8 months ago

Subject: Appreciation for Your Outstanding Support and Leadership

Dear [His Name],

I hope this message finds you well. I wanted to take a moment to express my sincere appreciation for your exceptional contributions within our team, especially as one of the lead figures under the same product area.

Your unwavering support and leadership during our project deliveries have not gone unnoticed. Your ability to navigate challenges, offer guidance, and provide assistance whenever needed has been instrumental in the success of our endeavors. Your dedication to ensuring that our team functions smoothly and efficiently sets a remarkable standard for all of us to aspire to.

Your commitment to excellence is evident in everything you do, and it truly inspires us all. Your positive attitude and willingness to go above and beyond have created a supportive environment where everyone feels valued and motivated to do their best work.

On behalf of the entire team, I want to express our deepest gratitude for your hard work, dedication, and leadership. Your contributions have not only strengthened our projects but also enriched our team dynamic. We are incredibly fortunate to have someone like you leading us forward.

Thank you once again for your outstanding efforts. Your contributions make a significant difference, and we are truly grateful for all that you do.

Warm regards,

[Your Name]