Posts

Localizer in Controller

Localizer in Controller Using using Microsoft.Extensions. Localization; Includes private readonly IStringLocalizer< AppAccessController>  _localizer; Resource file must be in a Controller Folder in Resources Method example public Dictionary<string,string> GetRoleList(string appName, bool includeX) { //Code here return allItems.ToDictionary<string, string, string>(i => i, i =>  _localizer[i] ); }

Excel download with Jquery using Table

I have a tricky dynamic table built from a model that I did not want to fashion in the controller so wanted to just download the table as shown. This Jquery/Javascript solution allowed me to do just that. Using a button on the page id='export' and using a table on the page id='tblExport' We add an event listener for the button - I have declared everything explicitly but could probably have shortened some references to objects.   //For the Csv Export const toCsv = function (table) { // Query all rows var data = "" ; var tableData = []; var rows = $ ( " table tr " ); rows. each ( function (index, row) { var rowData = []; $ (row). find ( " th , td " ). each ( function (index, column) { rowData. push (column. innerText ); }); tableData. push (rowData. join ( "," )); }); data += tableData. join ( " \n " ); return data; }; const download = function (te...

Linq Remove from list based on other table

One way to do it when you have two lists (repYearlyData and otherdata)       foreach (var yd in repYearlyData)             {                 for(int d=0;d<otherdata.Count;d++)                 {                     if (yd.AssignedRep == otherdata[d].AssignedRep)                     {                         otherdata.RemoveAt(d);                     }                 }             } var result = peopleList2 . Where ( p => ! peopleList1 . Any ( p2 => p2 . ID == p . ID ));         public List<TeamAverages> GetRepMonthlyAverages() ...

Disable Button based on checked items in CheckboxList

Windows Forms using the ClientID                $("#<%=chkMinCedProgramManagers.ClientID %>").find('input[type="checkbox"]').click(function () {                                    $("#<%=btnSaveSubGroup.ClientID %>").removeAttr("disabled");   //Identify How many checkboxes are checked so that we can toggle the button               var prgchecked = $('#<%=chkMinCedProgramManagers.ClientID%>').find('input[type="checkbox"]:checked').length; //Disable button if we have zero checked  if (prgchecked===0) {                         $("#<%=btnSaveSubGroup.ClientID %>").attr("disabled", "disabled");  };                });

Sparkline Chart

VIEW <script src="~/scripts/jquery.sparkline.min.js"></script> <div style="border:2px solid #cccccc;padding:10px;width:50%; box-shadow: 10px 10px 5px #888888;text-align:center;float:left;">             <h4 style="color:#58B609;">Expirations by Month next 12 months</h4><hr />             <div class="sparkline" data-type="bar" data-width="97%" data-height="250px" data-bar-Width="12" data-bar-Spacing="10" data-bar-Color="#58B609" style="float:left;margin-left:30px;">                 @ViewBag.Expire              </div>       $(".sparkline").each(function () {                     var $this = $(this);                     $this.sparkline('html', $this.data());       ...

Multiple Filters

 $(document).ready(function () {     ManageRadioButtons();     numerizeRows();     $('[data-toggle="tooltip"]').tooltip(); }); jQuery.expr[':'].icontains = function (a, i, m) {     return jQuery(a).text().toUpperCase()         .indexOf(m[3].toUpperCase()) >= 0; }; $("#searchInputResponsibility").keyup(function () {     if (checkMultiple() == true) {         filterMultiple();         return true; }     var data = this.value.split(" ");     var currentRow = $("#fbody").find("tr").not('.H').not('.thead');         if (this.value == "") {         currentRow.show();         return;     }     //hide all the rows     currentRow.hide();       currentRow.filter(function (i, v) {     var $t = $(this).find("td:eq(0)");     for (var d = 0;...

Jquery add dynamic numeric column

 Jquery adding column options function numerizeRows() {     var eachRow = $("#fbody").find("tr").not('.H').not('.thead');          var start = 1;     $(".id").each(function() {         this.text(start);         start = start + 1;     });     //eachRow.each(function () {      $(this).children('td:eq(0)').html(start);     //    var myNumber = '<td>' + start + '</td>';     //    this.prepend(start);     //    start = start + 1;     //}); };

Linq list filtered on list

modelItems is a list of Model intList  is a list of Integers I am looking for modelItems where the id is in my Int List var myFilteredList= modelItems.Where(item => intList.Contains(item.Id))   .Select(a => a).ToList();

Dynamic Dropdowns NetCore and Json

 Html for placeholder   <select id="AppList"  class="form-control input-sm"></select> Controller returns  a Model - Add records to the Model and then return as JsonResult  public async Task<JsonResult> GetApplications(int id) {           var selectAppList = new List<ModelName>();              var apps =  _applicationService.GetApplicationModels();                 var modelVariable = (await GetModelRecords);  if (modelVariable is object ) {                   selectAppList.Add(modelVariable); }       return Json(selectAppList);  } Jquery Add something like this to document.ready $("#brandId").change(function () { var id = $("#brandId").val(); BuildAppList(id); }); Then add the function function BuildAppList(id) { $.ajax({ ...

Ajax Loop Photos

function GetPhotos() {     var row = "<div class='w3-container w3-row-padding'>";     var itemcount = 0;     $.ajax({         url: '/Photos/PhotoList',         type: 'GET',         contentType: 'application/json',         data: "{}",         dataType: "json",         success: function (data) {             var count = Object.keys(data).length;            // var row = "";                          $.each(data, function (item) {                                              if (itemcount % 6 != 0) {                     row += "<div class='w3-left w3-p...

MVC Changed State with no query string

 I needed to take action if i was in the edit state of my page.  So in the controller I set a ViewBag object then from my jquery I checked the value I needed to check a NO value in a checkbox if there was no textarea value in the model set  var number = parseInt(@ ViewBag.Edit );             if (number == 1) {                 if ($("#TextAreaEngagement").val().length == 0) {                     $("#chkEngagedNo").prop("checked", true);                 }                              }

Linq Query Syntax vs Method Syntax

Referenced from MSDN: https://msdn.microsoft.com/en-us/library/bb397947.aspx Query syntax: IEnumerable<int> numQuery1 =               from num in numbers             where num % 2 == 0             orderby num             select num; Method syntax:         IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n)

Sticky Footer made simple

CSS Footers are simple but people tend to overthink them.  Here is how it works You have two pieces A container that all your other stuff is in A footer that you want to always stay at the bottom of the page In Blazor I put this container on my content pages and not my host page because I didn't want my left hand nav to be involved <div class="container"> All my content </div> <footer> Centered footer content </footer> And the CSS .container {     width:100%;     padding: 0 15px; } footer {     font-size: 12px; (you could also use a vw value here)     padding-top:20px;     background-color: #xxx;     color: #fff;     margin: auto;     height: 60px;     width: 100%;     position: sticky; //absolute;     bottom: 0;     text-align: center; }

Ah Blazor - Now refresh the page!

Started my first Blazor project today.  New to NetCore as well so it was a fun challenge.  I like that is is similar to MVC  and I appreciate  the ability to add code into my page while building without moving to a controller - it was a real challenge to accommodate some JQuery but I got everything to work.  After looking a little closer I realized a large chunk of my JQuery and even javascript could be moved to the @code section and written differently - made for a cleaner, more readable page. I spent over an hour trying to figure out how to do a simple page refresh!  Part of the challenge is that Blazor is a moving target - different libraries and ways of doing simple tasks from version to version - I am confident that most of that will stop as they more clearly define what it is they want to do with this tool. Refresh a page (NetCore 3.1) First set up an alias for the uriHelper - you will now find it in NavigationManager @inject NavigationManager ...

From Checkbox to Linq list

Just the Values of the Selected Items List <string> selectedValues = chkMyList . Items . Cast < ListItem >() . Where ( li => li . Selected ) . Select ( li => li . Value ) . ToList (); Both Text and Value of Selected item into a listItem object List < ListItem > selected = chkMyList . Items . Cast < ListItem >() . Where ( li => li . Selected ) . ToList ();

Linq Compare to a list

Establish your list var idList = new [] {5, 7}; Compare against the List var jobs = originaljobs.Where(t => t.StatusId != null).Where(t => idList .Contains((int)t.StatusId));  

Conversion Classes

Convert from Model to Dataset public static DataSet ToDataSet (this IList list) { Type elementType = typeof(T); DataSet ds = new DataSet(); DataTable t = new DataTable(); ds.Tables.Add(t); //add a column to table for each public property on T foreach (var propInfo in elementType.GetProperties()) { Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType; t.Columns.Add(propInfo.Name, ColType); } //go through each property on T and add each value to the table foreach (T item in list) { DataRow row = t.NewRow(); foreach (var propInfo in elementType.GetProperties()) { row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value; } t.Rows.Add(row); ...

Jquery ... little things

Code Snippets Remove duplicate IDs on a page - but not the first one     $('[id]').each(function () {                          $('[id="' + this.id + '"]:gt(0)').remove();                       });

Open XML and Word Doc creation

https://github.com/OfficeDev/office-content/blob/master/en-us/OpenXMLCon/articles/360318b5-9d17-42a1-b707-c3ccd1a89c97.md While at Lockheed I created an interface that modified and created contracts on the fly - wish I had kept some code references  - but I started here To generate Word documents with Office Automation within .NET, specifically in C# or VB.NET: Add the  Microsoft.Office.Interop.Word  assembly reference to your project. The path is  \Visual Studio Tools for Office\PIA\Office11\Microsoft.Office.Interop.Word.dll . Follow the Microsoft code example you can find here:  http://support.microsoft.com/kb/316384/en-us .

API Examples Returning various ...

API Examples  public IQueryable<Customer> GetCustomers()         {             return db.Customers;     [ResponseType(typeof(Customer))]         public IHttpActionResult GetCustomer(string email)         {             Customer customer = db.Customers.Where(c=>c.Email== email).FirstOrDefault();             if (customer == null)             {                 return NotFound();             }             return Ok(customer);         }     }   // PUT: api/Customers/5         [ResponseType(typeof(void))]         public IHttpActionResult PutCustomer(int id, Customer customer)     ...