Posts

Showing posts from 2014

PDF from MVC Razor - with heading

Image
Today I was tasked with creating a PDF from a report that had two queries - a header section and detail section. After looking at all the viable options I was tempted by iTextSharp but was faced with the challenge of implementing it in razor.  I then came across this nifty dll written specifically for that purpose and it utilizes iTextSharp to do it. RazorPDF  was the answer.  Al Nyveldt did an excellent job with it and includes a github download with great samples.  The one challenge he didn't cover was my example of two queries to make a more comprehensive report. As shown in the example (screenshot of my pdf generated using this tool) I have header information as well as additional data laid out in a table. To accomplish this I created a ViewModel in my Data project with a simple class that incorporated two references.  One to the header data and one to the Zipcode detail.     public class Fran_Zip_ViewModel     {         public IEnumerable FranZip { get; set; }

#MakeItHappen

Microsoft is making New Years Resolutions come true.  Mine are so big that I am not sure how they could help but thought I would lay it out here for you. 2015 New Years Resolution To get out of debt enough that I can concentrate on bringing my ideas to fruition.  For years I have been making software for my employers while never seeming to have the time to develop my own ideas.  Over the years I have supported domains that I one day will have the time to work on. Some of my domains: ItsaBigDeal.com I envision a daily deal (similar to Woot) and a subscription site combined  If you don't know what a subscription site is - they are becoming a big deal (see mysubscriptionaddiction.com ) ReportMinder.com Wow software out there for daycares/elderly care centers has some deficiencies and I think I can build a better web/app based software UltimateSpaces.com Not sure what I want to do with this domain but it is a great domain. Some of the regionall

Case Statement within Linq

var numberText = ( from n in numbers where n > 0 select new { Number = n , Text = ( n == 1 ? "One" : n == 2 ? "Two" : n == 3 ? "Three" : "Unknown" ) } );

Single Value from Data Entity - not in entity collection

Example of a single computed value from database, not a declared entity type  private decimal getTuneupAmount(DateTime dateCompleted,int classid, int  id)         {        string sql = @"SELECT  (count(ow.orderworkid) * (select tuneupamount from mastertable)) as TuneupAmount";                         sql += " from tbl_o o ";                         sql += " join tbl_work ow on o.orderid=ow.orderid ";                         sql += " join _setup s on ow.taskcodenumber=s.TaskCodeNumber and s.typeid =2 ";                         sql += " WHERE   ow.soldbyid =" + id + "  and ow.solddate ='" + dateCompleted+ "' and o.classcodeid=" + classid + " ";                         sql += " group by soldbyid,ClassCodeID, ow.solddate";  var tuneamt = (_dbContextZ.Database.SqlQuery (sql).SingleOrDefault());                                 decimal retval = 0;             if (tuneamt != null)

Merging Data with LINQ

var terms = from t in HRSystemDB . Terminations select new { Month = t . TerminationDate . Month , Year = term1 . TerminationDate . Year , IsHire = false }; var hires = from emp in HRSystemDB . Persons . OfType < Employee >() select new { Month = emp . HireDate . Month , Year = emp . HireDate . Year IsHire = true }; // Now we can merge the two inputs into one var summary = terms . Concat ( hires ); // And group the data using month or year var res = from s in summary group s by new { s . Year , s . Month } into g select new { Period = g . Key , Hires = g . Count ( info => info . IsHire ), Terminations = g . Count ( info => ! info . IsHire ) }

C#, MVC Tips and Stuff

A list of things that I have found handy to know... Tip #1 Boolean Enum Comparison Not to return an enum value from say an abbreviation to a long string but just to determine if your value is a valid value in the enum list.  So you have your Enums declared in a base class or some other class something like this:  public enum MyCustomEnumGroup     {         ABC,         MQP,         RAD,         STY     } Then wherever you need  to check your string to see if the string you are passing in is in the Enum Group call it as shown below, this returns a boolean based on the match to the enumgroup.   if (Enum.IsDefined(typeof(MyCustomEnumGroup),mystringtopassin))

Wrapping my head around MVC - one page, two views

I am really loving MVC, only really immersed in it for a couple of months but it is all coming together for me lately.  The most difficult challenge I faced in the beginning was generating a mixed context view, by that I mean something more akin to a normal web page. Maybe some header information at top and a grid of data below.  At first it was really easy to get something like a customers orders in the grid but how to display another grid of customer address information on the same page.  So to accomplish this lets say that you have a class that has the orders info. Orders.cs customerid orderid balance description And you have a customer class Customers.cs customerid customername streetaddress Cust_ordersDTO .cs CustomerID orderid balance description CustomerName StreetAddress public List< Cust_orders > AddressList { get; set; } public List< Cust_orders > OrderList { get; set; } So you will need to make a new class that has all properties combined in

Booleans in Linq

Using a nullable Boolean (bool?) datatype in LINQ can cause some issues You can return those values by using the nullable operator as shown below   Transfer = e.Transfer ?? false This will return the value from e.Transfer and if the value is null will return False

LINQ - Left join with where conditions

Left joins don't come natural to LINQ but the solution is not that complicated. Below is my example I needed to pass in 3 fields for my where clause and I was getting back the LoginName field from the USERS table - unfortunately sometimes this field was empty and my join would not work - in the SQL we know and love this is easily accomplished with a left join (take all the fields from the first table or the table on the left and any that match in the second table) Below you can see how this works. The 'subgroup' referenced below is just an alias, there is no table named subroup - almost acting like a temptable.  var mygroupitems = (from e in MyEntities.Terr_History                             join p in MyEntities.Users on e.Approver_User_Id  equals p.Users_Id into XX                             from subgroup in XX.DefaultIfEmpty()                             where e.tdg_PID == pid  && e.Account_Code==accountcode                             && e.

How to get Commas in your razor Html.TextBoxFor

There are so many ways to do this ... but depending on circumstances they don't always work.  The simplest way is to apply the format directly on the Textbox like this:   @Html.TextBoxFor(model => item.Population, "{0:N0}", new {style = "width: 100px;"})

The Simple Answer to the WebGrid sorting issue - LINQ to Entities only supports casting EDM primitive or enumeration types

Spent so much time on this error, examining my models, data structure etc. What it boiled down to was the sortability of the IEnumerable object on the page vs a sortable list. All you need to do most of the time is to recast it in your controller like this:  var retdata = bl.GetPidHistory(pid);  var itemstoreturn = retdata.ToList();  return View(itemstoreturn);  This is applicable when your view has a model like this: @model IEnumerable

SubSelects in LINQ

What a challenge I was facing trying to figure out how to solve this problem in LINQ.. but i did it .. and am sharing. SQL query: Select Distinct  o.ConceptCode, u.firstname, u. lastname , (select count(*)  from callLead  where calldate ='2014-09-02'  and conceptcode=O.conceptcode and userid=O.userid) 'DailyTotal' ,(select count(*) from callLead where calldate between '2014-09-01'  and '2014-09-05' and conceptcode=O.conceptcode and userid=O.userid) 'WTD' ,(select count(*) from callLead where datepart(m,calldate)=9 and conceptcode=O.conceptcode and userid=O.userid) 'MTD' ,(select count(*) from callLead where datepart(yyyy,calldate)=2014 and conceptcode=O.conceptcode and userid=O.userid) 'YTD' from callLead O join users u on o.userid=u.userid The LINQ Conversion: The LINQ version is much prettier actually  var rptSummary = (from e in SalesEntities.CallLeads                             join j in SalesEntities.Users on e

Cannot Convert Int to String - MVC Dropdownlist Nightmare

So I struggled with this simple code for binding a dropdownlist IEnumerable items = db.SiteMenus               .Select(c => new SelectListItem  {  Value = c.MenuID,  Text = c.MenuName               });                  ViewBag.SiteMenuItems = items;               return View();                .Select(c => new SelectListItem   {              Value = c.MenuID,                                Text = c.MenuName               });              ViewBag.SiteMenuItems = items; return View();             list.Add(new SelectListItem { Text = "-Select Category-", Value = "0" });             var cat = (from c in db.SiteMenus select c).ToArray();             for (int i = 0; i < cat.Length; i++)             {                 list.Add(new SelectListItem                 {                     Text = cat[i].MenuName,                     Value = cat[i].MenuID.ToString(),                                 });             }             ViewBag.SiteMenuItems

Microsoft Deserves Some Credit

I am the first to point out system deficiencies and am happy to let you know that this morning I am ragging on no one. I have a new Surface Pro 3 and am loving it as McDonalds might say, this morning I am very happy with Microsoft for a different reason. At work we are using Team Visual Studio - phenomenal product, especially for remote workers.  My work computer, which is a mean laptop with 16 gigs of ram and a kick butt processor has Visual Studio 2012.  This morning I wanted to revisit a project I was working on so decided to try and connect my surface with VS 2013 to the project.  It was so absolutely seamless that it put a happy spin on the day ahead! Congrats to the Visual Studio Online team. So after investigating it looks like with VS 2012 Microsoft did something brilliant - they made the Visual Studio interface backward compatible thus not forcing an office to upgrade all developer software at once but more importantly allowing me to work at 5 in the morning from my surf

Membership and Looping through the Site Users in MVC with Razor

There are so few examples of this out there - it took me forever to find it but it was such a simple, elegant solution that I thought I would share. So in your Action you don't want to use the MembershipCollection directly as it will return a string that will not be IENumerable - instead you will want to use your UsersContext This will go in your Controller     [Authorize(Roles = "Admin")]         public ActionResult MembersIndex()         {             using (var ctx = new UsersContext())             {                 return View(ctx.UserProfiles.OrderBy(x => x.UserId).ToList());             }         } Then in your Razor MVC Page you will do something like this:       @foreach ( var user in Model){         @user.UserName  - @user.UserEmail        } You don't need to declare a model in the top of your page.

An Open Letter to Microsoft

Dearest Microsoft, We have been the best of friends for many years.  I have built my career around your technologies, been an advocate for your software, shared information on your hardware and participated in your MVP program (twice!).  It is out of this deep appreciation for you that I write to you today. I just purchased the Surface Pro 3 - and I love it - but that is not what this letter is about. Your store (microsoftstore.com) could use a revamp.. The deficiencies as I see them are primarily with the customer specific pages, once the customer is signed in. The view on the primary page and the order page is not in a grid as one might expect when supplying this type of information nor is it laid out in a manner easily read, in fact the page is so poorly designed that if you have three orders with 3 items each you have to actually go to the next page to see the third order,  I can't imagine the difficulty if someone had 10 or more orders.  Not only is the view challeng

Data Entity Random Database Record

You've seen those random quotes on pages, probably most of them are done with Javascript.  This one is done using a database table (three fields, id, linenumber,linetext) and a data entity call and features the SKIP method. You have to have an orderby in your query to be able to use SKIP So put a label on the page or webcontrol and format it as you wish From the page load call the function to get the data lblRandom.InnerText = getrandomvalue();  public string getrandomvalue()         {             using (my_maintenanceEntities context = new my_maintenanceEntities())             {                 var query = (from c in context.tbl_texttable                              orderby c.LineNumber                              select c.LineText);                 int count = query.Count();                 int index = new Random().Next(count);                           return query.Skip(index).FirstOrDefault();             }         }

Another Conditional Linq for int values

I have a dropdown list where the first selection is to return ALL Records and the value is 0 otherwise they make a selection and it returns the equivalent integer. Here is how I worked it out in my Linq query The dropdown is passing into a variable called ClassCodeID  && (ClassCodeID.Equals(0) || s.ClassCodeID >= ClassCodeID || s.ClassCodeID == ClassCodeID) And that seemed to work... however when returning values it did not roll up the values as I expected since classcodeID was not in the groupby.. it only returned a record for a specific code but the values from all codes were rolled into the returned data.  I added an additional where statment and this seemed to have fixed the issue . where (ClassCodeID.Equals(0) || s.ClassCodeID == ClassCodeID

Linq Conditional Selection - handling 'like' in Linq

So the first request was to use  two date fields one optional dropdown value an optional textbox  value  Below is the first query I created which satisfied this request.   But scope creep raised its ugly head and the requirements were changed..  Now I need to provide results for either an 'empty' textbox or any entry such as the first couple of letter with  results similar to a "Like" statement - the second example shows how I changed to accommodate.  var dbRecords = (from c in context.tbl_mydata                             where (c.DateRan >= startdate && c.DateRan <= enddate)                                  && (string.IsNullOrEmpty(mnum) || string.Compare(c.MNumber, mnum, true) == 0)                                  && (string.IsNullOrEmpty(concept) || string.Compare(c.Concept, concept, true) == 0)                                  && (!z || c.MNumber.Length <= 5)                                  && (!

Linq - Data Entities - Records by Max Date with CASE

Image
 I needed to get essentially a summary by case statement for a given date.  As you can see I have defined the MAX date into a variable.  This example also shows using a substring of the first character in a LET statement  DateTime? maxDate =                 (from a in context.tbl_tslog                 orderby a.CurrentTime                 select (DateTime?) a.CurrentTime ).Max(); var dbRecords = (from c in context.tbl_testlog                            where (c.CurrentTime >=maxDate)                                         let range = (  c.Usr.ToUpper().Substring(0,1) == "B" ? "US" :                             c.Usr.ToUpper().Substring(0, 1) == "G" ? "CA" :                             c.Usr.ToUpper().Substring(0, 1) == "U" ? "UK" : "Other"                                               )                                  group c by range into g  select new { Group = g.Key, Users = g.Count(), Latest

Conditional Linq value and a beautiful solution

Having little to no experience with Linq this one was rather tough. .  I googled Conditional Data Entity but found nothing as slick as this solution a friend sent me. So the problem was this ... I had some textboxes, date fields etc for report filters but the textbox was OPTIONAL.  I wanted to manage the condition in the query.   So here is what we came up with: var dbRecords = (from c in context.myTable where (string.IsNullOrEmpty(bnum) || string.Compare(c.BNumber, bnum, true) == 0 )  && (c.DateRan >= startdate && c.DateRan <= enddate) And the way this works  - if bnum has a value then we will select where c.BNumber = bnum otherwise we don't use it in the where statement at all.  Really made life easy!

Grouping with Data Entities

I am really loving the data entity in my new projects but have come across a couple of issues already. Tonight I learned about using a field that is not a part of your database and not in the entity but is a consolidation field from a group.  Once I found some good samples it worked incredibly well and I had a little summary grid on the page in just a couple of minutes.  So here is what I did  using (myEntityName context = new myEntityName())     { //First I declared a couple of variables because I was looking at data between specific dates          DateTime startdate = DateTime.Parse("2014-02-01");             DateTime enddate = DateTime.Parse("2014-02-01");          var dbRecords = (from c in context.myTableName                           where (c.MemberStartDate >= startdate && c.MemberStartDate <= enddate)                           group c by c.Concept into g   //So you notice I used a g for the group by set of data //The g.key part th