Nov 11, 2014

ASP.NET WebForms - propagating control events up in chain - bubbling

When making complex web forms pages with nested custom control sooner or later you will want centralized management of events raised by controls.
This is oldie but works:

Bubbling an Event

Oct 16, 2014

DotNetNuke - T-SQL manually update to clear password for known user name

DotNetNuke - T-SQL manually update to clear password for known user name

declare @password as varchar(100)
declare @username as varchar(100)
set @password = 'xxxxx'
set @username = 'yyyyy'
begin tran
update aspnet_Membership set
[Password] = @password,
PasswordFormat = 0
where UserId in
(select top 1 UserId from aspnet_Users where UserName = @username)
commit

DotNetNuke - SiteLog T-SQL for deleting everything except newest 100000 rows

DotNetNuke
Unless you master the art of DotNetNuke logging engine most dreadful feature of DNN is its vast log tables which tends to skyrocket size of DNN databases.
This script is no legit solution you should understand and properly configure DNN logging but until then it does the job...

select * into sitelog100000 from SiteLog s
where s.SiteLogId in (
select top 100000 SiteLogId from SiteLog order by SiteLogId desc)
truncate table sitelog


--select * from sitelog100000
set identity_insert sitelog on
INSERT INTO [dbo].[SiteLog]
           ( SiteLogId, [DateTime]
           ,[PortalId]
           ,[UserId]
           ,[Referrer]
           ,[Url]
           ,[UserAgent]
           ,[UserHostAddress]
           ,[UserHostName]
           ,[TabId]
           ,[AffiliateId])
select * from sitelog100000
set identity_insert sitelog off
drop table sitelog100000

Sep 29, 2014

Entity Framework 6 - save changes with values from entity obtained out of context

When saving using Entity Framework changes in Db entity values for updating for existing Entity can be provided by helper  SetValues:


 OfferItem offerItem;
            using (Rainbow3Entities db = new Rainbow3Entities())
            {
                offerItem = db.OfferItem.First();
            }
            var prId = offerItem.ProductID;
            var ofId = offerItem.OfferID;
            offerItem.Name = "dummy";
            using (Rainbow3Entities db = new Rainbow3Entities())
            {
                OfferItem offerItemFromDB = db.Set<OfferItem>().Find(offerItem.ProductID, offerItem.OfferID);
                db.Entry<OfferItem>(offerItemFromDB).CurrentValues.SetValues(offerItem);

                db.SaveChanges();
            }

Sep 17, 2014

Entity Framework - Don't save object graph in disconnected DbContexts

Don't use disconnected DbContexts when you want to save object graph !
Either perform object graph building and save in same DbContext either use foreign keys.

Read more:
http://msdn.microsoft.com/en-us/magazine/dn166926.aspx

Sep 10, 2014

DotNetNuke tips


DNN 7.3 +

Must read !
Proper registration of custon Javascripts and CSS to support minification and bundle-ing;
http://www.dnnsoftware.com/wiki/client-resource-management-api


DNN 7.3.2   Default DNN menu module DDRMenu     

~/DesktopModule/DDRMenu/Menu.ascx

User for MenuStyle="bootstrapNav".
You'll find this menu template in Gravity skin
For example:
...\Portals\_default\Skins\Gravity\bootstrapNav\
You may copy it to your DesktopModule/DDRMenu folder or use it from your skin folder.



DNN 4.9.5.  Anatomy of url in DNN. All of below urls target same DNN page XXX:


  • www.acme.com/Default.aspx?tabid=XXX
  • www.acme.com/tabid/XXX/Default.aspx
  • www.acme.com/AnyTextYouLike/CanBeHere/tabid/XXX/Default.aspx


There is only one catch. If you want to have physical folder in your root (virtual directory) then you don't use tabid:


  • www.acme.com/german/Default.aspx
In this case german is folder in web root.




DNN (4.9.5 ?) helper for accessing physical home DNN directory of active portal:

DotNetNuke.Common.Globals.GetPortalSettings().HomeDirectory

Sep 4, 2014

MS SQL Can't drop user since it is DBO

You are trying to drop user from Security/Users and get error something like "Can't drop user who owns schema ..."

Useful link:

http://www.mssqltips.com/sqlservertip/2620/steps-to-drop-an-orphan-sql-server-user-when-it-owns-a-schema-or-role/

Further actions were needed for me.
Go to Schemas, find schema in question ( e.g. db_owner) -> Properties -> change Schema owner to "dbo".
This will release user in question and you should be able to drop it.


Aug 13, 2014

ASP.NET why Page_PreRender ?

So what's the purpose of Page_PreRender in ASP.NET webforms?

Easiest answer for me is through simple example.


  1. Create classic ASP.NET webforms with single ASPX
  2. Create 2 ASCX web user controls
Place in each code in Page_Load:

WebUserControl1.ascx


    public partial class WebUserControl1 : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Title = "WebUserControl1";
        }

WebUserControl2.ascx

    public partial class WebUserControl1 : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Title = "WebUserControl1";
        }


Register both on ASPX like this:

<%@ Page Title="About" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="WebApplication6.About" %>
<%@ Register Src="~/WebUserControl2.ascx" TagPrefix="app" TagName="web2" %>
<%@ Register Src="~/WebUserControl1.ascx" TagPrefix="app" TagName="web1"%>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">    
    <app:web1 id="ctrl1" runat="server" />  
    <app:web2 id="ctrl2" runat="server" />
</asp:Content>

Run web and observe that in browser  Tab Title is reflecting change from WebUserControl2.ascx Page_Load.
Now add Page_PreRender event in first one WebUserControl1.ascx:

   protected void Page_Load(object sender, EventArgs e)
        {
            Page.Title = "WebUserControl1";
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            Page.Title = "PreRender_WebUserControl1";
        }
    }

Run  and observe that now text from WebUserControl1's Page_PreRender event is shown instead of previous from WebUserControl2 Page_Load.

Same idea if you have filled Page_PreRender of ASPX.

Bottom line is to use Page_PreRender on only one place in your page elements (ASPX,ASCX) when you need to make sure that code in PreRender is the last modification to common page elements that are shared among all controls.

Jul 4, 2014

Publications / Magazine / NDC magazine

http://issuu.com/developermagazine/docs

DotNetNuke / module development / manifest

When developing DNN module extensions in your Visual Studio DNN Module project template there is manifest of your module with extension DNN.
Here is more:

http://www.dnnsoftware.com/wiki/page/manifests

Excerpts:

It should also be made known that each package equals one extension that can be managed in the DotNetNuke Extensions module, where they are grouped by extension type.


Although DNN does not expose a way to take a dependency on a particular .NET framework version, this can easily be emulated by taking a type dependency on a class that does not exist in prior framework versions. For example, to require .NET 4 as a precondition to installation, one may depend instead on the System.Tuple class (which was introduced with .NET 4.0):

<dependency type="type">System.Tuple</dependency>

There are a few things to be aware of when installing multiple packages within a single install (and thus, using a single manifest). First, packages are installed in the order they are declared in the manifest file (top to bottom). . This means, if you are installing a skin extension that also contains a skin object, you need the skin object to be installed prior to the skin being installed (thus, placing the skin object package towards the top, above the skin package). In this example, the skin object was used by the skin being installed and therefore it needed to be available prior to the skin being installed (otherwise, the skin object would not be rendered properly). 


May 9, 2014

Where is ODBC provider 32 bit?

In order to configure ODBC driver for legacy 32 bit application on 64 bit Windows servers use this:

C\windows\sysWOW64\odbcad32.exe

For 64 bit ODBC this is default.


  • On the Start menu, point to Administrative Tools, and then click Data Sources (ODBC).
; but very often ODBC is used for old 32 bit app's and you wont find it there.

May 3, 2014

DotNetNuke 6,7 - researching, estimating

Small researching whether is DotNetNuke dead or still kicking?
Are there true alternatives in ASP.NET CMS arena.

Just some hints:


Good objective review :


Clear Pro & Con:


Is Community Edition crippled in favor of PRO ?


DotNetNuke Community vs Professional Edition:


Integration with Social networks from version 6:


DotNetNuke 6.2 also exposes a full RESTful social API that enables users to create unique applications using social content from DotNetNuke. The API leverages new client-based web development techniques using popular JavaScript frameworks like  jQueryUI and Knockout.js.

DNN Evoq pricing

http://www.clarity-ventures.com/articles/article/721/a-costbenefit-analysis-of-dnn-professional-dnn-enterprise-and-dnn-community-dot

DNN 7 raises minimum requirements for hosting !

http://blog.powerdnn.com/index.php/dotnetnuke-7-the-modern-cms-for-windows-arrives/

What's new in DNN 7?
http://www.arrowtechsolutions.com/whats-new-in-dotnetnuke
 With support for Active Directory and SharePoint Lists, DNN 7.0 can also be seamlessly integrated with popular enterprise applications.

Apr 24, 2014

MS SQL Server - Configuring MS SQL Server for Remote Access

This is repost of this:

Configuring MS SQL Server for Remote Access

Extra info from my experience:

  1. If you have more then one SQL server instance make sure that they use different ports.
    Leave first one on 1433 and assign your new one 1434.
  2. In IP addressess section IPAII make sure to clear TCP Dynamic ports on the bottom.
When trying to connect using SSMS if you had to use different port from 1433 and have some named instance here is naming convention for SQL server address:

vs2008develop,1434\MSSQLSERVERR2

Apr 23, 2014

DotNetNuke - Skins - How to reuse parts of page - using custom control inside skin custom control

Inside your Skins package folder you have number of different skins:

root\_default\Skins\NewSkin\HomeSkin.ascx
root\_default\Skins\NewSkin\ProductsSkin.ascx

You want to reuse repeated functionality, no matter static HTML or server side oriented with DNN expressions.

Create blank ASCX and place your func. in it. You don't need .vb or .cs code file.

Key point is that your header should have attributes like this:

<%@ Control Language="vb" AutoEventWireup="true" %>

DotNetNuke Efficion Articles module - Tips & tricks

Efficion Articles modules


  • Article list - articles/items are displayed but cannot be selected
    • Go to Article details of article that cannot be selected and under section "Detail Type" make sure to choose something different from None like "Text/HTML"


Tips for Articles module :


This was for old version 3.2.6

Apr 14, 2014

ASP.NET Url parts

Just reposting from here:

http://stackoverflow.com/questions/40680/how-do-i-get-the-full-url-of-the-page-i-am-on-in-c-sharp

Request.ApplicationPath :   /virtual_dir
Request.CurrentExecutionFilePath :  /virtual_dir/webapp/page.aspx
Request.FilePath :  /virtual_dir/webapp/page.aspx
Request.Path :  /virtual_dir/webapp/page.aspx
Request.PhysicalApplicationPath :   d:\Inetpub\wwwroot\virtual_dir\
Request.QueryString :   /virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.AbsolutePath :  /virtual_dir/webapp/page.aspx
Request.Url.AbsoluteUri :   http://localhost:2000/virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.Host :  localhost
Request.Url.Authority : localhost:80
Request.Url.LocalPath : /virtual_dir/webapp/page.aspx
Request.Url.PathAndQuery :  /virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.Port :  80
Request.Url.Query : ?q=qvalue
Request.Url.Scheme :    http
Request.Url.Segments :  /
    virtual_dir/
    webapp/
    page.aspx

Apr 8, 2014

MS SQL server administration tips

When you backup DB on SQL server A and restore it on SQL server B you may encounter problems.

Here is some tips that have helped me.

User that you have put in your connection string must be:
1. Delete it from Security / Users of your Database
2. If does not exists in SQL Server B Security / Users create it
3. DO NOT MAKE any user mapping of this user in step 2. Just create user
4. Go to Properties of SQL Server B and select Files. Change DB owner to your conn.str. user.

This should work now.

Generally you should have dbo owner & Public rights for your user in user mapping in Security tab of your database.

Step 1 is obligatory ! Proven ...




http://www.mssqltips.com/sqlservertip/2620/steps-to-drop-an-orphan-sql-server-user-when-it-owns-a-schema-or-role/

Apr 1, 2014

DotNetNuke - tips when copying existing Dnn to another server

You want to copy database and DNN folder to another web server and SQL server.
If you think you fixed conn. string and DNN keeps showing Install wizard make sure to do bellow steps.
SQL:
1. Drop user that is used for conn. string and recreate it on SQL server with DBO rights. Assign it to your database
2. Add in table PortalAlias your new domain because it probably changed.

Web.config
1. Use IIS section Conn.string & AppSettings to change conn.strings. Use  .   for local SQL and DON'T use integrated security since IIS does not work under them.ms

Verify in web.config did IIS designer screwed up conn string section.

Mar 17, 2014

ASP.NET WebForms - Client Report Definition - dynamically generate PDF presentation of RDLC from code

using Microsoft.Reporting.WebForms;

....


LocalReport localReport = new LocalReport();

            localReport.ReportPath = @"c:\Users\sbencetic\Documents\Visual Studio 2012\Projects\WebApplication2\Report1.rdlc";
            //ReportDataSource reportDataSource = new ReportDataSource("Customers", Customers.GetAllCustomers());

            //localReport.DataSources.Add(reportDataSource);
            string reportType = "Excel";
            string mimeType;
            string encoding;
            string fileNameExtension;

            //The DeviceInfo settings should be changed based on the reportType
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx
            string deviceInfo =
            "<DeviceInfo>" +
            "  <OutputFormat>PDF</OutputFormat>" +
            "  <PageWidth>8.5in</PageWidth>" +
            "  <PageHeight>11in</PageHeight>" +
            "  <MarginTop>0.5in</MarginTop>" +
            "  <MarginLeft>1in</MarginLeft>" +
            "  <MarginRight>1in</MarginRight>" +
            "  <MarginBottom>0.5in</MarginBottom>" +
            "</DeviceInfo>";

           
            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;

            //Render the report
           
            renderedBytes = localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);
            Response.AddHeader("content-disposition", "attachment; filename=NorthWindCustomers." + fileNameExtension);
           
            Page.Response.BinaryWrite(renderedBytes);                      


JQuery training

http://try.jquery.com/

Windows desktop - where is my appsettings in app.config ?

After long time working with web I got frustrated with trivial thing.
You can not open App.Config and simply write down your appsettings.
In windows desktop trick is to go through project properties then select Setting and use VS editor.

Mar 6, 2014

Windows 8.1 - can't save file to c:\Windows

Microsoft has increased out of the box security of Windows 8.1

By default user even as local admin does not have Full Control on some system folders like c:\Windows.

You can google solution like this:

http://www.thewindowsclub.com/take-ownership-windows-8

Yet this didn't gave me all answers.

Follow these steps:

1. On folder you wish right click
2. Select Security
3. Select Advanced
4. On the top change owner to yourself:     domain\username
5. Apply
6. Repeat step 1.
7. Edit
8. Locate yourself in user list and give Full control

Feb 27, 2014

SQL Compact Edition tips & tricks (ADO.NET)

Support for SQL Compact Edition is ... well sparse. It's one of those unwanted child's of Microsoft that he tries quickly to forget.
That means you'l have pain if you choose that way.
Just few years ago making local database in VS 2008 was child's game. Everything was there, project Data template, designer.
Now in VS 2013 it's hell.
At the moment if you need some kind of local database you can use "Service-based database" VS template.
It uses MDF & LDF files architecture from SQL server. I'm not clear how can you distribute this database to application users. There is some talk about special licence concerning use of this type of database.
Another approach is to dive into SQL CE fog.

1. Using Extensions & Updates, find and install third-party SQL Compact Toolbox.
Careful people say it's full of bugs and not well maintained.

2. Install NuGet package "Microsoft SQL Server Compact Edition"

3. Using SQL Compact Toolbox create new local SDF file.

4. Create connection string:

<add name="Application" connectionString="Data Source=|DataDirectory|\SQLCEv2.sdf;" providerName="System.Data.SqlServerCe.4.0"/>

For more info about DataDirectory folder substition read:

Folder substitution in DataSource property of Connection string:

http://social.msdn.microsoft.com/Forums/sqlserver/en-US/0712dd47-8437-4c84-b27e-2b12fddf2153/what-is-the-datadirectory-in-data-source-datadirectorynorthwindsdf?forum=sqlce


5. ADO.Net should work now:

string conStr = ConfigurationManager.ConnectionStrings["Application"].ToString();
            SqlCeConnection con = new SqlCeConnection(conStr);
            con.Open();
            SqlCeCommand cmd = new SqlCeCommand("insert into [Product] (Name) VALUES('Sinisa')", con);
            cmd.ExecuteNonQuery();
            con.Close();


Instead of ADO.NET you can use NPoco with no problem.

Feb 20, 2014

C# - throwing exceptions in catch block ?

Tricky question from job interview.

Will in given code finally be executed ?

string t = "x";
            try
            {
                try
                {
                    int i = int.Parse(t);
                    Console.WriteLine(i);
                }
                catch (FormatException e)
                {
                    Console.WriteLine(e.Message);
                    throw new ApplicationException("new exception...");
                }
                finally
                {
                    Console.WriteLine("finally");
                }
            }
            catch (Exception)
            {
                Console.WriteLine("handled exception...");
            }
            Console.ReadLine();

Yes it will but ONLY if new exception from catch block is handled in outer try block.

Result:

FormatException
Finally
Handled exception


In this case when outer try block is missing finally will not execute:

string t = "x";

                try
                {
                    int i = int.Parse(t);
                    Console.WriteLine(i);
                }
                catch (FormatException e)
                {
                    Console.WriteLine(e.Message);
                    throw new ApplicationException("new exception...");
                }
                finally
                {
                    Console.WriteLine("finally");
                }
            Console.ReadLine();


To conclude be very careful with code you write in your catch block.
It should not employ any kind of complexity that mighty throw exception!

Jan 29, 2014

WCF & IIS tips

When clean WCF project is initially created and hosted on server/local IIS this might be necessary to configure:

  • On entire folder in Security Tab give rights for IIS_IUSRS control
  • In IIS on Authentication enable Forms authentication

Also if you reference 32-bit DLL's like I did with Microsoft Script Control you need to enable 32 bit applications on advanced properties of website application pool.



Jan 20, 2014

Powershell - replace text in file(s) & custom functions in separate script

PowerShell example how to replace string and use custom function.
On bottom is example that uses regex expression for replace.

."c:\Users\sinisabencetic\Dropbox\*******\Dcs5Net\dcs5net-lib.ps1"
<# AdServer root folder
#>
$devRoot = "c:\Development\DCS5Net\trunk\WebSite\Config\";
$target = $devRoot + "AppSettings.config"
<# This is syntax for calling parameter less functions#>
DisableFVB
DisableGF
<# Enable FVB config #>
(Get-Content $target) | Foreach-Object {
$_ -replace '<appSettings>',
'<appSettings><add key="FVBPortal" value="True"/>'
} | Set-Content $target

dcs5net-lib.ps1

function DisableFVB
{
<# Disable FVB config #>
<#  If exists commented remove it
#>
(Get-Content $target) | Foreach-Object {
$_ -replace '<!--<add key="FVBPortal" value="True"/>-->',
   ''
} | Set-Content $target <#
If exists uncommented remove it
#>
(Get-Content $target) | Foreach-Object {
$_ -replace '<add key="FVBPortal" value="True"/>',
   ''
} | Set-Content $target
}


This code replaces attribute value contents. It expects chars or \ in match expression and replaces it with contents of variable provided as argument of function.

function FixAppSett($pathToReport)
{
$webconfig = "c:\Development\DCS5Net\trunk\WebSite\web.config"
(Get-Content $webconfig) | Foreach-Object { $_ -replace "(<add key=`"OrdnerBerichte`" value=`")([a-zA-Z\\]+)(`"/>)","`$1$pathToReport`$3"
} | Set-Content $webconfig
}

Jan 17, 2014

Crystal Reports 13.0.2000.0 with Visual Studio 2013

Website ASP.NET 4.0 uses Crystal Reports 13.0.2000.0
They are referenced in web.config like this:

        <add assembly="CrystalDecisions.CrystalReports.Engine, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/>
        <add assembly="CrystalDecisions.ReportSource, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/>
        <add assembly="CrystalDecisions.Shared, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/>
        <add assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/>
        <add assembly="CrystalDecisions.Windows.Forms, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/>
        <add assembly="CrystalDecisions.ReportAppServer.ClientDoc, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/>-->
       
Website was created and maintained on colleague's machine.
I checked it out from source control.
Solution did not build.
Compiler could not resolve Crystal assembly:

CrystalDecisions.ReportAppServer.ClientDoc

Of course, I had to install Crystal Reports assemblies because they don't exists in bin folder.
BTW here is detail explanation where .NET compiler searches for referenced assemblies:

http://stackoverflow.com/questions/981142/dll-in-both-the-bin-and-the-gac-which-one-gets-used

I searched for Crystal assemblies here:

http://scn.sap.com/docs/DOC-7824

Make sure to download "Install executable" from first column.
You can not self-extract it, it will fail.
Right click on EXE and choose extract.
Then start setup.

Crystal will properly register both in GAC and in Visual studio.

Do NOT use MSI packages runtimes!
They will install but you will not be able to reference them. Worst thing is that you can find them in GAC and even copy. Nothing will work. Tried it. Stick to biggest package that integrates into IDE.



http://msdn.microsoft.com/en-us/library/bb398202.aspx

http://scn.sap.com/message/14688220#14688220




Jan 14, 2014

Web Essentials 2013

Yea it's stupid, people waited for it for ages... but I just want it to go away...
Surprisingly it took me to many seconds to find out how ...

http://blogs.msdn.com/b/webdev/archive/2013/06/28/browser-link-feature-in-visual-studio-preview-2013.aspx

Jan 13, 2014

Javascript tips & tricks


  • Coll way to join strings:


var base = 'http://acme.com',
    action = 'get',
    param = 'apple';
var fullUrl = [base,action,param].join('');
alert(fullUrl);


  • Closure ?

http://stackoverflow.com/questions/111102/how-do-javascript-closures-work

  • Private & public members in JSON

var myWidget = function(){  
      //private method declaration
    var myShow;
    //private method body
    myShow = function(){ return "I'm private!"; }
    //public method declaration
    this.Show = function Show() { alert(["I'm calling ->",myShow()].join('')); }
    //this.Show = function Show() { alert('xx'); }
}
var coolWidget = new myWidget();
//this works
coolWidget.Show();
//this does not works. It's private member!
coolWidget.myShow();
                          •  Use Console.Log() for quick debugging instead of annoying alert