Showing posts with label MOSS 2007. Show all posts
Showing posts with label MOSS 2007. Show all posts

Thursday, October 11, 2012

2nd Popup Issue In SharePoint 2010 Visual Web Part (With Ajax Update Panel)

I need to popup an alert for the user 2 times based on his/her option picked.
 
Business scenario:
If user choose to deleting a master record, 1st popup and alert the user his/her action.
And if (s)he choose to delete, now I have to find if any child records effecting, if so, not to delete the main record but alert the user again for further action.

This is how I solved it: With the help of JavaScript and Server events.
Added two delete buttons on webpart designer
  1. Main Delete:
                   <asp:Button ID="btnDelete" runat="server" Text="Delete" Width="100px" OnClientClick="if(confirm('Are you sure you want to delete this saved record?')==true)return true;else return false;" CausesValidation="false" onclick="btnDelete_Click" class="ms-ButtonHeightWidth" ChildrenAsTriggers="true"/>            
 2. Hidden Delete: (using style to hide)
                        <asp:Button ID="btnDeleteConfirm" runat="server" Text="DeleteConf" Width="100px" CausesValidation="false" onclick="btnDeleteConfirm_Click" class="ms-ButtonHeightWidth" style="display:none" />
 
OnClientClick event of the Main delete button prompt for 1st initial popup. Once he/she choose to say YES, onclick="btnDelete_Click" will fire as coded in javascript function.
Now in the btnDelete_Click event if I find any child records (I am using entity framwork here) I will register and call ConfirmDelete()

protected void btnDelete_Click(object sender, EventArgs e) {
.
.
if(entityList.Count > 0)
{
   RegisterPopupScript();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "PopupDelete", "ConfirmDelete();", true);
}else
{MasterSalesRepService.Delete(Convert.ToInt32(lblSalesRepId.Text));
RedirectPage();
}
}

private void RegisterPopupScript()
        {
            Type type =
this.GetType();
            if (Page.ClientScript.IsStartupScriptRegistered(type, "
PopupScript"))           
               
return;
                       
            System.Text.
StringBuilder script = new System.Text.StringBuilder();
script.Append("<script language=\"javascript\" type=\"text/javascript\">\n");
script.Append("function ConfirmDelete(){if(confirm('Do you want to delete child record(s) as well?')==true) return document.getElementById('" + btnDeleteConfirm.ClientID + "').click(); else  return false; }");
script.Append("
</script >");                      
           
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "PopupScript", script.ToString(), false);          
        } 

protected void btnDeleteConfirm_Click(object sender, EventArgs e)
        {
            DeleteXrefSalesRep();
            DeleteMasterSalesRep();
            RedirectPage();
        }

In the script I will fire "btnDeleteConfirm_Click" only if user proceed other wise I won't
Note: I won't delete main record as well as child record if user cancels the action as you see from my btnDelete_Click code.

Tuesday, October 9, 2012

Attaching & Debugging to a specific w3wp.exe

Very common thing we developers do or run into is attaching all the w3wp.exe process while debugging.

Simply because we don't know which service a/c or IIS process to be attached while debugging.
Now in my case, as shown below I have to confirm (7 times) attachment of process, right! That's another fold to the debugging process.

 














Save the grief by use this little script to know your exact web application and attach to it irrespective of service A/C.
 
@ECHO OFF
cls
c:\Windows\System32\inetsrv\appcmd list wp

Save the above as wp.bat and store in C:\windows\system32 folder, I am choosing this because the path already added to the Environmental variable's path, which means now I can call this file from any command prompt path/folder location.

I will be invoking the script from H:\> by typing "wp" and enter.
Results shown as below & In my case I will be only attaching to 9044.

Happy debugging!

Tuesday, November 8, 2011

Terminating/Canceling the Workflows

As we know some time it's bit trick to terminate/cancel a workflow.. Which made me create this web part, so that I can delegate my job to the power user so that they can manager it better! And also gives me some extra time to concentrate on my deadlines.

Challenges:
Very first that you need to have proper admin access to see "Terminate this workflow now" link
When you click on the workflow hyper link on the library item 


Here is the web part UI:





Note: ID is the document list item id; you can make more fancy by providing the file name or even loading the active workflow items once selected the document library name

Code for Process Button:
private void CancelWF(string ListName, string ItemId)
{
  SPSecurity.RunWithElevatedPrivileges(delegate()
  {
   
using (SPSite siteColl = new SPSite(SPContext.Current.Site.Url))
    {
     
using (SPWeb site = siteColl.OpenWeb())
      {
      
if (site != null)
       {
       
try
        {
        
SPList workflowTasks = site.Lists["Tasks"];
         SPList doc = site.Lists[ListName];
         SPListItem docItem = doc.GetItemById(Convert.ToInt32(ItemId));

         foreach (SPListItem listItem in docItem.ListItems)
         {
          site.AllowUnsafeUpdates =
true;
          foreach (SPWorkflow itemWorkflow in listItem.Workflows)
          {
          
SPWorkflowManager.CancelWorkflow(itemWorkflow);
           _lblMessage.Text = string.Format(("Administratively Canceled Workflow for the ItemId: {0} / File Name : {1}"), ItemId, listItem.File.Name);
           _lblMessage.ForeColor = Color.Blue;
          }
          site.AllowUnsafeUpdates =
false;
        }
      }
     
catch (Exception ex)
      {
        HandleException(ex);
      }
     }
    }
   }
  });
}


End results:

Thursday, July 28, 2011

Updating Timer Job Schedule

Some time we need to build and deploy a timer job with specific schedule say hourly or daily.
But for testing with the business or on your own , you don't want to wait for a day to see the change

Here is a simple console app code which you can use to change timer schedule for testing for any other reason

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace UpdateTimerJob
{
  class Program
  {       
   
static void Main(string[] args)
    {
      updateTimer();
    }

static void updateTimer()

{
  using (SPSite site = new SPSite("http://sp2010/sites/timer/"))
  {    foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
    {      if (job.Title == "WorkflowEscalation")
      {
        SPMinuteSchedule schedule =
new SPMinuteSchedule();
        schedule.BeginSecond = 0;
        schedule.EndSecond = 59;
        schedule.Interval = 5;
        job.Schedule = schedule;
        job.Update();


        Console.WriteLine("START UPDATING... ");
       }
     
Console.WriteLine("JOB: " + job.Title);
    }
  }
}
} }


Note: this need to run on the server; you can further modify this app to read site, title & schedule, then update accordingly

Wednesday, July 27, 2011

Timer Job With Trick

Timer Job our good old friend, for further details or quick start take a look at this http://technet.microsoft.com/en-us/library/cc678870(office.12).aspx 

A little know trick I have implement in my timer job so that it install only on Web front end or Single server (ex. DEV box, usually all in one box).

const string JOB_DEFINITION_NAME = "EscalationTimerJob";

public override void FeatureActivated(SPFeatureReceiverProperties properties)
 {
  SPSecurity.RunWithElevatedPrivileges(delegate()
  {                     
   #region ONLY WebFrontEnd/SingleServer
   SPSite site = properties.Feature.Parent as SPSite;
   SPWebApplication webApp = site.WebApplication;

   //make sure job isn't already registered
   if (webApp == null)
   {
    throw new SPException("Error obtaining reference to Web application.");
   }
   foreach (SPJobDefinition job in webApp.JobDefinitions)
   {    if (job.Name == JOB_DEFINITION_NAME)
       job.Delete();
   }
   foreach (SPServer server in SPFarm.Local.Servers)
   {    if (server.Role == SPServerRole.SingleServer || server.Role == SPServerRole.WebFrontEnd)
 {
  //Install the Job                        
  WorkflowEscalation taskJob = new WorkflowEscalation(JOB_DEFINITION_NAME, webApp, server, SPJobLockType.Job);
  SPHourlySchedule schedule = new SPHourlySchedule(); //Every Hour
  schedule.BeginMinute = 0;
  schedule.EndMinute = 59;
  taskJob.Schedule = schedule;
  taskJob.Update();
  }
}
#endregion
});
}


Note:
1. Added RunWithElevatedPrivileges, so that job definition will be create when activated even without full access. Feature activation runs under the application pool account. So it needs to be a farm administrator which will be mitigate by implementing RunWithElevatedPrivileges

2. Also make sure you also implemented below in your main execute() file
public WorkflowEscalation(string jobName, SPWebApplication webApp, SPServer server, SPJobLockType targetType): base(jobName, webApp, server, targetType)
 {
  this.Title = jobName;
 }

Usual code for installing in on all the servers:
const string JOB_DEFINITION_NAME = "EscalationTimerJob";
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(
delegate()
{
  #region For Multiple Servers
  SPSite site = properties.Feature.Parent as SPSite;
  //make sure job isn't already registered
  if (site.WebApplication == null)
  {
   
throw new SPException("Error obtaining reference to Web application.");
  }

  foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)

  {
   
if (job.Name == JOB_DEFINITION_NAME)
      job.Delete();
  }

 
//Install the Job                    
  WorkflowEscalation taskJob = new WorkflowEscalation(JOB_DEFINITION_NAME, site.WebApplication);
  SPHourlySchedule schedule = new SPHourlySchedule(); //Every Hour
  schedule.BeginMinute = 0;
  schedule.EndMinute = 59;
  taskJob.Schedule = schedule;
  taskJob.Update();

  #endregion                                     
  });
}

Monday, March 7, 2011

How to Control Hyper Link Attributes to Open In a New Window

Wondering how to control the Hyper Link control behavior! Like STYLE, OPEN , SET FOCUS & ATTRIBUTES

Current project requirement to open the Hyper link with specific browser attributes like With Scroll bar, No Menu bar, Specific Window Position, Height & Width.

Achieved with Java Script as shown below code:

string strURL = "http://rajadandu.blogspot.com/";

//Create Hyper Link
HyperLink h = (HyperLink)e.Row.FindControl("ConfHlink");

// Setting Style
h.Style["margin-left"] = "5px";

//Setting default Hyper Link Navigation to NULL
h.NavigateUrl = "javascript:void(null);";

//Hyper Link Display string
h.Text = "Opening With Controlled Hyper Link";

//Java Script with Open Window with attributes
//Then at last Set Focus
h.Attributes["onclick"] = "javascript:window.open('" + strURL + "','','scrollbars=yes,menubar=no,height=430,width=700,top=0,left=0,resizable=yes,toolbar=no,location=no,status=no'); window.focus();";

Tuesday, December 28, 2010

Remove Title Header from Webpart

Add this stylesheet elements to the page by using content editor webpart

<style type="text/css">
.ms-viewheadertr {
 DISPLAY: none
}
.ms-vhltr {
 DISPLAY: none
}
</style>

Before:





After:

Wednesday, November 24, 2010

SharePoint 2007 to 2010 Migration

1. Run the preupgradecheck
psexec \\SP2007Server -u domain\UserID -p yourPWD -s stsadm -o preupgradecheck
Note: I used psexec sysinternal tool, felt easy working from my Pc rather than RDPing to the server

2. Based on Above check we have 2 options out of 4 options

1. In-place upgrade
○ Use existing hardware – servers/farm offline during upgrade
○ Configuration and all content upgraded
○ Farm-wide settings preserved
○ Customizations available after upgrade
○ Recommended for small or non-production environments

2. Database Attach upgrade
○ New hardware
○ Upgrade multiple DBs at a time
○ Server farm settings not upgraded
○ Customizations must be transferred
○ Can consolidate multiple farms into one
○ Recommended if farm level configurations are minimal

3. Hybrid 1: Read-Only Database upgrade
○ Use Database Attach upgrade to preserve existing farm
○ Existing farm is put in read-only mode
○ Create a new farm and attach all content databases
○ Server farm settings not upgraded
○ Recommended over Database Attach

4. Hybrid 2: Detach Database upgrade
○ Use in-place upgrade for farm settings to preserve configurations
○ Detach and upgrade content databases
○ Alternatively, upgrade content databases in a temporary farm
○ Recommended if farm level configurations are significant

3. Pre Upgrade check will give you possible options for you to migrate, I choose Content Database Attach.

4. Identifying the .WSP files to be removed, Clean up your current 2007 environment before you migrate, so that you have less things to worry.

a. Used Bamboo SharePoint Analyzer http://community.bamboosolutions.com/blogs/bambooteamblog/archive/2008/11/06/introducing-bamboo-sharepoint-analyzer.aspx Choose where solution is used Option. To Identify Solutions and Features that have been deployed, displayed per Web App, Site Collection or Site scope
Now they even have client version, so you can run from your local PC.

5. Downloaded the STSADM Extender for automating the deleting away the unwanted web parts
Please Install the http://stsadm.blogspot.com/2007/10/set-web-part-state.html STSADM Extended commands to strip the web parts from the pages.
 
Download from:
SharePoint 2007 STSADM Extension WSP Files (SP2 is Recommended)
MOSS Only STSADM Extensions (x86, x64)
To install for the first time run the following commands (make sure you are in the directory where you downloaded the file):

stsadm -o addsolution -filename Lapointe.SharePoint.STSADM.Commands.wsp

stsadm -o deploysolution -name Lapointe.SharePoint.STSADM.Commands.wsp -immediate -allowgacdeployment

stsadm -o execadmsvcjobs


6. Stsadm -o gl-setwebpartstate -url "http://SP2007Server/default.aspx" -title "Un wanter WP Title like custom Events" -delete -publishUse the Excel sheet to generate the script for us.
You need Primarily 2 main fields Web Page & Display Web Part You get these 2 values from Bamboo Analyzer.
Formula to get script =CONCATENATE("stsadm -o gl-setwebpartstate -url """,[@[Web Page]],""" -title """,[@[Display Web Part]], """ -delete -publish")OR
Manually Strip web parts:
Find the pages then add the ?contents=1 to go to Manage Web part Page; then remove away the web parts & checked in those are checked out by other user(s) Note: Make sure you check out the Page.

7. Taking DB Offline on 2007 Env.
a. STSADM -o deletecontentdb –url "http://SP2007Server/" -databasename "WSS_Content" -databaseserver "SP\SHAREPOINT"

b. USE master
Go
ALTER DATABASE WSS_Content SET OFFLINE WITH
ROLLBACK AFTER 60 SECONDS

c. USE [master]
GO
EXEC master.dbo.sp_detach_db @dbname = N'WSS_Content',
@keepfulltextindexfile = N'true'
GO
8. My assumption is that you already have or created a new web application and site collection
Taking DB Offline on 2010 Env. (newly created site collection)
a. STSADM -o deletecontentdb –url "http://SP2010Server/" -databasename "WSS_Content_SP2010" -databaseserver "SP\SHAREPOINT"

b. USE [master]
GO
EXEC master.dbo.sp_attach_db @dbname = N'WSS_Content',
@filename1 =N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SHAREPOINT\MSSQL\DATA\SP2007\WSS_Content.mdf'
Note: You can user SQL Manager for attaching the DB, easy too!

c. Run Powershell script
i. Test-SPContentDatabase –name WSS_Content –WebApplication http://SP2010Server

For further identifying the migration issues you may encounter when you attach.

ii. New-SPContentDatabase -Name WSS_Content -WebApplication http://SP2010Server

Friday, October 15, 2010

A Blank, White Web Page Is Displayed in IE

Make sure that LOOPBACK CHECK is disabled, To disable the loopback check. follow these steps:

1. Click Start, click Run, type regedit, and then click OK.
2. In Registry Editor, locate and then click the following registry key:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
3. Right-click Lsa, point to New, and then click DWORD Value.
4. Type DisableLoopbackCheck, and then press ENTER.
5. Right-click DisableLoopbackCheck, and then click Modify.
6. In the Value data box, type 1, and then click OK.
7. Quit Registry Editor, and then restart your computer.

Note: This also helps in fixing calling custom web services in InfoPath form which returns with null/no data

Thursday, October 14, 2010

Web Part Page Maintenance

All I know was use my book marked Manage Web Part Page URL from my IE favorites to bring up maintenance page to fix the web part.

http://<site>/_layouts/spcontnt.aspx?&url=default.aspx

by change the site and url parameter.

But lately found out that if you add the ?contents=1 to your page at the end, system will build the manage webpart maintenance page!! How cool is that?

Monday, September 20, 2010

Hiding the context menu Options/Items

Add the Content Editor web part, add below code to it.(remove items which you want to see!!)

<script type="text/javascript">

function CAMOpt(p,wzText,wzAct,wzISrc,wzIAlt,wzISeq,wzDesc)
{
var mo=CMOpt(wzText,wzAct,wzISrc,wzIAlt,wzISeq,wzDesc);
if(!mo)return null;
if(wzText != "View Properties")
if(wzText != "Edit Properties")
if(wzText != "Manage Permissions")
if(wzText != "Edit Document")
if(wzText != "Delete")
if(wzText != "Send To")
if(wzText != "Check Out")
if(wzText != "Version History")
if(wzText != "View Workflow History")
if(wzText != "Schedule Workflows")
if(wzText != "Alert Me")
AChld(p,mo);
return mo;

}
</script>

Tuesday, June 30, 2009

Thanks to Lytebox!

In a nutshell Lytebox improved version of Lightbox class that embed media and presents in a rich end user experience. Read more at http://www.huddletogether.com/2007/04/16/lightbox-203-released/
And http://www.dolem.com/lytebox/

Let's get into Share Point Integration:
1. Create a document library which can be used for Centralized sharing purpose.

2. Download Lytebox v3.22 http://www.dolem.com/lytebox/lytebox_v3.22.zip

3. Upload lytebox. Js , lytebox.css & Images into above created document library.

4. I took a power point presentation and converted all the slides into .jpg (Image) files

5. Upload all those Image files into another document library (I called it Help, since I was dealing with help docs to present in a very rich user experience.)

Note: Name the Image files such a way that you can related it back to your slides
Ex: Presentation Name_Slide number ==> Booking Coordinator Instructions_1.jpg

6. Add Content Editor web part.

7. Now Lytebox Includes
<script language="javascript" src="/Documents/Overlay/lytebox.js" type="text/javascript"></script>

<link media="screen" href="/Documents/Overlay/lytebox.css" type="text/css" rel="stylesheet">

8. Now add Images for slide show; we need to use "LYTESHOW" as REL attribute


9. Hit save and exit from the edit mode of the page.

10. End results on the Pages.


11. User Experience after launching the link.


Some other Usage of this great class:
You can have external page displayed as overlay.

1. Add this code (assumption is that you already added step 7)


2. Results on Share Point Page


3. Google Search Results


4. Custom Search page.