Monday, August 28, 2017

Open Oracle dmp file and export to SQL DDL file

Problem:

Working a project to migrate a system off of Oracle and onto SQL Server.
The current host responded to my request for DDL with a dmp file!  The dmp
file is a binary format which is used by Oracle toolset to import and export database
content and structures.  The point being that without Oracle installed on a system
you cannot read this file.  Minor point we are not an Oracle shop and so do not
have the in-house expertise.  Say hello to Prof Google.


Solution:

1.) Download Oracle OracleXE112_Win64.zip.  Available on the Oracle site once you register.
2.) Install this onto your box
3.) Most likely will install at c:\oraclexe\app\oracle
4.) Get your dmp file (YourDBA.dmp)
5.) Place it into following location: c:\oraclexe\app\oracle\admin\xe\dpdump
Note: You can place this dmp file in another folder but you will be required to configure
the database settings.(https://docs.oracle.com/cd/E11882_01/server.112/e22490/dp_overview.htm#SUTIL819)
6.) Start up a command prompt and navigate to directory: c:\oraclexe\app\oracle\product\11.2.0\server\bin
7.) Issue following command
impdp 'system/root AS SYSDBA' show=Y file=YourDBA.dmp


End result was the creation of the YourDBA.sql which gives us the file we wanted in the first place!


Reference:

  1. https://docs.oracle.com/cd/E11882_01/server.112/e22490/dp_overview.htm#SUTIL819



Monday, August 21, 2017

ADFS 2.0 Token based Authentication Token Expiry





Token based Authentication Token Expiry

Tokens issued by AD FS 2.0 expire after a default time of 60 minutes. This requires users to be re-authenticated (for internal access) or to sign in again (for IFD access). The token lifetime is set separately for each relying party trust (internal and external).
To check the life time, complete the following steps on the AD FS 2.0 server:
  1. Check the names for the relying party trusts in the AD FS 2.0 Management Console and use the appropriate names in the following steps.
  2. Start Windows Powershell (use Run as Administrator).
  3. In Powershell, type Add-PSSnapin Microsoft.Adfs.Powershell.
  4. To view information for the internal relying party trust, type Get-ADFSRelyingPartyTrust –Name “CRM Internal Claims Relying Party”. Replace CRM Internal Claims Relying Party with the appropriate name for your ADFS configuration.
  5. Review the value for TokenLifetime. The value is measured in minutes.
  6. To change the value, type Set-ADFSRelyingPartyTrust –Targetname “CRM Claims Relying Party” –TokenLifetime newvalue where newvalue is the value in minutes.
  7. Repeat this process for the external (IFD) relying party trust.


Source:
  1. http://www.fkbase.info/node/163
  2. https://technet.microsoft.com/en-us/library/gg188586(v=crm.6).aspx
  3. https://samlman.wordpress.com/2015/03/01/setting-the-login-token-expiration-correctly-for-sharepoint-2010-saml-claims-users/
  4. http://stackoverflow.com/questions/23692326/adfs-2-0-microsoft-identityserver-web-invalidrequestexception-msis7042

Working with MVC5 and bootstrap DateTimePicker (eonasdan)


Issue:



Install-Package Bootstrap.v3.Datetimepicker.CSS



bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/bootstrap-datetimepicker.min.js",
                      "~/Scripts/respond.js"));

bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/bootstrap-datetimepicker.min.css",
                      "~/Content/site.css"));


<script type="text/javascript">
    $('#DateTest').datetimepicker(
        {
   //v3 turn off the time selector
            format: 'DD-MMM-YYYY'
            //pickDate: true                 //en/disables the date picker
           // pickTime: false,                 //en/disables the time picker
            //useMinutes: false,              //en/disables the minutes picker
           // useSeconds: false,              //en/disables the seconds picker
          //  startDate: moment().subtract('days', 1)// a minimum date

        });
</script>


Source:


https://blog.jigsawpieces.me/2014/07/23/lbd-adding-datetimepicker-control-to-mvc-project/
http://eonasdan.github.io/bootstrap-datetimepicker/Options/

date type IE-11 limitation




Working in MVC project and using different browser's, I ran into this issue with the date picker supported natively in Chrome but not in IE.


@Stephen Muecke pointed the reason of the problem:

Refer comparision here. The type="date" attribute is not supported in either IE-11 or FireFox-38 so you're out of luck for the time being.


@section Scripts {
    /* ... */
    <script type="text/javascript">
        /* ... */
        if (!Modernizr.inputtypes.date) {
            $('.datepicker').datepicker();
        }
    });

</script>



Source
https://stackoverflow.com/questions/31099367/datetime-picker-doesnt-appear-in-internet-explorer-and-firefox-with-bootstrap

C# date comparison MVC Razor

Issue:
I had a problem with a conditional test which was failing.  I was trying to compare two dates but the condition was not firing in my view.




claimPayments.Payment_Date.Value.ToString("dd-MMM-yyyy") == temp.ToString("dd-MMM-yyyy")


changed it to


claimPayments.Payment_Date.Value.Ticks.Equals(temp.Ticks)


This fixed the problem.  Using the ticks function gets around the issue of trying to match date formats.



Thursday, June 8, 2017

MVC Caching issue

Issue:

I had an issue with a MVC view rendering a modal page.  The problem was that the AJAX call was not refreshing the view when it was re-rendered on the page.  The change to the database is occurring but the view refresh was not showing the latest information.

 var data = { "claimNumber": activeClaimID };
        $.ajax
        (
                 {
                     url: '@Url.Action("IndexPartial", "CaseFileViewModels")',
                     async: false,
                     type: 'GET',
                     data: data,
                     success: function (result) {

                         hideWaitDialog();
                       
                         //Clear out the entire modal block
                         $('#modal-container').empty();
                         $('#modal-container').append(result);
                         ret = true;
                     },
                     error: function (xhr, status, err) {
                         alert(xhr.responseText);
                         alert(status);
                     },
                 }
         );


My problem was that I did not assign the attribute Output Cache to the ActionResult.
Once I disabled the default hander on ActionResult then my view began to refresh.

[OutputCache(Location = System.Web.UI.OutputCacheLocation.None)]
public ActionResult IndexPartial()
{....}


Source:

https://stackoverflow.com/questions/20917398/view-not-refreshing-after-ajax-call


Tuesday, June 6, 2017

Jquery attr method


Issue

I had a checkbox with imbedded attributes.  I needed to get these values out of based on a click event
The key to getting the specified values was the use of the attr method.

<input name="SavePaySchedule" id="SavePaySchedule1" type="checkbox" value="true" selectedscheduleitem="1f3dc523-c466-4dc5-bb52-09848a79c9fd" schedulecountry="44207e0b-d4ca-4bfd-b1b3-2f28a2c6d5ef">


 <script type="text/javascript">
                                    $('#SavePaySchedule').click(function (o) {
                                        var $input = $(this);
                                        var scheduleCountry = $input.attr('scheduleCountry');
                                        var selectedScheduleItem = $input.attr('selectedScheduleItem');
                                        var activeState = $input.prop('checked');

                                    });
                                </script>

Source

http://api.jquery.com/attr/

Linq to SQL distinct

Issue:

I needed to get a distinct value from a query like

select distinct o.ProgramID,t.Program
from table1 o
inner join table2 t on o.ProgramID=t.ProgramID
order by t.Program

var result = (from o in table1
              join t in table2 on o.ProgramID equals t.ProgramID
              orderby t.Program
              select new { o.ProgramID, t.Program }).Distinct();
https://stackoverflow.com/questions/4318909/linq-to-sql-distinct-and-orderby

Wednesday, April 19, 2017

MVC razor decimal formatting

Issue:

Trying to get a decimal property of an EF generated model to display more than default 2 decimal place accuracy.

Use N6 as the numeric format string.
myDecimal.ToString("N6");
or
string.Format("{0:N6}", myDecimal);

Source:

http://stackoverflow.com/questions/8412882/c-sharp-show-a-decimal-to-6-decimal-places

The entity cannot be constructed in a LINQ to Entities query

Issue:


I had a problem casting an anonymous type to a type of a ModelView class that I had defined.
The query worked but failed on my conversion to the type PayScheduleCurrencyModelView.

Incorrect:

 var currencyDetail = (from hn in db.Host_Nation
                                      join cur in db.Currencies on hn.Currency_ID equals cur.Currency_ID
                                      where hn.Host_Nation_ID.Equals(country)
                                      select new PayScheduleCurrencyModelView
                                      {
                                          Country_ID = hn.Host_Nation_ID,
                                          Country = hn.Host_Nation_Name,
                                          Currency_Code = cur.Code,
                                          Currency_Description = cur.Description,
                                          Exchange_Rate = cur.Rate
                                      }).AsEnumerable().Select(x => new PayScheduleCurrencyModelView
                                      {
                                          Country_ID = x.Country_ID,
                                          Country = x.Country,
                                          Currency_Code = x.Currency_Code,
                                          Currency_Description = x.Currency_Description,
                                          Exchange_Rate = x.Exchange_Rate
                                      }).FirstOrDefault();


Correct:


 var currencyDetail = (from hn in db.Host_Nation
                                      join cur in db.Currencies on hn.Currency_ID equals cur.Currency_ID
                                      where hn.Host_Nation_ID.Equals(country)
                                      select new 
                                      {
                                          Country_ID = hn.Host_Nation_ID,
                                          Country = hn.Host_Nation_Name,
                                          Currency_Code = cur.Code,
                                          Currency_Description = cur.Description,
                                          Exchange_Rate = cur.Rate
                                      }).AsEnumerable().Select(x => new PayScheduleCurrencyModelView
                                      {
                                          Country_ID = x.Country_ID,
                                          Country = x.Country,
                                          Currency_Code = x.Currency_Code,
                                          Currency_Description = x.Currency_Description,
                                          Exchange_Rate = x.Exchange_Rate
                                      }).FirstOrDefault();


The fix was to drop the implied cast in the linq to sql query.  This cast was causing the EF error.


Source:


  1. http://stackoverflow.com/questions/12916080/the-entity-or-complex-type-cannot-be-constructed-in-a-linq-to-entities-query

Friday, April 14, 2017

Set variable formatting in MVC razor

Issue

This was a real challenge to figure out.  It seems pretty straight forward but it is the details that eat up so much time.  I had a number of decimal data types that represented currency.  I wanted them displayed at local currency.  I thought .Net has this down and lots of people have done this already.  Easy, right?

Well, yes and no.  I went to implement and found most examples and answers incomplete.

Here is what you need.  In the razor view, add references to the threading and globalization namespaces:

@using System.Threading
@using System.Globalization

In your markup, use the String.Format and CultureInfo methods to get your formatting correct.

 var tDebit = String.Format(new CultureInfo("en-US"), "{0:C}", nDebit);
 @Html.Raw(tDebit);



Sources

  1. https://msdn.microsoft.com/en-us/library/bz9tc508.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-3
  2. http://stackoverflow.com/questions/10740828/format-decimal-to-currency-in-viewbag
  3. https://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

Tuesday, April 4, 2017

Print content of javascript object

Issue:

The issue I had was listing the contents of js object.  This is pretty straightforward but handy.

alert(JSON.stringify(YOUR_OBJECT_HERE, null, 4));

Source:

http://stackoverflow.com/questions/1625208/print-content-of-javascript-object

Friday, March 24, 2017

DateTime DisplayFormat seems to have no effect (MVC5, Razor)

Issue:

I had declared in my model the following

[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? AuditDate { get; set; }

  @Html.EditorFor(model => model.AuditDate, new { htmlAttributes = new { @class = "form-control" } })
           
But it was not working!

Then I noted that the Default Displayformat is defined to work with @Html.Display or @Html.DisplayFor and inorder to get it working with Editor controls you need to apply ApplyFormatInEditMode = true.



Source:

https://forums.asp.net/t/1857087.aspx?DateTime+DisplayFormat+seems+to+have+no+effect+MVC4+Razor+

Wednesday, March 22, 2017

MVC attribute DataFormatString

Issue

Needed to format dates in an MVC model.  I wanted to use the attribute decorators for the properties.
I just could not remember the syntax for DataFormatString

  [Display(Name = "Date Notified")]
  [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy} ")]
  public DateTime? Received_Date { get; set; }

{0:dd MMMM yyyy}    -    gives 24 February 2006
{0:MMM dd}    -    gives Feb 24 (substitue MMM with MMMM for the full month name instead of abbreviation)
{0:dd/MM/yy}    -    gives 24/02/06
{0:dd/MM/yyyy}    -    gives 24/02/2006


Source

https://social.msdn.microsoft.com/Forums/windows/en-US/bb8b1e0e-bd41-4206-9895-4e79463b9bc6/dataformatstring-for-datetime-column?forum=winformsdatacontrols

Monday, March 20, 2017

Remove Timestamp from a DateTime variable in MVC Razor

Issue

I needed to format some dates on a View and could not remember the syntax.

Define in your model a readonly variable

public String startDateFormatted { get { return String.Format("{0:dd/MM/yyyy}", startDate); } }
Then in the razor syntax just use DisplayFor

DisplayFor(modelItem => item.startDateFormatted)

OR

You can use the assign the date formatting attributes on the property of the model

[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")]
public DateTime? startDate { get; set; }

Source

http://stackoverflow.com/questions/11122171/asp-net-mvc-razor-remove-time-from-datetime-property

Friday, March 17, 2017

AJAX Controller Action Method from a Razor View


Issue

How to call to a controller action from jquery?

Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}
Person class
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
Key to note here is that the data line id must match the name of the variable in the Action result parameter list.

Source

http://stackoverflow.com/questions/14049817/in-asp-net-mvc-all-possible-ways-to-call-controller-action-method-from-a-razor
http://stackoverflow.com/questions/1194104/jquery-ajax-ajax-passing-parameters-to-callback-good-pattern-to-use
http://stackoverflow.com/questions/15576548/how-to-pass-parameters-in-get-requests-with-jquery

Handling Nullable Guid


Issue

How to cast nullable Guid inline?

 return source ?? Guid.Empty;

Source

http://stackoverflow.com/questions/5498528/how-to-convert-guid-to-guid

Thursday, March 9, 2017

Linq to SQL where clause against collection of list values

Problem:

I was working on an EF Model with Linq 2 SQL.  
I sometimes depend on the SQL sp's which depend upon subqueries

select x.value1,x.value2 from myTable x
where
x.primarykey in (select foreignkey from myTable2 where name="jump")

How do you accomplish this in Linq?


Solution:

var innerquery = (from iq in myTable2
where iq.name.Equals("jump")
select iq.id);

var Ids = innerquery.ToList();

var query = 
from mt in myTable
where
Ids.Any(qq => mt.Id.Equals(qq)
select mt);

Source:

http://stackoverflow.com/questions/1075540/linq-to-sql-how-to-do-where-column-in-list-of-values

.NET: Combining two generic lists

 

Problem:

I had created two List collections based on a some predicate searches against an EF model.
I need to blend the 2 lists together


Solution:

The AddRange method did the trick
List<Type> list1;
List<Type> list2;

List<Type> combined;
combined.AddRange(list1);
combined.AddRange(list2);

Source:

http://stackoverflow.com/questions/2002770/net-combining-two-generic-lists


Wednesday, March 1, 2017

Convert nullable bool? to bool

I was trying to set up a complex query screen in MVC.  I have some checkboxes which may or may not be used in the query.  I needed to cast the nullable bool to bool


bool newBool = x.HasValue ? x.Value : false;

Source:
http://stackoverflow.com/questions/6075726/convert-nullable-bool-to-bool

Thursday, February 16, 2017

How To Create Sub Dropdown menu in MVC 5 ?

Problem:

I needed a way to put a submenu into a menu in bootstrap in MVC 5 project.  The folks at bootstrap don't support this anymore.

Solution:

CSS:
#nav ul{
    display : none;
}
#nav li:hover > ul{
    display : block;
}
    <ul id="nav">
      <li><a href="#">Menu1</a></li>
      <li><a href="#">Menu2</a></li>
      <li><a href="#">Menu3</a></li>
      <li>
        <a href="#">Menu4</a>
        <ul>
            <li><a href="#">SubMenu1</a></li>
            <li><a href="#">SubMenu2</a></li>
            <li><a href="#">SubMenu3</a>
                <ul>
                    <li><a href="#">SubMenu11</a></li>
                    <li><a href="#">SubMenu22</a></li>
                </ul>
            </li>
        </ul>
      </li>
    </ul>

Source:

https://forums.asp.net/t/1987573.aspx?How+To+Create+Sub+Dropdown+menu+in+MVC+5+