JavaScript add bookmark

無法查看此摘要。請 按這裡查看文章。

Windows command – backup & remove all IIS log

  1. Download Source code by package (must) ,  Unzip BackupLog Folder to C:\  (Total 5 files: 7z.dll , 7z.exe , ufind.exe,  BackupLog.bak, BackupLog_Chinese.bak)
  2. Download sample batch (must) based on date and time format.  US or Chinese
    Chinese format , US Format
  3. Check your IIS Log path location was under the “C:\inetpub\logs\LogFiles”  , if not please modify sample batch or modify the parameter whatever you want.
  4. [Option] Setting task scheduler run the batch file
Dropbox share link OR Download Source code by package

A Friendly remind: If choose task scheduler to perform batch job, please ensure the account log-in on the server once and had permission on log folder.

[Umbraco] Replace p tags start with root block in TinyMCE Editor

Purpose : Replace <p> to <div>+<br/>

Version: 4.X   ,   File : /config/tinyMceConfig.config

Add TinyMCE configuration key under the <customConfig> element.

<config key="force_p_newlines">false</config>
<config key="force_br_newlines">true</config>    
<config key="forced_root_block">div</config>   

Recycle Application pool.

[Umbraco] Bug in calculating image dimensions in TinyMCE

Encounter in version  4.5.2 & 4.7.1

Update one existing picture by TinyMCE , when change height or width , another one will be changes to NaN.

How to fix:

Add rel in allowedAttributes element

File : /config/umbracoSetting.config

<allowedAttributes>alt,title,border,class,style,align,id,name,onclick,usemap,rel</allowedAttributes>

2. Ensure img element allw rel attribute ,

File : /config/tinyMCEConfig.config

img[id|dir|lang|longdesc|usemap|style|class|src|onmouseover|onmouseout|border|alt=|title|hspace|vspace|width|height|align|umbracoorgwidth|umbracoorgheight|onresize|onresizestart|onresizeend|rel],

[Umbraco] Add User with hashed password & check unique loginname

protected static bool addUmbracoUser(string loginName, string userName, string password)
{
if (ensureUniqueLoginName(account))
{
User u = umbraco.BusinessLogic.User.MakeNew(userName, loginName.Trim(), hashPassword(password), new List < UserType> ());
u.addApplication("content");
u.addApplication("media");
u.addApplication("users");
u.addApplication("settings");
u.addApplication("developer");
u.addApplication("members");
u.Save();
return true;
}
else
{ return false; }
}

private static bool ensureUniqueLoginName(string loginName)
{
umbraco.BusinessLogic.User[] u = umbraco.BusinessLogic.User.getAllByLoginName(loginName);
if (u.Length != 0)
{
return false;
}
return true;
}

private static string hashPassword(string password)
{
HMACSHA1 hash = new HMACSHA1();
hash.Key = Encoding.Unicode.GetBytes(password);

string encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
return encodedPassword;
}


Reference: http://our.umbraco.org/wiki/reference/api-cheatsheet/users,-user-types-and-permissions/add-user-with-hashed-password

RadControls – RadGrid export to Excel with text format


void btnExport_Click(object sender, ImageClickEventArgs e)
{
rgGrid.ExcelExportCellFormatting += new OnExcelExportCellFormattingEventHandler(rgKBuser_ExcelExportCellFormatting);
rgGrid.MasterTableView.ExportToExcel();

}
void rgKBuser_ExcelExportCellFormatting(object sender, ExcelExportCellFormattingEventArgs e)
{
e.Cell.Style["mso-number-format"] = @"\@";
}

Reference: http://www.telerik.com/help/aspnet-ajax/grid-html-export.html

Security issue – HttpResponse.Redirect in Umbraco appear trace information


If use below solution to implement redirection on your site.
Please ensure hack ~/default.aspx to disable the trace parameter.
<%@ Page language="c#" Codebehind="default.aspx.cs" AutoEventWireup="True" Inherits="umbraco.UmbracoDefault" trace="false" validateRequest="false" %>
Please use web debugging tool to check your umbraco site , e.g. Fiddler
You can fellow below step .
1. open Fiddler
2. visit the redirect URL .  
3. in WebView tab , will appear all trace information , like Server Variables , Session State

IIS 7 To export/import a single website

Step1 Export:
%windir%\system32\inetsrv\appcmd list site “MyWebsite” /config /xml > c:\mywebsite.xml

Step2 Hack xml:
Hack name & id attributes in second site element , c:\mywebsite.xml

e.g.
<site name="mywebsite" id="1" serverAutoStart="true">
to
<site name="mywebsite2" id="2" serverAutoStart="true">

Step3 Import:
%windir%\system32\inetsrv\appcmd add site /in < c:\mywebsite.xml

Reference: :http://www.microsoftpro.nl/2011/01/27/exporting-and-importing-sites-and-app-pools-from-iis-7-and-7-5/


Note for purpose of create new website and keep original website

  1. Manually add new application pool & set new applicationPool to your website.
  2. Set attribute of serverAutoStart to “false”
  3. Set new attribute to bindingInformation.

[Umbraco] Ensure/Check unique user LoginName


private static bool ensureUniqueLoginName(string loginName)
{
umbraco.BusinessLogic.User[] u = umbraco.BusinessLogic.User.getAllByLoginName(loginName);
if (u.Length != 0)
{
return false;
}

return true;
}

[Umbraco] Add more than one TinyMCE datatype on page or usercontrol

        private void addTinyMCEControl(Control targetPlaceHolder, TabPage tp)
{

DataTypeDefinition htmlEditorDataType =
DataTypeDefinition.GetDataTypeDefinition(new Guid("A521511A-7BEE-4C5B-8D7B-4B06B57392B3"));

//The other way can get datatype id directly.
//DataTypeDefinition htmlEditorDataType = DataTypeDefinition.GetDataTypeDefinition(-87);

TinyMCE umbracoTinyMCEEditor = (TinyMCE)htmlEditorDataType.DataType.DataEditor;

string toolbar_id = string.Empty;

if (umbracoTinyMCEEditor != null)
{
if (umbracoTinyMCEEditor.config["umbraco_toolbar_id"] != null)
umbracoTinyMCEEditor.config.Remove("umbraco_toolbar_id");
toolbar_id = "tinyMCEMenu_" + targetPlaceHolder.ClientID;
umbracoTinyMCEEditor.config.Add("umbraco_toolbar_id", toolbar_id);
targetPlaceHolder.Controls.Add(umbracoTinyMCEEditor);
tp.Menu.NewElement("div", toolbar_id, "tinymceMenuBar", 0);
}
}


Reference:


[LINQ] Get child controls


using System.Collections.Generic ;
using System.Linq;
///
/// Get all child & sub-child controls within a control by type
///

/// The control we're searching in form/page.
/// The control type we're looking for (i.e; TextBox)
///
public IEnumerable < Control > GetAllChildControls(Control control, Type type = null)
{
var controls = control.Controls.Cast< Control >();

if (type == null)
return controls.SelectMany(ctrl => GetAllChildControls(ctrl, type)).Concat(controls);
else
return controls.SelectMany(ctrl => GetAllChildControls(ctrl, type)).Concat(controls).Where(c => c.GetType() == type);
}



//How to use.
IEnumerable< Control > textBoxControls = GetAllChildControls(this, typeof(TextBox));
IEnumerable< Control > allConrols = GetAllChildControls(this);


Reference : http://www.dreamincode.net/code/snippet5634.htm

[Reflection] Get and Set values of Properties


object sampleObj = new object();
foreach (PropertyInfo info in sampleObj.GetType().GetProperties())
{
// To Get value
if (info.CanRead)
{
object o = info.GetValue(sampleObj, null);
}


// To Set value
object myValue = "Something";
if (info.CanWrite)
{
info.SetValue(sampleObj, myValue, null);
}
}

[Exception] Collection was modified; enumeration operation may not execute

Solution : replace for each loop to standard loop

 


ArrayList items = new ArrayList();

//foreach (var item in items)
//{
// //do something
//}

for (int i = 0; i < items.Count; i++)
{
//do something
}


Referece: http://alitarhini.wordpress.com/2011/04/06/collection-was-modified-enumeration-operation-may-not-execute/

SQL scripts - Delete all Tables, Procedures, Views and Functions

Delete All Tables


DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql
WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec SP_EXECUTESQL @Sql
FETCH NEXT FROM @Cursor INTO @Sql
END
CLOSE @Cursor DEALLOCATE @Cursor
GO
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO



Delete All Stored Procedures



declare @procName varchar(500)
declare cur cursor
for select [name] from sys.objects where type = 'p'
open cur

fetch next from cur into @procName
while @@fetch_status = 0
begin
if @procName <> 'DeleteAllProcedures'
exec('drop procedure ' + @procName)
fetch next from cur into @procName
end

close cur
deallocate cur

Delete All Views



declare @procName varchar(500)
declare cur cursor
for select [name] from sys.objects where type = 'v'
open cur

fetch next from cur into @procName
while @@fetch_status = 0
begin
exec('drop view ' + @procName)
fetch next from cur into @procName
end
close cur
deallocate cur


Delete All Functions



declare @procName varchar(500)
declare cur cursor
for select [name] from sys.objects where type = 'fn'
open cur

fetch next from cur into @procName
while @@fetch_status = 0
begin
exec('drop function ' + @procName)
fetch next from cur into @procName
end

close cur
deallocate cur

Umbraco v4 - delete Recycle Bin by T-SQL


--Verify the number of nodes returned is the save as the number of nodes that is in the Recycle Bun
--select count(*) from umbracoNode where path like '%-20%' and id!=-20

begin transaction
DELETE FROM umbracoRelation WHERE parentId IN (SELECT id FROM umbracoNode WHERE path LIKE '%-20%' AND id != -20)
DELETE FROM umbracoRelation WHERE childId IN (SELECT id FROM umbracoNode WHERE path LIKE '%-20%' AND id != -20)
delete from cmsPreviewXml where nodeId in (select id from umbracoNode where path like '%-20%' and id!=-20)
delete from cmsContentVersion where contentId in (select id from umbracoNode where path like '%-20%' and id!=-20)
delete from cmsDocument where nodeId in (select id from umbracoNode where path like '%-20%' and id!=-20)
delete from cmsContentXML where nodeId in (select id from umbracoNode where path like '%-20%' and id!=-20)
delete from cmsContent where nodeId in (select id from umbracoNode where path like '%-20%' and id!=-20)
delete from cmsPropertyData where contentNodeId in (select id from umbracoNode where path like '%-20%' and id!=-20)
delete from umbracoRelation where parentId in (select id from umbracoNode where path like '%-20%' and id!=-20)
delete from umbracoRelation where childId in (select id from umbracoNode where path like '%-20%' and id!=-20)
delete from umbracoDomains WHERE domainRootStructureID in (SELECT id FROM umbracoNode WHERE path like '%-20%' and id != -20)
delete from cmsTask where nodeid in (SELECT id FROM umbracoNode WHERE path like '%-20%' and id != -20)
delete from umbracoUser2NodePermission where nodeId in (SELECT id FROM umbracoNode WHERE path like '%-20%' and id != -20)
-- delete the XML nodes....
delete from umbracoNode where path like '%-20%' and id!=-20
commit transaction
--Verify is done , replace rollback to commit

--Reference : http://our.umbraco.org/forum/using/ui-questions/26114-Delete-recycle-bin-problem?p=1

Entity Framework - not have a primary key defined

Condition :
Add ADO.NET Entity Data Model > Right click >  update Model from database > pick table/view

VS Output:
The model was generated with warnings or errors.
Please see the Error List for more details. These issues must be fixed before running your application.

Open edmx file with XML editor have error :








Solution:


SELECT ISNULL((ROW_NUMBER() OVER (ORDER BY column1 DESC)), 0) AS ‘ID’, column1, column2
FROM  dbo.sample


 


Reference link :
http://www.hilmiaric.com/?p=95
http://www.ericsdavis.net/index.php/2009/03/14/entity-framework-and-primary-key-inference/
http://stackoverflow.com/questions/745341/can-sql-server-views-have-primary-and-foreign-keys

Install SQL Server 2008 R2 exception

install_SQLServer2008R2_Error

Error details:

See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration section handler for userSettings/Microsoft.SqlServer.Configuration.LandingPage.Properties.Settings: Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified. (C:\Users\RichardSRHan\AppData\Local\Microsoft_Corporation\LandingPage.exe_StrongName_ryspccglaxmt4nhllj5z3thycltsvyyx\10.0.0.0\user.config line 5) ---> System.IO.FileNotFoundException: Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified.
File name: 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
   at System.Configuration.TypeUtil.GetTypeWithReflectionPermission(IInternalConfigHost host, String typeString, Boolean throwOnError)
   at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.Init(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord)
   at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.InitWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord)
   at System.Configuration.RuntimeConfigurationRecord.CreateSectionFactory(FactoryRecord factoryRecord)
   at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredHere)

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

   --- End of inner exception stack trace ---
   at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredHere)
   at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
   at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
   at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
   at System.Configuration.ConfigurationManager.GetSection(String sectionName)
   at System.Configuration.ClientSettingsStore.ReadSettings(String sectionName, Boolean isUserScoped)
   at System.Configuration.LocalFileSettingsProvider.GetPropertyValues(SettingsContext context, SettingsPropertyCollection properties)
   at System.Configuration.SettingsBase.GetPropertiesFromProvider(SettingsProvider provider)
   at System.Configuration.SettingsBase.GetPropertyValueByName(String propertyName)
   at System.Configuration.SettingsBase.get_Item(String propertyName)
   at System.Configuration.ApplicationSettingsBase.GetPropertyValue(String propertyName)
   at System.Configuration.ApplicationSettingsBase.get_Item(String propertyName)
   at Microsoft.SqlServer.Configuration.LandingPage.LandingPageForm.OnLoad(EventArgs e)
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl()
   at System.Windows.Forms.Control.WmShowWindow(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


************** Loaded Assemblies **************
mscorlib
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5448 (Win7SP1GDR.050727-5400)
    CodeBase: file:///C:/Windows/Microsoft.NET/Framework64/v2.0.50727/mscorlib.dll
----------------------------------------
LandingPage
    Assembly Version: 10.0.0.0
    Win32 Version: 10.50.1600.1 ((KJ_RTM).100402-1539 )
    CodeBase: file:///F:/x64/LandingPage.exe
----------------------------------------
System.Windows.Forms
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5446 (Win7SP1GDR.050727-5400)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5453 (Win7SP1GDR.050727-5400)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Drawing
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5420 (Win7SP1.050727-5400)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
Microsoft.SqlServer.Configuration.Sco
    Assembly Version: 10.0.0.0
    Win32 Version: 10.50.1600.1 ((KJ_RTM).100402-1539 )
    CodeBase: file:///F:/x64/Microsoft.SqlServer.Configuration.Sco.DLL
----------------------------------------
Microsoft.SqlServer.Chainer.Infrastructure
    Assembly Version: 10.0.0.0
    Win32 Version: 10.50.1600.1 ((KJ_RTM).100402-1539 )
    CodeBase: file:///F:/x64/Microsoft.SqlServer.Chainer.Infrastructure.DLL
----------------------------------------
System.Xml
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5420 (Win7SP1.050727-5400)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Xml/2.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------
Accessibility
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/Accessibility/2.0.0.0__b03f5f7f11d50a3a/Accessibility.dll
----------------------------------------
Microsoft.SqlServer.Management.Controls
    Assembly Version: 10.0.0.0
    Win32 Version: 10.50.1600.1 ((KJ_RTM).100402-1539 )
    CodeBase: file:///F:/x64/Microsoft.SqlServer.Management.Controls.DLL
----------------------------------------
System.Configuration
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5420 (Win7SP1.050727-5400)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Configuration/2.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------

************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.

For example:

<configuration>
    <system.windows.forms jitDebugging="true" />
</configuration>

When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.

 

 

Solution:

delete the folder %userprofile%\local settings\application data\Microsoft_Corporation , re-install