rwezowicz

This user hasn't shared any biographical information

Homepage: http://notjusttheory.wordpress.com

Converting a System.IO.Stream to String

This is a piece of code I have needed a bunch recently … found originally at StackOverflow

byte[] bytes = new byte[content.Stream.Length];
content.Stream.Position = 0;
content.Stream.Read(bytes, 0, (int)content.Stream.Length);
string data = Encoding.UTF8.GetString(bytes);

Leave a comment

Adding log4net to your .NET application

Having done this twice in the last two weeks (and forgetting the second time what I did the first time), I figure it would be good to notate this:

  • Install log4net from NuGet
  • Create a log4net.config file
    • Confirm that the directory you are using for your log is able to be written by the application
  • Add the following to the bottom of your AssemblyInfo.cs file
    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
  • In Global.asax.cs add the following (link):
    // Initialize log4net.
    if (!LogManager.GetRepository().Configured)
    {
       log4net.Config.XmlConfigurator.Configure();
    }
    
  • Good Site:
    https://www.codeproject.com/Articles/140911/log-net-Tutorial

Leave a comment

C# System.DayOfWeek Enumeration Incrementing

We ran into a very unique bug yesterday that was causing an infinite loop because a condition was never getting hit.  We were utilizing the System.DayOfWeek Enumeration and incrementing one day at a time of it.

Here is the gotcha though, if you increment a DayOfWeek, be very aware if you are incrementing PAST Saturday.

If it is Sunday, and you add a day, of course you get Monday … and so forth until you get to Saturday … when you add one day to Saturday, you would expect to get Sunday as DayOfWeek is an enumeration type of object … BUT YOU DON’T, you get 7!!!

And then further if you go to compare that 7 to a DayOfWeek item (Sunday – Saturday), you cannot … because it is 7 … not part of the DayOfWeek Enumeration

// Start Day
DayOfWeek dow = DayOfWeek.Sunday;
Console.Write(dow);

// Increment to Monday
dow = dow+1;
Console.Write(dow);

// Increment to Tuesday
dow = dow+1;
Console.Write(dow);

... the other days

// Increment to Saturday
dow = dow+1;
Console.Write(dow);

// You would think it would increment to Sunday ... BUT ??????????
dow = dow+1;
if (dow == DayOfWeek.Sunday) 
{
  Console.Write("dow variable is Sunday");
} 
else 
{
  Console.Write("dow variable is NOT SUNDAY ... it is " + dow);
}

The output of this is

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
dow variable is NOT SUNDAY ... it is 7

The fix to be able to check this is to CAST/CONVERT the DayOfWeek variable to and Integer, and then and only then can you check if it incremented past Saturday.

// FIX
dow = dow+1;
if (Convert.ToInt16(dow) == 7) dow = DayOfWeek.Sunday;
if (dow == DayOfWeek.Sunday) 
{
  Console.Write("dow variable is Sunday");
} 
else 
{
  Console.Write("dow variable is NOT SUNDAY ... it is " + dow);
}

Definitely a hiccup that probably needs to be addressed by Microsoft.

I found a StackOverflow discussion on this … and seemingly the “+” isn’t fully implemented for System.DayOfWeek, but this would be around adding Monday to Wednesday or something like that … adding single days, should be supported, it only makes sense, but for completeness here is the link.

I submitted it to Microsoft … it’s currently in Triaged state:
https://developercommunity.visualstudio.com/content/problem/269125/systemdayofweek-enumeration-incrementing-by-day.html

Leave a comment

“Stub” Functions in SQL Server

Recently we implemented a new way to deploy functions (and stored procedures) in SQL Server.

For many years, when we deployed new versions of software, we would delete a function that was there, and then just redeploy it which was fine in practice, but we lost history on it.

Here is an example function that was deployed this way:

IF EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[FunctionName]') 
AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
 DROP FUNCTION dbo.FunctionName
GO

CREATE FUNCTION FunctionName()
RETURNS @t TABLE (t int)
AS
BEGIN
....

All would work fine … but as I stated, the modify/create dates and so forth were lost on the function.

So we changed out deployment structure a bit to create a “stub” function FIRST if it wasn’t there already and then ALTER it … thus we wouldn’t lose the modify/create date history or other deeper changes on it.

IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE NAME = 'FunctionName')
EXEC ('CREATE FUNCTION [dbo].[FunctionName]() RETURNS VARCHAR(1) AS 
BEGIN RETURN ''1'' END')
GO

ALTER FUNCTION [dbo].[FunctionName]()
RETURNS @t TABLE (t int)
AS
BEGIN
....

The thought was that this would work fine (we’ve been doing it this way with our stored procedures too without issue) … BUT HERE we ran into a problem

Msg 2010, Level 16, State 1, Procedure FunctionName, Line 8 Cannot perform alter 
on 'dbo.FunctionName' because it is an incompatible object type.

And incompatible type error … HUH?

Capture

I confirmed that the function CREATE worked correctly … but I couldn’t ALTER it … AND it wasn’t appearing in the “Table-valued Functions” in the Object Explorer of SQL Server Management Studio, but it definitely created (because I couldn’t create it again) … but where?

 

 

And then I found what happened … it created the “stub” function as a “Scalar-valued Function” because our CREATE statement had return as a scalar value.

So we switched things around to have our “stub” function return a TABLE …

IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE NAME = 'FunctionName')
EXEC ('CREATE FUNCTION [dbo].[FunctionName]() 
RETURNS @t TABLE (t int) AS BEGIN RETURN END')
GO

ALTER FUNCTION [dbo].[FunctionName]()
RETURNS @t TABLE (t int)
AS
BEGIN
....

And NOW it works … it classified the “stub” function at a “Table-valued Function” … and now the ALTER works.

To be totally secure … we updated the NOT EXISTS to be

IF NOT EXISTS (select 1 from sys.objects where name = 'FunctionName' AND type = 'TF')

That further clarified the function as a “Table-valued Function” (TF) in the NOT EXISTS check.

Now that works perfectly and our CREATE “Stub” Function

  • If the function IS NOT there, the CREATE will run and add it and then our ALTER will alter it
  • If the function IS there, our ALTER will just go ahead an alter it

 

 

 

Leave a comment

MultiSelect Drop Down with ASP.NET MVC Custom ID and Name Fields

I needed to create a drop down list where I could select multiple items in ASP.NET MVC, but I needed to potentially also show items already selected.  In addition the ID and Name fields would need to be customly named in the HTML attributes to match project specification when submitting a form.


Attempt 1

I had no problem creating the list, nor was there a problem setting the SELECTED items using the HTML Helper ListBoxFor

@Html.ListBoxFor(m => m.DataTypeSourceSelectedItems,
new SelectList(Model.DataTypeSourceItems, “Value”, “Text”), new { id = Model.ParameterFieldName } )

Which produced the output

<select id=”Parameter2″ multiple=”multiple” name=”DataTypeSourceSelectedItems”>
   <option value=”A”>Test A</option>
   <option selected=”selected” value=”B”>Test B</option>
   <option selected=”selected” value=”C”>Test C</option>
</select>

Functionally, this did EXACTLY what I wanted it do … my options were selected appropriately, I could select multiple outputs, and my ID was correct … BUT the name of the <select> was “DataTypeSourceSelectedItems” … I needed it to be Parameter2 alike to the ID.

So I tried to add the “name” as a htmlAttribute:

@Html.ListBoxFor(m => m.DataTypeSourceSelectedItems,
new SelectList(Model.DataTypeSourceItems, “Value”, “Text”), new { id = Model.ParameterFieldName, name = Model.ParameterFieldName } )

This still didn’t produce the output desired, so I went to another route.


Attempt 2

So I switched to utilizing ListBox standalone

@Html.ListBox(Model.ParameterFieldName, new SelectList(Model.DataTypeSourceItems, “Value”, “Text”, Model.DataTypeSourceSelectedItems), new { id = Model.ParameterFieldName } )

Which produced the output

<select id=”Parameter2″ multiple=”multiple” name=”Parameter2″>
 <option value=”A”>Test A</option>
 <option value=”B”>Test B</option>
 <option value=”C”>Test C</option>
</select>

So this time, my <select> is correct and the name and ID were matching AND correct, but NOTHING is selected.

I went back into Code and actually set the SelectListItems to have the appropriate Selected property but that didn’t have success either.


Attempt 3

Because MVC is so flexible and I don’t HAVE TO utilize the HTML Helper, I opted to just code it directly:

<select id=”@Model.ParameterFieldName” name=”@Model.ParameterFieldName” multiple=”multiple”>
@foreach(SelectListItem sli in Model.DataTypeSourceItems)
{
if (sli.Selected)
{
<option value=”@sli.Value” selected=”selected”>@sli.Text</option>
}
else
{
<option value=”@sli.Value”>@sli.Text</option>
}
}
</select>

Which produces the output

<select id=”Parameter2″ name=”Parameter2″ multiple=”multiple”>
<option value=”A”>Test A</option>
<option value=”B” selected=”selected”>Test B</option>
<option value=”C” selected=”selected”>Test C</option>
</select>

Exactly what I was looking for.


Just goes to prove that the HTML Helpers are there to help us, but they don’t necessarily ALWAYS help.

 

BTW: This is a good location for how to implement MultiSelect Drop Downs in General: https://www.codeproject.com/Articles/1063846/Step-By-Step-Implementation-of-MultiSelectList-In

4 Comments

XML Serialization with Inheritance and “new”

We were building an XML structure … we will call this a Rule and a DerivedRule.

We built simple classes to serialize or deserialize the XML.

At the basic level all that works fine … my DerivedRule will have everything my Rule has and the “Value” string.

The issue arose when we had multiple Rules or DerivedRules … We made a simple LIST classes following the same style:


In theory we would think this work work … RuleList was the base class and DerivedRuleList would just extend RuleList.  The problem was that we were extending the Rules property … but HIDING the base classes property using “new”

When we tried to deserialize this we would get the following error:

5

We were baffled for a while, because we were appropriately utilizing “XmlElement” as requested.  And the we read the error in far more detail … the Rules property was hiding the base class member’s Rules property.  We couldn’t just override it, and because the DerivedRuleList was using a List<DerivedRule> and the RulesList was using a List<Rule>.

After searching for a while, we didn’t find a solution and our final output was that we disconnected the inheritance on the DerivedRuleList and everything came up without issue.

4b

Other attempts were made and some compiled just fine, but wouldn’t actually serialize or deserialize … and that was to make Rule and DerivedRule implement a common interface and then make a SINGLE RulesList with a property of List<IRule> Rules … and while that correctly compiles without any issue, serialization won’t work with an interface without much additional coding.

 

, , , ,

Leave a comment

Unable to Compress Files in Windows 10

Over the past few months, I haven’t been able to “zip” files … knowing that this was a normal thing back in Windows 7, I figured either Windows 10 REMOVED it or something is wrong.

Finally I really needed to send something zipped up … so I researched it … and found this result.  This worked perfectly.

Leave a comment

Passing “LIKE” Parameters To Fetch XML in SSRS Reports

Today I encountered a situation where I needed to do a LIKE lookup in the Account entity in Dynamics CRM 2013 in SQL Server Reporting Services.

I have a simple Fetch XML Query:

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">
     <entity name="account">
          <attribute name="name" alias="Name" />
          <filter type="and">
               <condition attribute="name" operator="like" value="@AccountName" />
          </filter>
     </entity>
</fetch>

The problem here is that I need to add “%”s to the condition to search for multiple items (i.e. the LIKE) … if I want to find any instances where the name has “aca” (to find any academy, academics, etc.) … my condition needs to be:

<condition attribute="name" operator="like" value="%" + @AccountName + "%" />

But that in itself doesn’t work … how can I get the “%”‘s into the query … don’t worry, there is a way.

1) Add a parameter to the SSRS Report as you normally would

parameter

2) Create a dataset and add a custom parameter to the dataset

– Name it whatever you would like, but set it to the value of an expression.  Make the expression look like this

="%" & Parameters!AccountName.Value & "%"

dataset

3) Use the “LIKE” parameter just created in your Fetch XML

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">
     <entity name="account">
          <attribute name="name" alias="Name" />
          <filter type="and">
               <condition attribute="name" operator="like" value="@AccountNameLike" />
          </filter>
     </entity>
</fetch>

 

At this point, test your work, and you should be able to use LIKE parameters in Fetch XML in SQL Server Reports Service Reports.

Leave a comment

Getting the Get FormType CRM 2011+

In CRM 4, we could call the form type very easily … CRM 2011+ isn’t very difficult either

CRM4
crmForm.FormType

CRM 2011+
var type = Xrm.Page.ui.getFormType();

Possible Form Types Returned

 0 – undefined
1 – Create
2 – Update
3 – Read Only
4 – Disabled
5 – Quick Create (being depreciated)
6 – Bulk Edit

Leave a comment

SharePoint Waiting for SP.js to Load

We spent our day here at my FT job trying to figure this our out … me a senior level .NET developer and two senior level SharePoint masters.

First we had nice newly created web part, running a jQuery based carousel of pictures.  Everything was working fine, until we launched it to our SharePoint 2013 publishing page.  SP 2013 Team Pages worked just fine, SP 2010 worked just fine, and edit mode of the SP2013 publishing page worked just fine … but when we moved it to Checked In and Published, literally the web part just stopped.

Also 3 hours later we found what was happening:

We were running the command:

ExecuteOrDelayUntilScriptLoaded(function () { myFunc(); }, "sp.js");

We wanted to make sure that “sp.js” was loaded BEFORE calling our “myFunc” call … well on publishing pages in SP 2013 … they have changed the function for this to

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', myFunc);

Gosh … there is 3 hours lost on my day … jeepers; we made the switch and everything worked immediately

Leave a comment