Who is talking?


Verify your website accessibility

over 2 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Web accessibility is the practice of ensuring that your website is interactive and accessible to even people with disabilities. Many countries provide laws protecting the rights of disabled persons, therefore it becomes really important to design and develop the website in compliance with those laws and follow web accessibility as de-facto.The blog helps to test your web accessibility.1. Open chrome browser and browse any website. Open developer tools and click on Audit tab. Scroll to Audits section and check the 'Accessibility' option.Web accessibility check in Chrome browser2. Once you click on 'Run audits' button, you will see a message(as shown below). Don't worry, auditing has started.Starting auditing of website3. Once audit is completed, it will generate audit report(as shown below)Audit report for web accessibilityHave a great day !!

Creating and Installing Sitecore Packages

almost 3 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Creating and Installng Sitecore PackageCreate Sitecore Package1. Open Sitecore(from where you would like to create package) and click on Package Designer2. Once Package designer panel is opened, click on Item statically and provide all required details as shown below3. After clicking on 'Item statically' option, a popup will open. Choose selected items and click on 'Add with SubItems' or 'Add Items' buttons    a. clicking on 'Add Item' will only include selected item and not child items    b. clicking on 'Add with subitems' will include selected Item and its child items4. Click on 'Generate Zip' option which will generate the package in .zip format5. Download the .zip file of sitecore package by clicking on download buttonInstalling Sitecore Package1. Open Sitecore (instance where you would like to install package) and click on 'Installation Wizard'2. upload the .zip package to install and click next to install3. During install, Sitecore popup will appear for inputsa. Override - This option replace the entire subtree with the subtree in the package. You have to be very careful while selecting Override option as it may delete all child items if you have not added the Item with child items while creating package. b. Merge - This is safe option which will find the matching items and versions with those from the package but do not replace any subitemsPlease feel free to post your comments in case you see any concerns or like to thank you :).

Quick Tutorial - Setup a Solr instance

over 3 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Before we start installing Solr instance on any machine, we should be clear on few concepts.What is Solr?Solr is Apache's product and a fast open-source Java search server.Why we need it?Solr enables you to easily create search engine for websites, databases and files.How can we install it?You can download any version of Solr from http://archive.apache.org/dist/lucene/solr/. Steps to install after it is downloaded-Extract the downloaded Solr package and copy it on C or D drivePlease make sure latest version of Java is installed on machine. You can start Solr instance by below command: java -jar start.jarBy default, Solr will run on port 8983. However you can change it ../etc/Jetty.xml file. Look for <set name="port"><SystemProperty name="jetty.port" default="8983"></set> and change it.You can keep the below command in .bet file and run it automatically. "C:\solr-6.1.0\bin\solr" restart -h localhost -p 8984Please feel free to send email for any help.

Could not load file or assembly 'Microsoft.Web.Infrastructure'

almost 4 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Could not load file or assembly 'Microsoft.Web.Infrastructure, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.What 'Micorosoft.Web.Infrastructure' does?This dll lets HTTP modules register at run time.Solution to above problem:Copy 'Micorosoft.Web.Infrastructure' dll in bin folder of your project and this problem should be resolved. If you have .Net framework installed on machine, this dll should be present on it. You can search for this dll and copy it in your active project folder.  Alternatively, you can install this dll using nuget package managerPM> Install-Package Microsoft.Web.Infrastructure -Version 1.0.0Happy coding!!

WFFM: Save to Database

almost 5 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Web Forms For Marketers has become one of the essential component of Sitecore. Almost every website is using forms to capture the inputs from users and it is very common scenario to get the data stored in Database for reporting purpose. Here are few easy steps which can help you storing the form's data in SQL database.Download the WFFM - SQL Provider(Save To Database) and install it in Sitecore using Installation wizard. All physical files and Sitecore items will be stored in respective location.Once installed, you will notice that it has created a new Action under System-> Modules -> Web Forms for Marketers -> Settings -> Actions -> Save ActionsNow, we have to add connection string in configuration file which will help us storing the data in that database. You have to keep the name of connectionstring to 'wfm' only as same name is referred in WFFM module code.< add connectionstring="user id=your_db_user_id;password=your_db_password;Data Source=your_db_server;Database=your_db_name" name="wfm" >You are done.Now add the 'Save to Database' action on any WFFM form and start using it. Also validate the database and data should start getting stored in it.Furthermore, this module provides the capability of exporting the saved data in CSV format. We can do customization on it to export the data from different servers(CMS or CD) which I will explain in next article.Please don't hesitate to contact me at 'email.bajaj@gmail.com' for any Sitecore related query/scenario.

HTTP Compression and Performance tuning

over 5 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

With the advancement of technology and exceeding expectations of users, one has to be very careful designing a website. Performance is one of the key elements for success of an application. Even if, you have designed the application with uttermost care and rock solid architecture, there are few key areas in which you have to be really vigilant. HTTP Compression is one of those pivotal spaces.HTTP compression is the technique to compress static and dynamic content which improves the transfer speed and performance of a website.Steps to keep the compression ON for a website. Here the demonstration is given for IIS based website.1. Open IIS (inetmgr)2. Goto website. Right side will show all components of that website3. Click on 'Compression' module and verify that both the checkboxes are checked if you need static and dynamic content to be compressed.4. Click 'Mime Types' and check 'application/x-javascript' is added in the existing mime types. If not, add it.5. Reset IIS, browse website and verify that JS is getting compressed now.Web.Config SettingsHere are all the mime types and gzip information which should exist for a website if compression needed, either in IIS settings or in web.config.Note: Include it in web.config if configuration file also get deployed with every build.Section to include in <system.webserver></system.webserver><system.webServer><httpCompression> <staticTypes> <add mimeType="text/*" enabled="true" /> <add mimeType="message/*" enabled="true" /> <add mimeType="application/javascript" enabled="true" /> <add mimeType="application/x-javascript" enabled="true" /> <add mimeType="image/jpeg" enabled="true" /> <add mimeType="*/*" enabled="false" /> </staticTypes> <dynamicTypes> <add mimeType="text/*" enabled="true" /> <add mimeType="message/*" enabled="true" /> <add mimeType="application/javascript" enabled="true" /> <add mimeType="application/x-javascript" enabled="true" /> <add mimeType="image/jpeg" enabled="true" /> <add mimeType="*/*" enabled="false" /> </dynamicTypes> <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" dynamicCompressionLevel="4" /> </httpCompression></system.webServer>After compression is ON:Response header of a JS file being loaded in website. 'Content-Encoding: gzip' shows that it is compressed.Useful toolsThere are several webistes which can help you detect, if your website/CSS/JS is compressed or not. You should check css/js or website seperately to make sure that all static medias are compressed. One of the examples website is given here.Check CompressionFor further detail, you can contact me www.bajajsumit.com. Please share your feedback if you find the article useful.

Running dotnet on Linux

over 5 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Server: Linux, version SUSE 12To run dotnet code on Linux, the first and foremost task is to "Install Mono package on linux".Note: Mono is an open implementation of Microsoft's .Net framework, including compilers. It uses the same development libraries on Linux which are being used on Windows. Therefore, if you code and compiled some mono code on Linux,  it will work for Windows as well.      zypper is a package installation tool which is used in this scenario. If zypper is not available, check which package manager tool is installed on server. Furthermore, to verify if zypper is installed or not, type zypper on command line which will show all options if zypper is available on server else it will show 'command not found'.zypper ar -r http://download.opensuse.org/repositories/Mono/SLE_11_SP2/Mono.repoThe above command will download from mentioned URL in a new repository. Here 'ar' stands for 'add repo'.After adding it to repository, type 'zypper refresh' command, it will ask to install packages. Type the appropriate option and install the Mono packages.Once successful installation,       we are all set to run dotnet on linux server.Running first dotnet codeCreate a new test.cs file by typing following command.$cat>test.csNow open the file using any available editor. In this case it is 'vi' editor.vi test.csStarting writing the first dotnet code as shown below.      Information about 'vi' editor:Type 'i' to change it to insert mode.Type 'esc' to come out of insert mode.Type ':w' to write the file and save.Type ':q' to quit and come back to command line tool.       NOTE: If any exception appears like '!' is required to override the file. Type ":w!" to override the existing file and write the new text. OR Type ":q!" to override the existing file with new text and quit.C# code for 'test.cs':using System;namespace Test1{class Test1{static void Main(string[] args){Console.WriteLine("Hello World!!");}}}Once you have saved the file, its time to compile it. 'mcs' is command which is used for compiling the code.dev-server-linux-suse12:~ # mcs test.csAfter compilation is successfully completed, its time to run the application. As it is console project, '.exe' file will be created as output. 'mono' is the command used for running the test project.dev-server-linux-suse12:~ # mono test.exeHello World!!You are all set to run dotnet on Linux. Provide your valuable comments/suggestions.

Cannot alter the login 'sa', because it does not exist or you do not have permission.

over 5 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Working on projects, it can happen that 'sa' account gets locked. If it is on local machine OR development boxes, onus would be on you to fix it. If scripts and SQL steps are not working, this might help you fixing the issue.Steps to unlock 'sa' account and resetting the password.1. Open SQL Server Configuration Manager2. Select SQL Server Services -> 'SQL Server' service.3. Right click on 'SQL Server' service and click on "Startup Parameters". For 2008, server "Startup Parameters" are inside Advanced tab. 4. Add '-m' in startup parameters as shown above and click on 'Add'. This will put SQL server into 'Single User Mode' and local admin will have 'Super User' rights. For 2008, server you have to add ':-m' in the last of the existing query.5. Save the settings and Restart the service.6. Now open the SQL Server Management Studio and connect to database using 'Windows Authentication'.7. Goto Security -> sa -> Right click and open properties.8. Unlock the 'sa' account and reset the password.YOU ARE DONE!!**Important: Now to switch back to 'Mixed User Mode' where you can access the database using 'sa' account, remove the '-m' from 'Startup Parameters' which we added in above steps.

Setting up web server and continuous integration

almost 6 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Apart from creating website & app-pool in IIS, there are several steps which need to be performed when setting a new website on server.Setup Web ServerThere are few activities which you have to perform on Web Server:1. Install Web Deploy [Download]2. Install URL Rewrite [Download]3. Make Sure .Net Framework feature is ON in Windows features4. Create a standard user which could be used to deploy files to web server after successful build5. Open "services.msc" and check that 'Web Deployment Agent Service' is running with the standard user credentials created in Step 4.6. Run App pool and website with same standard user which is created in Step 47. Reset IIS ServerContinuous IntegrationThere are several tools which are being used for continuous integration but they perform same functions when we discuss about build and deployment. In this example, we are referring Jenkins [Download].If msdeploy or any relevant command is being used to deploy files on web server, same standard user credentials should be used to copy the content else it will throw unauthorized exception.Common ExceptionsAn item with the same key has already been added.Solution: It can be resolved by checking Mime types. There is a probability that same Mime type is being added by web.config which is there in IIS already. In IIS 8, there is not need to add Mime types manually.Website is appearing but css/font is not loading.Solution: Open dev tools(if its chrome browser, press F12 key) and check if in console you are getting errors like 404, 500 etc. Check if css/font files are present in the right folder. If gulp or grunt is being used, make sure it is compiling the files without exception.If any CMS is being used then there might be CMS related errors.Sitecore has no necessary permissions for reading/creating counters. OR Sitecore publishing screen is showing 'Initializing' but not publishing anything.Solution: Application pool user should be member of 'Performance Monitor User' group. Add user to this group and restart IIS. Even after this, if it does not work sitecore counter can be disabled by setting counter value to false. For example: <setting name"counters.enabled" value-"false"/>Let me know if you still get any exception. Have a nice day!!

Get all Items inheriting another template

almost 6 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Working on different templates and Sitecore items, its very common requirement to knowhow many items are created with a specific templatehow many template are inheriting a base template or another templateSitecore provide this feature out of box however you need to write query to fetch the required items.Open Sitecore IDE (http://localhost/sitecore/shell/default.aspx?xmlcontrol=IDE)Goto Tools -> XPath BuilderWrite XPath Expression:/sitecore/templates//*[contains(@__Base template,'{1FE1328B-375B-4548-A53E-344FA61ACC90}')]In result section, it should show all templates which are inheriting base template with ID {1FE1328B-375B-4548-A53E-344FA61ACC90}.Similarly, query /sitecore/content//*[@@templatename='Promotional Page'] should show all pages (under content) created with 'Promotional Page' template.On top of results, it shows the count of items and time taken to fetch the items.We can use fast query as well instead of query.Note: The above queries are example of specific requirement. Query can be modified to get required items according to project need.URL: Sitecore Query and Fast Query

Sitecore - Moving items from web to master

over 6 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

In most of the cases, generally you create items in master database and publish to web/production data. However, sometimes few items are in web database and not in master. Reason can be anything, like you might have deleted it in master but did not publish the parent item or due to some other reason.If you are thinking, you will create package from web and deploy it in master, that will not work. :-) When you create package from master, it installs the items in master only and same is the case with web.Right and easy way to do is Transfer the item. Yes, you read it right. There is a provision in Sitecore to transfer the items from one database to another.Select the item which you want to transfer from one database to another. Right click on it and then select Copying. Click on Transfer. see screenshotOnce you click on Transfer, it opens up a popup box. Click 'Next'. see screenshotAfter clicking on next, you have to choose the database where you would like to transfer the item. In this case,master database is selected. see screenshotSelect the folder where you want to transfer the item on master database(in this case). Click 'Next' and it will transfer the item to master database.If you like the blog, kindly put your comments. You can write email to support@bajajsumit.com for any Sitecore or .Net related help.

Delete duplicate records from table in single statement (SQL Server)

over 6 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Deleting duplicate records is very common requirement therefore multiple options are available to delete duplicate records. However this article provides the solution to delete the duplicate records using single statement.Delete from <TABLE_NAME> where <ID> not in ( select max(<ID>) from TABLE_NAME> group by <DUPLICATE_COLUMN>) For example:Employee table EmpId EmpFullName EmpSalary EmpTitle 1 Sumit Bajaj 5000 Dev 2 Amit 10000 SDev 3 Sumit Bajaj 5000 Dev 4 Priyanka 50000 Mgr 5 Umesh 10000 SDev 6 Umesh 10000 SDev 7 Amit 10000 SDev 8 Geetika 5000 Dev where few records are duplicate and need to be removed.For this table, delete query would be Delete from Employee where EmpId not in (select max(EmpId) from Employee group by EmpFullName)After executing this query you will left with only unique records as shown below. EmpId EmpFullName EmpSalary EmpTitle 3 Sumit Bajaj 5000 Dev 4 Priyanka 50000 Mgr 6 Umesh 10000 SDev 7 Amit 10000 SDev 8 Geetika 5000 Dev Thanks for reading and hope this article helped.

Oracle SQL Developer Installation

over 6 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

After spending enough time on installing Oracle SQL Developer and respective issues, I thought of writing few easy steps to install it. Hope it would help and save your time.Steps to install Oracle SQL Developer(for windows):Download SQL Developer from Oracle site. DownloadDownload JDK if it is not installed on your machine. DownloadInstall JDK and then unzip SQL DeveloperClick on sqldeveloper.exe, it will ask for java.exe pathOpen the path where JDK is installed. It would be something like "C:\Program Files\Java\jdk1.7.0_40\jre\bin" depeneding upon which version you install.If it is giving any exception, remove the entry [SetJavaHome] from sqldeveolper.conf file from "..\sqldeveloper\sqldeveloper\bin\sqldeveloper.conf" and give the correct path of java.exe file.Please provide your feedback if you like the post.

Excess of technology ruins

almost 7 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Most of us are using so many apps on mobile and spending plenty of time using those apps. Well, even I am not exception but excess of technology sometime ruins. I would like to narrate one incident where I used Google Maps and screamed after using it.I visited Dehradun, Uttrakhund from Gurgaon recently and chose Google Maps to show me the route. It showed me two ways and advised me to go via shortest route which I followed. After reaching half way, I found that road was damaged so badly that I was not able to proceed. After collecting information from villagers nearby, I got to know that this path was always like that. One of the villagers advised me not to go further on that path as for cars its not possible to cross. He advised me to take alternate route which was going through the villages. Thanks to Indian people who are so kind and helpful.Although that road was raw and some patches were there yet it was better then the path Google Maps proposed. By somehow, I could reach Dehradun crossing so many villages. Generally it takes 5 hours to reach Dehradun but that day it took 9.5 hours to reach to destination. I conveyed my thanks to GOD and villagers who helped me to reach there.To conclude, I am in complete agreement that using technology to some extent surely helps but using it in excess ruins.This is what I have written to Google: " I have used Google Maps (India) to get the way to Dehradun, Uttrakhund from Gurgaon. It showed me 2 ways and    advised me to go from shortest path which I followed. After going half way I found that the road is so damaged that I can  not proceed. So I would like to suggest that if Google could provide feedback popup for that route where a person can give some  rating or comments would be really great. It would help you to choose the best way to go."Share you incidence and help people to make life better.

Could not load file or assembly 'MySQL.Data' or one of its dependencies. Access is denied.

about 7 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

It is very common error with .net assemblies. When someone included dlls from outside, in the project, this kind of exceptions are generic.Here is the resolution.Open the file location (MySql.Data.dll in this case)Right click on dll and check its properties (it should not be encrypted and should have right access permissions)Run the project after assigning appropriate permissions. It should work now.Even after this if it does not work. Check in web.config that assembly information is added under <compilation> tag.It is advisable to included new dlls using nuget package reference. It will update its reference automatically.Happy Coding!!!

Google search appliance (GSA) sorting and filtering

about 7 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Working with Google Search Appliance(GSA), sometimes business has requirement of sorting or filtering the results. Browsing the internet did not provide any helpful pointers for the ways to sort or filter the search results therefore I have written these instructions to use sorting & filtering in easy way with examples.Sorting:Google Search Appliance(GSA) has provided the tags to sort the results in ascending or descending order. Pages should have meta tags which provides information to GSA box for crawling. Using those tags, sorting can be achieved.For example: If web pages has a tag<meta name="title" content="Sumit Bajaj::Passionate Technologist" />GSA URL should include parameter to sort the results&sort=meta:title:a  (for arranging all results in ascending order w.r.t title)&sort=meta:title:d  (for arranging all results in descending order w.r.t title)Similarly it can be sorted for another meta tags.Filtering:Similar like sorting meta tags can be used for filtering as well. Google Search Appliance(GSA) has provided the provision to filter the results too. Pages should have meta tags which provides information to GSA box for crawling. These tags can be used for filtering the output.For example: If web pages has a tag<meta name="articledate" content="2014-10-12" />GSA URL should include parameter to filter the results&query=inmeta:articledate:daterange:2014-01-01.. (all article whose articledate is greater than 2014-01-01)&query=inmeta:articledate:daterange:2013-01-01..2014-01-01(all article whose articledate is in between 2013-01-01 & 2014-01-01)&query=inmeta:articledate:daterange:..2014-01-01 (all article whose articledate is lesser than 2014-01-01) Similarly we can modify the tags and syntax to get desired output.Reference:Google Search Appliance documentFor more details, you can contact me on "email.bajaj@gmail.com" or visit my websitehttp://www.bajajsumit.comEnjoy coding and build the best.Sumit Bajaj <!--[if IE]><style type="text/css">body {behavior: url(csshover3.htc);} </style><![endif]--> <!-- Start: Facebook like and share for Sumit Bajaj -->

Host Angular App on Heroku

about 7 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Angular is one of the javascript frameworks which provides new dimensions of writing javascript and on the other hand Heroku is a web hosting platform which allows applications to host. Most importantly, it gives option to host various applications free of cost.Now considering that an angular project is ready and need to be hosted somewhere so could be accessed publicly. There are few steps which will push the project on Heroku platform and enable the angular project to be browsed by outside world.Pre-requisite:1. You should have a Heroku account, if not create one.2. Heroku toolbelt is installed on machine. Once installed using command prompt, enter"heroku login" and provide your email and password to log into heroku account.3. In case you need some domain name, register it in advance. Otherwise you can access the URL which Heroku provides by default.4. Last and most important point, you should be ready with angular project. Insure that you are not getting any error while running commands like "grunt build" or "grunt serve".Lets start to host it on Heroku:1. Run the command "grunt build" on your angular project. Once succeed, it will create a "dist" folder in your project with compiled code and clean structure.2. Heroku need a server to serve the files. As angular project only has static files, we will use Node server for serving the file.Create a web.js file and keep it in root directory of project. Put the mentioned lines in that file and save it.var gzippo = require('gzippo');var express = require('express');var app = express();app.use(express.logger('dev'));app.use(gzippo.staticGzip("" + __dirname + "/dist"));app.listen(process.env.PORT || 5000); 3. Now create a procfile (without any extension) and keep it in root directory as well. Put the mentioned lines in that file and save it.web: node web.js Note: "procfile" is starting point of application and lines written in it is telling node server to execute "web.js" file which internally is serving content from "dist" folder.4. Run command "heroku create [app_name]"It will create a project on heroku.5. After adding file using "git add ." and committing using "git commit m 'initial commiy'", push it to heroku using command > git push heroku master6. It will push the project on Heroku project and give you the heroku path to browse the website. For instance, http://abc.herokuapp.comYou are done!!In case some specific domain name is required to point to this app, can be done easily by providing CName and pointing to heroku app.Please provide your feedback or email me to "email.bajaj@gmail.com" for any query.

Get ASP.NET Web API to return JSON instead of XML

over 7 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

By default, Web API produces XML but if there is need for JSON, given syntax will do it.Open WebApiConfig.cs file in solution and add mentioned line in it as shown in example.public static void Register(HttpConfiguration config)        {            config.Routes.MapHttpRoute(                name: "DefaultApi",                routeTemplate: "api/{controller}/{id}",                defaults: new { id = RouteParameter.Optional }            );            //To produce JSON format add this line of code            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));        }Kindly provide your valuable comments if you find the post helpful.

Custom control in Sitecore

over 7 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Although Sitecore has provided most of the features out of box, yet sometime we need custom control to be created as per project need. In the given example, we will create a custom control "Pubish with media". Purpose of this custom button is to publish the content including media associated with it.Follow the mentioned steps to make custom control.Step1:Create a cs file in your project and name it as "PublishWithMedia.cs". Open the file and write the code. In this example,  we are showing code for publishing media with content item.usingSystem;usingSystem.Collections.Specialized;usingSitecore;usingSitecore.Data;usingSitecore.Data.Items;usingSitecore.Diagnostics;usingSitecore.Globalization;usingSitecore.Links;usingSitecore.Publishing;usingSitecore.Shell.Framework;usingSitecore.Shell.Framework.Commands;usingSitecore.Web.UI.Sheer;usingSitecore.Workflows;namespace MyProject.CustomControl{    /// <summary>    /// Represents the Publish Item command.    /// </summary>    [Serializable]    publicclass PublishWithMedia : Command    {        ///<summary>        ///Checks the workflow.        ///</summary>        ///<param name="args">The arguments.</param>        ///<param name="item">The item.</param>        ///<returns>The workflow.</returns>        private static bool CheckWorkflow(ClientPipelineArgs args, Item item)        {            Assert.ArgumentNotNull(args, "args");            Assert.ArgumentNotNull(item, "item");            if (args.Parameters["workflow"] == "1")            {                return true;            }            args.Parameters["workflow"] = "1";            if (args.IsPostBack)            {                if (args.Result != "yes")                {                    args.AbortPipeline();                    returnfalse;                }                args.IsPostBack = false;                return true;            }            IWorkflowProvider workflowProvider = Context.ContentDatabase.WorkflowProvider;            if (workflowProvider == null || (int)workflowProvider.GetWorkflows().Length <= 0)            {                return true;            }            IWorkflow workflow = workflowProvider.GetWorkflow(item);            if (workflow == null)            {                return true;            }            WorkflowState state = workflow.GetState(item);            if (state == null)            {                return true;            }            if (state.FinalState)            {                return true;            }            args.Parameters["workflow"] = "0";            object[] displayName = new object[] { item.DisplayName, state.DisplayName };            SheerResponse.Confirm(Translate.Text("The current item \"{0}\" is in the workflow state \"{1}\"\nand will not be published.\n\nAre you sure you want to publish?", displayName));            args.WaitForPostBack();            return false;        }        ///<summary>        ///Executes the command in the specified context.        ///</summary>        ///<param name="context">The context.</param>        public override void Execute(CommandContext context)        {            if ((int)context.Items.Length == 1)            {                Item items = context.Items[0];                NameValueCollection nameValueCollection = new NameValueCollection();                nameValueCollection["id"] = items.ID.ToString();                nameValueCollection["language"] = items.Language.ToString();                nameValueCollection["version"] = items.Version.ToString();                nameValueCollection["workflow"] = "0";                Context.ClientPage.Start(this, "Run", nameValueCollection);            }        }        ///<summary>        ///Queries the state of the command.        /// </summary>        ///<param name="context">The context.</param>        ///<returns>The state of the command.</returns>        public override CommandState QueryState(CommandContextcontext)        {            if ((int)context.Items.Length != 1)            {                return CommandState.Hidden;            }            return base.QueryState(context);        }        ///<summary>        ///Runs the specified args.        ///</summary>        ///<param name="args">The arguments.</param>        protected void Run(ClientPipelineArgs args)        {            Assert.ArgumentNotNull(args, "args");            string item = args.Parameters["id"];            string str = args.Parameters["language"];            string item1 = args.Parameters["version"];            if (!SheerResponse.CheckModified())            {                return;            }            Item currItem = Context.ContentDatabase.Items[item, Language.Parse(str), Sitecore.Data.Version.Parse(item1)];            Database targetDB = Sitecore.Configuration.Factory.GetDatabase("web");            if (currItem == null)            {                SheerResponse.Alert("Item not found.", new string[0]);                return;            }            if (!PublishWithMedia.CheckWorkflow(args, currItem))            {                return;            }            string[] strArrays = new string[] { AuditFormatter.FormatItem(currItem) };            Log.Audit(this, "Publish item: {0}", strArrays);            Items.Publish(currItem);            ItemLink[] itemLinks = currItem.Links.GetValidLinks();            foreach (ItemLink link in itemLinks)            {                Item itm = link.GetTargetItem();                if (itm != null)                {                    if (itm != null && itm.Paths.IsMediaItem)                    {                                               PublishItem(itm, targetDB);                    }                }                count++;            }        }        private void PublishItem(Item item, Database targetDB)        {            PublishOptions options = new PublishOptions(item.Database, targetDB, PublishMode.SingleItem, item.Language, DateTime.Now);            options.RootItem = item;            options.Deep = false;            new Publisher(options).Publish();        }    }}Build the project to check if any errors.Step2:Open "Commands.config" file in App_Config folder. Click on "View all files" in Visual studio if App_Config folder is not there.Copy the line in Commands.config file somewhere in the middle.<command name="contenteditor:publishwithmedia" type="MyProject.CustomControl.PublishWithMedia,MyProject.CustomControl"/>Note: Change the namespace and class name if you kept the names different.Step3:Open Sitecore instance and switch to "Core" database. Click on Database icon on bottom right corner of website for switching to Core database.Open Sitecore-> Content Editor and Expand the tree tositecore -> content -> Applications -> Content Editor -> Ribbons -> Chunks -> PublishCopy the existing item and create a new one. Rename it to "Publish with media". Open newly created item and in Data section of it fill mentioned information.Header information will be displayed as Custom control name on main UI. In click section, we have mentioned "contenteditor:publishwithmedia" which is command name we added in commands.config file.Save the item and switched back to master database as shown in start of Step 3.Step4:Open Sitecore -> Content Editor. Click on Publish menu and you will see custom button appearing on it.Click on button to check the functionality. Select any item and publish with custom button, it will publish the item and media associated with item to.Please provide your valuable comments.

Github cherry picking

over 7 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

What is cherry picking ?Cherry picking is plucking selective code to push to another branch. Sometime team is working on several modules and there is urgency to fix some production issue and deploy it.We can have two ways of doing it1. Create a separate branch from master (production branch) , for example name it as "branch1" and fix the bug and merge that branch into master back.2. Fix the bug in existing branch and cherry pick it in master branch. This way only selective changes would be pushed to master and not all code.Whenever we push some code in git, it creates a unique commit id.For example:Unique commit id looks like shown in green boxCopy that commit id which you want to cherry pick.Git checkout to master branch (where you want to cherry pick)$ command: git checkout masterCherry pick the selected commit by passing commit id.$ git cherry-pick b38adf46f21c963b6e85a804ef3942ad8d0b4e4dSelected commit will be merged into masterNow you can check the status and push the code respectively.Note: Cherry pick should be incremental and sequence wise. First commit should be cherry picked first followed by second and so on. Have a great day ahead !!

Add Rich Text Full Editor in Sitecore template

over 7 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

It is very common requirement and very easy to add Rich Text Full editor in Sitecore.Steps:1. Open Template and make the field as "Rich Text" fieldRich Text Full Editor2. Add "/sitecore/system/Settings/HTML Editor Profiles/Rich Text Full" to the source field next to it.3. Save the template and that's it.Create item with the new template and click on "Show Editor" link. It should show rich text full editor.Provide your valuable comments if this post resolved your problem.

Creating angular project at snap of fingure

over 7 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Open CMD prompt (Run as Administrator)Goto directory (where you want to create website) and typeyo angular:project_nameYou are done!! It will create all dependent files in the directory.If you are using IIS server, create a website and point it to directory/app folder. Browse the website for example: http://localhost, it will show you beautiful index page.Pre-Requisite: Yeoman (the scoffolding tool) should be installed. Refer Yoeman website for more details.Common Issue: When scoffolding angular project using yo command, if in between you are receiving errors, then execute this line on CMD prompt;C:\MyProject>git config --global url."https://" .insteadOf git://Author: Sumit BajajThanks for reading!!

HTTP Error 500.19 - Internal Server Error

almost 8 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

The requested page cannot be accessed because the related configuration data for the page is invalid.<staticContent> <mimeMap fileExtension=".woff" mimeType="application/font-woff"/></staticContent>This error occurs when there is a problem reading the configuration file for the Web server or Web application. In some cases, the event logs may contain more information about what caused this error.Solution:1. Open IIS and click on hosted website2. On the Featured View tab, double click on MIME type icon and check if .woff extension is present. If on click it gives error not to worry.3. Open web.config file of project solution and check if .woff mimemap entry is present. If yes, remove that entry.4. Go back to IIS and follow Step 1 and Step 2. It should show .woff extension now.5. Check your website and it should work now.Author: Sumit BajajThanks for Reading. Have a great time.

Uploading an Excel and Importing the data in database

almost 8 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

This is very common requirement to read the data from uploaded excel and import it in database. Earlier it was a tedious task but not now, thanks to Nuget packages where you get so many utilities to make your life easy. In this post, we will also use Nuget package and perform the task of uploading excel and importing the data in database.There are two steps to perform this,1. To upload the excel file on server2. Read the uploaded file and import the data to databaseStep1: To upload the excel file on server   <asp:FileUpload ID="excel_upload" runat="server"/>        if (excel_upload.HasFile)    {       bool upload_file = true;       string file_upload = Path.GetExtension(excel_upload.FileName.ToString());       if (file_upload.Trim().ToLower() == ".xls" |             file_upload.Trim().ToLower() == ".xlsx")       {          // Save excel file onto Server          xlsUpload.SaveAs(Server.MapPath("~/Uploads/" + excel_upload.FileName.ToString());       }    }Step2: Read the uploaded file and import the data to databaseTo perform excel read/write, we will use ClosedXML (Nuget package). Install the package using package manager.Once installed, include the namespace in your code file   using ClosedXML.Excel;Now the code starts to get data from uploaded excel file.      FileInfo fi = new FileInfo(filePath);      //Open uploaded workbook            var workBook = new XLWorkbook(fi.FullName);      //Get the first sheet of workbook      var worksheet = workBook.Worksheet(1);      var firstRowUsed = worksheet.FirstRowUsed();      var categoryRow = firstRowUsed.RowUsed();      int coCategoryId = 1;      //Get the column names from first row of excel      Dictionary<int, string> keyValues = new Dictionary<int, string>();      for (int cell = 1; cell <= categoryRow.CellCount(); cell++)      {        keyValues.Add(cell, categoryRow.Cell(cell).GetString());      }      //Get the next row      categoryRow = categoryRow.RowBelow();      while (!categoryRow.Cell(coCategoryId).IsEmpty())      {         int count = 1;         var pc = new ExpandoObject();         while (count <= categoryRow.CellCount())         {          // let this go through-if the data is bad, it will be rejected by SQL           var data = categoryRow.Cell(count).Value;           ((IDictionary<string, object>)pc).Add(keyValues[count], data);                      count++;         }         categoryRow = categoryRow.RowBelow();      }      //Insert the data in SQL which is captured in pc object.Reference: To get more detailed scenarios for excel data manipulation, click here.~~ Happy Coding ~~

Unable to launch the IIS Express Web server

about 8 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

I had exactly the same issue. Tried everything but finally one trick worked.Delete folder IISExpress from "My Documents"Load your project again, it will create IISExpress folder again with updated configurationCheck IISExpress folder has sufficient permissions to read-write the configuration fileLoad project again and Run IISExpress. It should work.Author: Sumit Bajaj

Create dynamic content using Razor templates

about 8 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

This article is explaining the usage of Razor template and effectiveness of these templates.Let's consider one scenario, when you have to send emails to different users with dynamic data which is different for different users. Example shown below is a basic example. Think of some complex scenario where plenty of data need to be changed and also require some styling.To start work on one simple example, right click on your website folder and create a new blank @view. Name it as "Useremail.cshtml". Paste the mentioned code there.Useremail.cshtml   <html>   <body style="font-family: Arial; font-size: smaller">   <p>Dear @Model.Name,</p>    <p>A new account has been created for you to access Application with                            username: <b>@Model.Username </b></p>    <p>You can access the application at @Model.AppUrl.</p>    <p>Your password will be sent to you in a following email.    </p>    <p>Thank you,</br>       Cleansheet Team.    </p>    </body>    </html>Explanation: The Useremail.cshtml is Razor template file which is having dynamic html. The variable which need to be dynamic, we can give them as @Model.variable_name. ( For example: @Model.Name )Next step is to create Controller which will assign the dynamic values, given in Razor template.Controller.cs       var userTemplate = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory +                                     @"Views\Email\Username.cshtml");       dynamic userObj = new { Name = "Sumit Bajaj", Username = "sbajaj", AppUrl =                                  Request.RequestUri.GetLeftPart(UriPartial.Authority) };       string userMsg = Razor.Parse(userTemplate, userObj);       Email.Send(user.Email, "Your user name for the Application", userMsg);Explanation: File.ReadAllText is reading the template file from current base directory. userObj is dynamic object  which is being populated with variables we defined in template file.Line [string userMsg = Razor.Parse(userTemplate, userObj);] is filling the userObj data in userTemplate (Razor template). Next line is sending email to user with dynamic data populated.Razor class is part of RazorEngine assembly which can be downloaded from Download RazorEngine Assembly. You can add reference of this assembly in your website and use it. ~~ Happy Coding ~~

Nuget Error: "No more data is available"

about 8 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Unable to install Nuget Package Manager on Visual Studio 2010 SP1, Windows 7, 64 bit machine. When creating new MVC4 Project, getting Nuget Error "No more data is available".Here are the steps which will resolve the issue.1. Open Visual Studio -> Tools -> Extension Manager...2. From Online Gallery, Download Nuget Package ManagerIf you get error like "No more data is available", Download it from Nuget Website.3. Once downloaded, change the extension "vsix" to "zip"    For example:  Nuget.Tools.vsix  -> Nuget.Tools.zip4. Goto path  C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\ide\Extensions\Microsoft Corporation\NuGet Package Manager\1.6.21205.9031if it is not existing, create the folders so path could look like above path.5. Unzip the Package (see step 3) in the folder (see step 4)6. Now ...\NuGet Package Manager\1.6.21205.9031 should have all dlls and respective files7. Restart Visual Studio and now it should workEnjoy!!

Steps to migrate from other CMS to Sitecore

about 8 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Here are few easy steps to migrate the data from other CMS to Sitecore1. Get the detail of CMS from where to migrate in Sitecore2. Export the articles or items in xml format. Generally all CMS gives this option to export it in xml file format3. Read the xml tags one by one to get all related details (code given is just for reference)//Get all files under specific directorystring[] files = Directory.GetFiles(path);List<ArticleData> articleList = new List<ArticleData>();//Read each file one by oneforeach (string filePath in files){    XmlDocument xmlDoc = new XmlDocument();    xmlDoc.Load(filePath);                  ArticleData article = new ArticleData();    article.FileName = filePath.Substring(path.Length + 1, (filePath.Length - (path.Length + 1)));    XmlNodeList list = xmlDoc.SelectNodes("record/item[@name='it_article_title']");                    article.Title = list[0].InnerText;    XmlNodeList list1 = xmlDoc.SelectNodes("record/item[@name='it_publication_date']");                    article.Date = list1[0].InnerText;    XmlNodeList list2 = xmlDoc.SelectNodes("record/item[@name='it_author']");                    article.Author = list2[0].InnerText;         XmlNodeList list4 = xmlDoc.SelectNodes("record/item[@name='it_summary']");                    article.Summary = list4[0].InnerText;       XmlNodeList list6 = xmlDoc.SelectNodes("record/item[@name='it_image_file_name']");                    article.Thumbnail = list6[0].InnerText;    articleList.Add(article);}           4. Create template in Sitecore including all required fields5. Take reference of below mentioned code to create item in Sitecore and fill the values in itDatabase masterDb = Sitecore.Configuration.Factory.GetDatabase("master");//Get the Item under which you want to import all items . //Here ID of that item is passed under which all items will be imported.Item activeItem = masterDb.GetItem(new ID("1CD389F0-E0C7-4D22-A39D-0C5BD2A1251D"));                //For Editing an Item in Sitecore, Security should be disabled else you have to create user //with required permission and write logic to authenticate it                using (new Sitecore.SecurityModel.SecurityDisabler())                {                       Item newItem = activeItem.Add(article.FileName, template);                    newItem.Editing.BeginEdit();                    newItem.Fields["Title"].Value = article.Title;                    newItem.Fields["Body"].Value = article.Text;                                        DateTime dt = new DateTime();                    DateTime.TryParse(article.Date, out dt);                    newItem.Fields["Article Date"].Value = Sitecore.DateUtil.ToIsoDate(dt);                    newItem.Fields["Image"].Value = article.Image;                    newItem.Editing.EndEdit();                }6. Run the code and check, Item should be created in Sitecore~~~~~~~~~~~~~~~Happy Coding !!~~~~~~~~~~~~~~

Sitecore 7: The Power Packed

over 8 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Sitecore 7 is new release of Sitecore content management system. It came up with so many exciting features that when someone will go through, definitely will say Wow!!. The industry's first fully integrated search based architecture.Out of so many power-packed features, here is the list of few.Search Boosting: It allows content to be pushed higher in the search. Rules are provided which can be easily created in sitecore depending on business requrements. For example: If we have 100 featured results to be displayed on page, then by boosting your items can up-rank it on top.Dynamic Data: The nice change in Data source field. It allows to write query based data source which make it fully dynamic. Criteria can be written in Build Query dialog box.Search Tagging: Inbuilt tagging mechanism pulls the content in search which is tagged. It is used for fetching more accurate data. No coding, its just add tags on item and you are done.Big Data: There is no limit on the amount of content it can store. Good thing is that high volume of data is not impacting the performance in any way.Pluggable Search: Everyone who worked on Sitecore has used Lucene/Solr but Sitecore 7 provides flexibility to plug search of your choice. User Interface is fully integrated with Search, LINQ usage and latest Microsoft.Net framework support and so many features to explore.

Importing existing blog data under New blog

over 8 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Welcome to the topic 'Importing existing blog's data under new blog'. Generally people write new post in existing blog but few people write blogs in category. One kind of posts under one blog and other kind of posts under other blog. For example: java-script related posts under java-script blog, ruby related issues under ruby blogs.Sometime when there is need to generate feed for blogs it gets difficult to accumulate all blogs under one feed when you have categories the blogs.Those who have all posts under one blog, feeds get generated easily.Let's see how different blogs can be grouped together under one blog. These steps are written for www.blogger.com, similar kind of steps can be used for other kind of blogging sites.1. Open blogger.com and click on the blog which you want to move to other (main) blog2. Click on Settings tab on left3. Click on Other tab under Settings4. Click on 'Export blog' which is shown on top right panel5. Clicking on it will download the xml file, download it6. Go back to main blog in which you want to import the blog7. Follow the steps from 1-3 and click on 'Import blog'8. Select the xml file which is downloaded and click on 'Import blog' button9. Select the settings as you want and blog will be imported in main blogScreenshot1 (Settings for existing blog) :Importing blogScreenshot2 (Get Imported blog and import in main blog) : After importing when you will open the mail blog, you will find the imported blog is also coming in Blog Archive section. Click on that blog and verify if it is imported successfully. All the best and keep blogging !!

over 8 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Brightcove video event handling is way to capture the video events and perform some operations on occurrence of that event.AlertNote: Brightcove API services does not work on local environment (for example: direct browsing of page) so you have to host the website on IIS.Here are the steps to include video on page and capture the events and perform some action on event occurrence.Open any HTML page and write the mentioned javascript code in head section.Javascript Section<script type="text/javascript">         var player;         var modVP;         var modExp;         var modCon;                  function myTemplateLoaded(experienceID) {                          player = brightcove.api.getExperience(experienceID);             modVP = player.getModule(brightcove.api.modules.APIModules.VIDEO_PLAYER);             modExp = player.getModule(brightcove.api.modules.APIModules.EXPERIENCE);             modCon = player.getModule(brightcove.api.modules.APIModules.CONTENT);             modExp.addEventListener(brightcove.api.events.ExperienceEvent.TEMPLATE_READY, onTemplateReady);         }         function onTemplateReady(evt) {                      modVP.addEventListener(brightcove.api.events.MediaEvent.BEGIN, onMediaEventFired);             modVP.addEventListener(brightcove.api.events.MediaEvent.CHANGE, onMediaEventFired);             modVP.addEventListener(brightcove.api.events.MediaEvent.COMPLETE, onMediaEventFired);             modVP.addEventListener(brightcove.api.events.MediaEvent.ERROR, onMediaEventFired);             modVP.addEventListener(brightcove.api.events.MediaEvent.PLAY, onMediaEventFired);             modVP.addEventListener(brightcove.api.events.MediaEvent.PROGRESS, onMediaProgressFired);             modVP.addEventListener(brightcove.api.events.MediaEvent.STOP, onMediaEventFired);         }         function onMediaEventFired(evt) {             alert(evt.type);             if (evt.type === brightcove.api.events.MediaEvent.BEGIN) {                 alert('Here Video Begins!!');             }         }    </script>Body Section<div style="display: none"></div>    <script language="JavaScript" type="text/javascript"src="http://admin.brightcove.com/js/BrightcoveExperiences.js">            </script>    <object id="myExperience2128824061001"class="BrightcoveExperience">        <param name="bgcolor" value="#FFFFFF" />        <param name="width" value="480" />        <param name="height" value="270" />        <param name="playerID" value="PLAYED_ID" />        <param name="playerKey" value="AQ~~,AAABywrPJyk~,MP34hwWOTrN8Z6UocoZHuAZdr8inViSF"/>        <param name="isVid" value="true" />        <param name="isUI" value="true" />        <param name="dynamicStreaming"value="true" />                <!-- smart player api params -->        <param name="includeAPI" value="true" />        <param name="templateLoadHandler"value="Test" />        <param name="templateLoadHandler"value="myTemplateLoaded" />        <param name="templateReadyHandler"value="onTemplateReady" />        <param name="@videoPlayer" value="VIDEO_ID" />    </object>

.NET Mathematics

over 9 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Loading UserControl on another UserControl & assigning Properties of loaded UserControlParent UserControl (.ascx) UI: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MultiVarientModule.ascx.cs"    Inherits="Modules.MultiVarientModule" %><div id="parent" runat="server"></div> Parent UserControl Code File (.cs) : #region CONSTANTSconst string CAROUSAL = "~/Modules/Carousal.ascx";const string THREECOLUMNS = "~/Modules/ThreeColumn.ascx";const string REGULAR = "~/Modules/Regular.ascx";#endregionprotected void Page_Load(object sender, EventArgs e){switch(ControlName){       case "Carousel":              parent.Controls.Add(LoadControl(CAROUSAL));              break;       case "ThreeColumn":              parent.Controls.Add(LoadControl(THREECOLUMNS));              break;       case "Regular":              {              Regular reg = (Regular)LoadControl(REGULAR);              reg.DisplayMode = ControlName;              reg.DisplayItem = multiVarientItem;              parent.Controls.Add(reg);              break;              }       default:              break;}} The above code is showing three different usercontrols to be added in parent div of another usercontrol.For assigning value to properties of child usercontrol, we have to write mentioned code. Here "Regular" is one userControl. Regular reg = (Regular)LoadControl(REGULAR);reg.DisplayMode = ControlName;reg.DisplayItem = multiVarientItem;parent.Controls.Add(reg);break; Loading the usercontrol and assigning it to Regular class     Regular reg = (Regular)LoadControl(REGULAR);Assigning properties of regular class      reg.DisplayMode = ControlName;     reg.DisplayItem = multiVarientItem;and finally adding the object to parent usercontrol.Regular (.ascx) UI <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Regular.ascx.cs" Inherits="Modules.Regular" %><div>    <h4><asp:Literal ID="regularTitle" runat="server" /></h4></div><div class="leftInteriorTwoColumn" runat="server" id="LinkWithDescription"><span sizcache="30" sizset="126"><asp:Repeater ID="Repeater_LinkWithDescription" runat="server" OnItemDataBound="Repeater_LinkWithDescription_ItemDataBound"><ItemTemplate>  <a runat="server" id="articleLink" />  <div sizcache="30" sizset="127">  <div class="editorsContent" sizcache="30" sizset="127">  <p sizcache="30" sizset="127">    <span id="publishedDate" runat="server" class="pubdate" />    <span id="articleDescription" runat="server" />    <a id="moreLink" runat="server" class="moreLink">more</a>  </p>  </div>  </div></ItemTemplate></asp:Repeater></span></div> Regular (.cs) Code File: private string displayMode = String.Empty;public string DisplayMode{  get  {    return displayMode;  }  set  {    displayMode = value;  }}private Item displayItem;public Item DisplayItem{  get  {    return displayItem;  }  set  {    displayItem = value;  }}

Gridview Performance improvement with Custom Paging

over 9 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Gridview provides excellent features to show the data on webpage. Few of the popular features are sorting, column arrangements, styles, item templates, editing, updating and deleting.Get the data from SQL, DataList, Arrays and bind the data to Gridview and it displays the data in required format.GridView1.DataSource = SQL command Result OR List() OR Array() GridView1.Databind();When the data is huge and you bind the data with GridView, it can impact the performance of your page. To Overcome that, GridView Paging is provided but it fetches all the records and bind it to GridView and when you click on page number, it shows the records of that page index.GridView paging is also not good solution and hits the performance as it fetches all the records once and then bind it to GridView.Here is the solution which do custom paging and fetches the data when required.GridView with Custom PagingGridView with Custom PagingGridView is showing 10 records by default. Clicking on 'Next' button will show next 10 records. Clicking on 'Previous' button will show previous 10 records. First button will take you to First Page and Last button will take you to Last page of GridView.Trick starts with SQL Server Stored Procedure. We have to write a stored procedure which will return the required records.  SQL Paging to improve performanceA kind of SQL Paging is done which takes two parameters 1. startIndex (from where to start)           2. recordCount (how many records to fetch)SQL Paging using Stored ProcedureSQL Paging using Stored ProcedureDefault value of @startIndex is set to 0 and @recordCount is set to 10 which means it will fetch 10 records starting from 0th row.Now time to write code to fetch the data and populate it to GridView.Populate GridView on PageLoadHere GridView is being populated on Page_Load method and PopulateData method is pulling the records from SQL Server.PopulateData(GridView1.PageIndex, 10);Note: GridView1.PageIndex gives the Index value which is 0 by Default Next Button ClickNow when we will click on 'Next' Button, we will increment the GridView1.PageIndex by 1 and next 10 results will be shown.Next Button Click Code BehindNext Button Click Code BehindPopulateData(GridView1.PageIndex * 10, 10);      where GridView1.PageIndex is incremented by 1 and gives results as 1. Multiply by 10 will give result as 10. Now records will start from 10 and will display next 10 records. Previous Button ClickSimilarly Previous Button will decrement the GridView1.PageIndex by 1 on every click till the value is 0.  First Button ClickClicking on First button will call method PopulateData(0, 10);  Last Button ClickClicking on Last button will call method PopulateData(TotalRecordCount()-10, TotalRecordCount());  where TotalRecordCount() method returns total count of records in sql table.After doing Cutom Paging, Editing, Deleting and Updating can also be done on fetched records. GridView Edit / Delete / Update after Custom PagingEditing can also be done easily after doing custom paging.It is very much similar to editing we do in Gridview. The only difference is that we are calling method PopulateData after finding index of edited row in GridView.PopulateData(GridView1.PageIndex*10,10)The reason we are calling this method because if  we will not call this method how GridView will come to know which record to edit when page postback will happen on click on Edit button of GridView.GridView Edit after Custom PagingGridView Edit after Custom PagingAs we have written the code for Edit, similarly you can write the code for cancel, delete and update event of GridView.Happy Coding !!It would be honor for me if you could provide your valuable comments if you liked / not  liked /suggestions to improve.

Wrap the data in Gridview

over 9 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Sometime the data in Gridview column is large and it makes the scrollbar to appear on the page. Due to which User Interface of page get effected.Here are two solutions for achieving the required wrapping.Why two solution are provided?The reason is that sometime solution 1 doesn't work for all browser. It vary with the way how you are pulling the data in Gridview.Solution 1:Putting <ItemStyle> tag and setting the width of column.Wrapping the data using <ItemStyle> tagWrapping the data using <ItemStyle> tagSolution 2:Putting <div> tag and styling on bounded column (Works on all browsers)Wrapping the data using <div> tag and stylingWrapping the data using <div> tag and stylingOutput: Here is the output how data displayed in Gridview is wrapped.Gridview WrappingGridview wrappingKeep posting your queries to get optimum solution.


over 9 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Could not load file or assembly 'System.Data.SQLite' or one of its dependencies. An attempt was made to load a program with an incorrect format. 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.BadImageFormatException: Could not load file or assembly 'System.Data.SQLite' or one of its dependencies. An attempt was made to load a program with an incorrect format. 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. Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Data.SQLite' could not be loaded.System.BadImageFormatExceptionSystem.BadImageFormatException: System.Data.SQLite Resolution Steps:1. Goto IIS (inetmgr)2. Open Application Pools3. Select the required pool4. Click on 'Advanced Settings' on right hand side panal5. Check the 'Enable 32-bit Applications' and set it to true (see below screenshot)6. Restart the pool and browse your websiteIIS SettingApplication Pool Advanced Settings

Sitecore Best Practices

over 9 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Design Prospective:1. Put components statically in html if it is being used multiple times and not much changes required. Use placeholders only to bind those components which are getting change frequently.2. Always set presentation details on _standard values.3. Do appropriate image resizing on server else it will slow down the performance when opening on browse.4. Create template for providing data to presentation component.5. Get the Data from DataSource from component Parameters to get variations.Code Prospective:1. Test your html/css/javascript code in such a way that Page Editor is enable for edit by non technical staff.2. Given meaningful names to placeholder so that right component could add under right placeholder.3. Write code using C# coz this is language generally use by Sitecore Support team.Use GUID instead of path/name as content can be moved to some other location in content tree.4. Create separate config file for your component instead of adding directly in web.config.5. Use Lucene Search in case data is large6. Do customization(if required) carefully and properly tested as it can impact the performance.

Sitecore customization using pipelines

over 9 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

A pipeline consists of a number of processors arranged in sequence to process a common set of parameters. If I have a series of tasks, which need to be performed to accomplish a task, then a pipeline may be the way to go.Instead of passing to each processor an arguments object containing these parameters, the pipeline class itself exposes properties representing the parameters.Sitecore pipelines also allow an object to pass through each step. This object can be manipulated by any of the steps and passed through to the next step until the end is reached and the object can be used by whatever executed the pipeline in the first place.In configuration file, you will be able to see numbers of pipelines, which is default from sitecore. You can create your own custom code and add pipeline to execute that code.Example:Pipeline contains parameter ‘type’, which contains information about class and assembly as shown in snapshot.UI customization using pipelinesEach step in pipeline is called a ‘processor’. Pipeline call the ‘Process’ method from class. Whatever functionality you want to achieve can be written in ‘Process’ method.For Example:In this scenario, Pipeline class is inheriting ‘HttpRequestProcessor’ and overriding its Process method to achieve some functionality.Now code has been written, we have to add pipeline in ‘web.config’ so it could execute. We have added our custom pipeline next to step, where we want to it be executed.So with just a few lines of code and configuration we can consume benefits of pipeline architecture and perform our custom actions.Have a great day and enjoy coding !!

Google Recaptcha implementation without plugin

over 9 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Google Recaptcha ImplementationSTEP 1:Add Following Script on you page:<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"> <!--</span-->script> <script src="http://code.jquery.com/jquery-latest.pack.js"><!--</span-->script> <script type="text/javascript"> function showRecaptcha(element) { Recaptcha.create("your_public_key", element, { theme: "clean", callback: Recaptcha.focus_response_field }); } function showResult() { //alert('start'); var challengeVal = Recaptcha.get_challenge(); //alert(challengeVal); var reponseVal = Recaptcha.get_response(); alert(reponseVal); var remoteIp = ""; //alert(remoteIp); var privateKey = ’Your_Private_Key’; var requestUrl = "http://api-verify.recaptcha.net/verify?privatekey=" + privateKey + "&remoteip=" + remoteIp + "&challenge=" + challengeVal + "&response=" + reponseVal; return requestUrl; } <!--</span-->script> <script type="text/javascript"> $(document).ready(function () { var container = $('#target'); $('.ajaxtrigger').click(function () { var url = showResult(); doAjax(url); //return false; }); function doAjax(url) { // if it is an external URI if (url.match('^http')) { // call YQL $.getJSON("http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(url) + "%22&format=xml'&callback=?", // this function gets the data from the successful // JSON-P call function (data) { // if there is data, filter it and render it out if (data.results[0]) { var data = filterData(data.results[0]); container.html(data); Recaptcha.reload(); // otherwise tell the world that something went wrong } else { var errormsg = 'Error: could not load the page.'; container.html(errormsg); } } ); // if it is not an external URI, use Ajax load() } else { $('#target').load(url); } } // filter out some nasties // filter out some nasties function filterData(data) { return data; } }); <!--</span-->script>After adding above script, add following line of code in section to display recaptchaSTEP 2: <div id="recaptcha_div"> <script type="text/javascript">showRecaptcha('recaptcha_div');<!--</span-->script> <!--</span-->div> <input type="submit" name="Button1" value="Submit" class="ajaxtrigger"> <div id="target"><!--</span-->div>

AJAX Progrraming

almost 15 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Ajax, shorthand for Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user requests a change. This is meant to increase the web page's interactivity, speed, and usability. The Ajax technique uses a combination of: XHTML (or HTML) and CSS, for marking up and styling information.The DOM accessed with a client-side scripting language, especially JavaScript and JScript, to dynamically display and interact with the information presented. The XMLHttpRequest object is used to exchange data asynchronously with the web server. In some Ajax frameworks and in certain situations, an IFrame object is used instead of the XMLHttpRequest object to exchange data with the web server, and in other implementations, dynamically added tags may be used. XML is sometimes used as the format for transferring data between the server and client, although any format will work, including preformatted HTML, plain text, JSON and even EBML. These files may be created dynamically by some form of server-side scripting.