13/12/2012

How to fix common errors in sitecore





How to fix common errors in sitecore


Check Connection strings in \Website\App_Config\ConnectionStrings.config


The network path was not found
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.Exception Details: System.ComponentModel.Win32Exception: The network path was not foundSource Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 

[Win32Exception (0x80004005): The network path was not found]

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)]
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection     owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +671
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection     owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +116
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1012
   System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6711619
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +152
   System.Data.SqlClient.SqlConnection.Open() +229
   System.Web.DataAccess.SqlConnectionHolder.Open(HttpContext context, Boolean revertImpersonate) +150
   System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation) +4874450
   System.Web.Security.SqlMembershipProvider.GetUser(String username, Boolean userIsOnline) +1729
   Sitecore.Security.SitecoreMembershipProvider.GetUser(String username, Boolean userIsOnline) +51
   System.Web.Security.Membership.GetUser(String username, Boolean userIsOnline) +175
   Sitecore.Security.Domains.Domain.CreateAnonymousUserIfNeeded() +56
   Sitecore.Pipelines.Loader.EnsureAnonymousUsers.Process(PipelineArgs args) +143
   (Object , Object[] ) +80
   Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) +191
   Sitecore.Nexus.Web.HttpModule.Application_Start() +160
   Sitecore.Nexus.Web.HttpModule.Init(HttpApplication app) +619
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +530
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +304
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr     appContext, HttpContext context) +404
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +475

[HttpException (0x80004005): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12881540
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12722601






It’s because .net framework 4.5 is installed on the server
Change the  \Website\Web.config

<setting name=”Login.RememberLastLoggedInUserName” value=”false” />

 Server Error in '/' Application.


Object of type 'System.Int32' cannot be converted to type 'System.Web.Security.Cryptography.Purpose'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentException: Object of type 'System.Int32' cannot be converted to type 'System.Web.Security.Cryptography.Purpose'.

Source Error: 
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 
 
[ArgumentException: Object of type 'System.Int32' cannot be converted to type 'System.Web.Security.Cryptography.Purpose'.]
   System.RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast) +185
   System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig) +122
   System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +206
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +126
   Sitecore.SecurityModel.Cryptography.CookieProtectionHelperWrapper.Encode(CookieProtection cookieProtection, Byte[] buf, Int32 count) +175
   Sitecore.sitecore.login.LoginPage.WriteCookie(String name, String value) +94
   Sitecore.sitecore.login.LoginPage.Login_LoggingIn(Object sender, LoginCancelEventArgs e) +133
   System.Web.UI.WebControls.Login.AttemptLogin() +108
   System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +93
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +84
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804



Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929



20/09/2012

How I solved 'permission to view' issue after publishing my website with git to windows Azure website


I  published my website (MVC 3.0) with git to Azure for the first time. when I browsed my website I got the following message:

You do not have permission to view this directory or page.

After spending an hour. I tried to publish it with .net by using publish profile. After following the  publish steps.I noticed that in the preview tab. It returns an error when you click on preview. I had broken js file in my solution.after removing that. everything works fine.

My solution for you if you got the same error
1- Build your solution in release mode.
2- Try to publish it with using publish option of project then check if you can preview all the files.



Resources:
https://www.windowsazure.com/en-us/develop/net/common-tasks/publishing-with-git
https://www.windowsazure.com/en-us/develop/net/tutorials/web-site-with-sql-database

19/09/2012

How to set function keys in windows to do the standard functions on mac!

I started to use windows on mac through boot camp. It's so weird, but it feels really great. The horrible thing is function keys don't work as you expected unless you do the following steps.

1- Open Boot Camp
2- Go To Keyboard Tab
3- Select the check box : Use all F1, F2, etc. keys as standard function keys.

source:
http://forums.macrumors.com/showthread.php?t=400404

07/09/2012

Add or Update KeyValuePair in Dictionary


question:

What's the easiest way to add new key or update its value if it's already exists?

you can check if the key contains in the keys collection and then update the value of key and if the key doesn't exists you can add new item, but is it a best way ?

 

var tempDic = new Dictionary<string, string>();
                    
if (tempDic.ContainsKey("Key1"))
{
tempDic["key1"] = "value";
}
tempDic.Add("key1","value");



The best way is :


var tempDic = new Dictionary<string, string>();
tempDic["key1"] = "value";


you cannot use Add(TKey key, TValue value) method and you will get the following exception



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

20/05/2012

Layouts with Razor Engine dll

Razor engine is a library that you can use to generate your cshtml files. For example you can use it for generating emails. It gives you the ability to add a layout (Masterpage) and then generate your templates based on the Layout.You can easily add it by nuget (add library package reference) .

using (var service = new TemplateService())
       {
var style = "<style type=\"text/css\">hr {color:sienna;}p {margin-left:20px;}</style>";
var layoutTemplate = style + "<h1>Main</h1>@RenderSection(\"Child1\")@RenderSection(\"Child2\")";
var childTemplate = "@{ _Layout =  \"Parent\"; }@section Child1 {<p>child1 </p>}@section Child2 {<p>child2 deatils <a href=\"http://www.google.com\">Google</a></p>}";
service.Compile(layoutTemplate, null, "Parent");
var result = service.Parse(childTemplate);
       }



You can download sample from Here:
https://github.com/Azadehkhojandi/RazorEngineTest

Resources:
https://github.com/Antaris/RazorEngine

12/04/2012

How to solve MVC remote validation caching problem in IE








If you trace the requests in IE you may notice that it doesn't fire validation action method for every change. But, It fires validation method for every single change in the Firefox.
It should return 200 HTTP Code for every call but, in IE it returns 304 for the inputs which you recently worked with it. The reason is IE caches the result of requests so it returns the previous request without running validation method.


Simple fix is Adding  OutputCache(Location = OutputCacheLocation.None, NoStore = true) attribute to action method.


Sample:

public class EmailModel

{
[Remote("EmailAlreadyExists", "MyController", AdditionalFields = "CurrentEmail")]
public string Email { get; set; }
public string CurrentEmail { get; private set; }
}

[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public ActionResult EmailAlreadyExists(string email, string currentEmail)
{
var result = false;
       // do something and set result
       return Json(result, JsonRequestBehavior.AllowGet);    
}

Reference:
http://stackoverflow.com/questions/7966726/asp-net-mvc3-remote-validation-calls-not-firing

10/04/2012

How to handle “A potentially dangerous Request.Form value was detected from the client…” in MVC


There are different ways to handle this error. Depends on your requirement you can chose how to solve it.

1- Handle it for a specific property

Add [AllowHtml] to model property.  Like following

public class InvitationViewModel
       {

[AllowHtml]
public string Message { get; set; }

}

2- Handle it on Action Method

Add [ValidateInput(false)] to the action. Like Following
[HttpPost, ValidateInput(false)]
public ActionResult Create(ObjectId id, string comment)
{
//do something
}



3- Handle it Globally in Global.asax.cs

protected void Application_Error()
              {
                     Exception lastError = Server.GetLastError();
                     if (lastError is HttpRequestValidationException)
                     {
                           //redirect to a static page and show proper error message
                     }
                                }

4- Add Regex and show proper error message to the user when user enters xml codes ‘<>’ in their textbox 

Add [RegularExpression] to model property.  Like following

[RegularExpression(@"/?\w+\s+[^>]*",ErrorMessage = "you are not allowed to enter HTML tags")]
public string Subject { get; set; }



5- Change  input box and use different control