Thursday, July 12, 2012

Display Current Login User Name in Sharepoint 2010 Using Sharepoint Designer 2010




Display the current login username in sharepoint control.We have only access to sharepoint designer. We dont have access to add serverside code.  So we decide to user "Welcome username" message. We used javascript to display the username. Please check the following code.


<script type="text/javascript" language='javascript'>
function getLoginName()
 {
 var tags = document.getElementsByTagName('span');
 var loginName = null;
     for (var i=0; i < tags.length; i++)
     {
    if(tags[i].title =="Open Menu")
       {
          var childTag = tags[i].getElementsByTagName('DIV');
             var innerChild = childTag[0].getElementsByTagName('a');
          var tloginName = innerChild[0].innerText;
          var iLength = tloginName.length; 
    if(tloginName.indexOf("Welcome") > -1)
    {
     loginName = tloginName.substring(8,iLength);
     break;
    }
       }
  }
  return loginName;
}

 
//To display in people & group control
function setPickerInputElement(pickerNo) 
{
  var result = ""; 
  var j = 0;
  var divs = document.getElementsByTagName("DIV"); 
  for (var i=0; i <30; i++)
   {
       if (divs[i].id.indexOf("UserField_upLevelDiv") > 0)
       { 
           j++;
           if (j == pickerNo)
           {
              result = divs[i]; 
              result.innerText = getLoginName();  
              break; 
           }
        }
    } 
 }
</script>





setPickerInputElement(1);
call this function, and pass the people & group No.if there is only one 
people & control use "1", if you have more than 1, give on which control the 
current username need to display.

Screen1:Paste the code as shown.

Screen 2:
With this approach, instead of people or group control, you can display the user name in textbox if required.

Active Directory Groups vs. SharePoint Groups for User Management.




Some advantages and disadvantages of the group types and let you choose what kind fits better for your needs.


How to move the Sharepoint Sites from Testing(Staging) Server to Production Server?



The major problem will be faced by the sharepoint developers/administrators starts when they complete the customization and move all their work to the Production Server. The approach what we take for ASP.NET applications will not work out for sharepoint sitesbecause all the page contents and configurations are stored in the database. So every developer will be thinking that there needs to be deployment project like MSI to easily deploy the sharepoint sites in the different machine other than the machine/server where we have developed. Microsoft has provided a command line tool to migrate all your works to another machine which is called as SMIGRATE.exe. This tool is available in your server (Which you have installed SPS and WSS) under the path..

Program Files\Common Files\Microsoft Shared\Web Server Extensions\60\Bin
either in C drive are D drive (Where you have installed the SPS and WSS). You can use this tool to backup and restore. To use this tool you must be a site administrator for both the web site being backed up and restored. You can see the switches of this utility by typing smigrate -h in your command line provided the exe path is included in your path list otherwise navigate to directory where you are having the exe file and run the command.
Note: It will restore all your work which you have done using front page extension and sharepint admin pages. It will not move all you virtual server excluded path files. You should move the files manually to the destination virtual server .
Example:you have used User controls to build the webparts and images. You have to place those .ascx and image files to the excluded folder. For that you need manually create the same folder structure in the destination virtual server path and move all the files from your source virtual server to here.Important: It is not like backup and restore like database. You can not restore a site on top of the existing web site which are templates applied already. It means when ever you are creating a site or sub site in the sharepoint server it will ask to choose the template at the final stage of site creation procedure. If you want to restore a site you have stop the site creation procedure at that point and restore your site from the backup.Procedure to Backup and restore Sharepoint sites:



Backup:
1. Make a note of all the excluded directories which are available in your source virtual server.
2. Navigate to
 
c:\program files\common files\Microsoft shared\web server extensions\60\Bin
(with assumption you have sharepoint installed on c drive) in your command prompt.
3. Run the command
 
smigrate -w http://Sites/ -f “d:\Backup.fwp” -u \ -pw
4. Now you can have a backup of your site at the specified location
Restore:
1. Create a folder in your sharepoint server Eg: C:\Restore
2. Open your IIS and create a new web site and map it to C:\Restore
3. Open the sharepoint central administration.
4. Create a portal site by mapping the exiting virtual server created at step 2
5. Step 4 will take some time to create a portal site. After successful creation of the portal site, Open the portal site home page and select the Sites link
6. Create a new site using Create site option in the left side of the page.
7. Note down the URL of your new site. (Eg: http://Sites/8. Stop the progress and close the browser when the select template page comes.
9. Use smigrate -r -w < -f “d:\Backup.fwp” -u \ -pw
10. Copy your source web.config from your source virtual server and replace the web.config in your destination virtual server path (This is needed if you have done any change on the source web.config)
11. Copy all your excluded folders from your source virtual server to destination.
12. Browse the center Administration->Sharepoint Portal server->Configure virtual server settings from the Virtual Server List page->(Select the Virtual server)->Define managed paths to exclude the directories.Now you have a new site with the replica of the existing one.
At this stage you will have question in your mind what is the procedure if any page are list has been created after deployed into production. All pages you can copy and paste it in the destination server using MS FrontPage 2003.

SharePoint Backup and Restore MOSS



If  you are moving your site from Testing(Staging) to Production, site backup and restore (using STSADM command line tool)  is the way to go. Other ways include SQL Server, Sharepoint Designer, DPM etc. However, site backup and restore using STSADM is probably the easiest and fastest one.


Backup the site using the following STSADM Command:Stsadm –o backup –url http://<server name>:<port> -filename <path\name to be used for the backup file>
Example:
Stsadm –o backup –url http://pravahaminfo:4545–filename "e:\backup4545.bak"

After the backup has been completed, “Operation Completed Successfully” message should be displayed.



Create a new Web Application for restoring the site:Go to Central Administration -> Application Management -> under SharePoint Web Application Management -> click Create or Extend Web Application. Fill in the required information, click Ok and wait until the progress continues.
Once the new web application is created, run the following STSADM command and restore the site using the backup file created above.

Stsadm –o restore –url http://<server>:<port> -filename <path\name of the backup file>
Stsadm –o restore –url  http://pravahaminfo:5454  –filename "e:\backup4545.bak"

Restored site should be up and running.
If it is not (and you are receiving weird errors in your browser), keep reading:
Now it could be the case that you have customized your site. So, we must deploy those customizations properly for the site to work as expected. This is typically a scenario while moving your site from Testing to Production environment. First you have to add the solutions (if any created) to the farm.
Add a Solution to the SharePoint Farm:Add the solution package to the farm by running the following commands. Make sure full path of WSP file is supplied.
 
stsadm –o addsolution –filename <path to mysolution.internet.test.wsp>

Deploy the Solution to the restored site:
Now we need to deploy the newly added solution to our restored site. Click the solution name and select ‘Deploy’ button from top. Select the appropriate web application in the deployment settings and click OK. This will take several minutes to deploy mysolution.internet.test.wspresources (list templates, features, assemblies, master pages, styles). Once the solution has been deployed, reset IIS to ensure all deployed changes are picked up by the web application.
You can also deploy the solution from the command line with the following SharePoint admin command.

stsadm -o deploysolution -name mysolution.internet.test.wsp -url <site> -immediate -allowgacdeployment –allowcaspolicies

Make sure all your assemblies (DLLs) are available in Global Assembly Cache (GAC) usually placed at c:\windows\assembly.  
 Activate features installed by mysolution.internet.test.wsp solution package:Go to the newly restored site, click Site Actions, click Site Settings, click Site Collection Features. Click Activate button to activate any Site Collection Feature.
Go to the newly restored site, click Site Actions, Site Settings, Site Features.
Click Activate button to activate any Site Features.
Update Web.Config file:It will be usually a case that your solution package will deploy a few DLLs with it. So we need to add all those Safe Control entries, Assembly Bindings, Keys and any other web.config changes to our newly restored sites’s web.config. Weird browser errors that I mentioned above usually appear due to these missing entries in web.config, specially when you are restoring on the same machine/server…….As assemblies will already be there in the GAC if the restore operation was performed on the same machine….you just need to make web.config entries to the restored site…..adding and deploying of the solution could be skipped. So lets do the copy paste operation from the old web.config to the new web.config. Just compare the two web configs and copy/paste the missing entries into the new. 
Web.config file could be found at the following path:
<drive letter>:\Inetpub\wwwroot\wss\VirtualDirectories\<port number>\web.config
 

Example:C:\Inetpub\wwwroot\wss\VirtualDirectories\5454\web.config 
 

Usually these changes will include Safe Controls, AssemblyBindings, PageParserPaths and Keys etc. After making these changes your site should be ready in Production.
If you are worried about the bad habit of Moss saving absolute URLs for the page layout in the properties of a publishing page, then relax, solution is already in the market:
References:
you are refering to the following Microsoft article that says that moving a farm using STSADM is obsolete:
and from here they will point you to “Moving to Another Farm” using SQL Server Tools:
Before I say why I was able to use STSADM, I will take this opportunity to share some important info:
You can use STSADM command to backup and restore on the same farm:
and you should not use STSADM command to restore to another farm, that’s right.
To restore to another farm, you must use SQL Server tools:
http://technet.microsoft.com/en-us/library/cc261918.aspx


and here is the important information: the specs of the farm on which you are restoring should still be exactly the same as the one from which backup is taken from. Specs means server names, software updates, number of servers…
Now if you are restoring to another farm which has different specs, then it will not be called as MOVING to another farm, it will be either MIGRATING or UPGRADING to anohter farm…..good news is that its still doable:
So, what have I done above in the post?
I haven’t actually moved the farm at all. I have simply moved a Site Collection from one farm to another.
So, the trick here is that moving farms is complicated……largely due to config and central admin databases because they contain computer specific information (in short)…….so why dont we simply move our site collection and probably relax :) :
You can also move individual content databases using STSADM:
Site Collection backup/restore that we did above will actually backup and restore the content DB.

I’m getting confused by all the options and different opinions in blogs. I’m going to move one or more site collections from one farm to a completely different one (new server names but same domain).
If I understand the link below correctly, Stefan Gossner basically says that in that kind of scenario the “Best is to use SQL backup/restore.”
If it’s a publishing site, one only needs to be sure to have SP2 and the April CU installed (so that links to pagelayouts are fixed), and then there are no problems using SQL backup/restore.

Redirect to a new page, when we get 404.htm error page in the application





Create a custom Page Not Found is to create a site level feature receiver that will attach it to the webApplication instance.
On the activated event you would attach it like this:
    [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
      if (properties != null)
      {
        try
        {
          SPSite site = properties.Feature.Parent as SPSite;
          System.Uri webApplicationUri = new Uri(site.Url);
          SPWebApplication webApplication = SPWebApplication.Lookup(webApplicationUri);
          if (webApplication != null)
            webApplication.FileNotFoundPage = "CustomError.html";
        }
        catch (Exception ex)
        {
         throw;
        }
      }
   }
And in your deactivated event you could unattach it by setting the same webApplication.FileNotFoundPage to null.
You will also have to save your Custom Page Not found page in the Layout.

How to Send Email to Registered Users using c sharp.




 I need to send an email to registered user for every 3 days.Mail starting date will be read from database(sqlserver).This should be done automatically.
I am hosting my website on shared webserver like india.com.
Think I cannot write windows service and install.
I think we need to wrtie webservice which fires acynchronously which checks date.
am n confusion.please guide me.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.Configuration;
using System.Data;
using System.Web.Security;


namespace IATI_Email_Application
{
   public partial class ATIEmail : System.Web.UI.Page
   {
       protected void SUBMIT_Click(object sender, EventArgs e)
       {
           String SMTPServerName =
ConfigurationManager.AppSettings["SMTP_SERVER"].ToString();
           String MailUserName =
ConfigurationManager.AppSettings["EMAIL_USERNAME"].ToString();
           String MailPassword =
ConfigurationManager.AppSettings["EMAIL_PASSWORD"].ToString();
           String adminToEmail =
ConfigurationManager.AppSettings["ADMINISTRATOR_TO_EMAIL"].ToString();
           String adminDisplayName =
ConfigurationManager.AppSettings["ADMIN_DISPLAY_NAME"].ToString();
           String subject =
ConfigurationManager.AppSettings["SUBMIT_SUBJECT"].ToString();
           string adminFromEmail =
ConfigurationManager.AppSettings["ADMINISTRATOR_FROM_EMAIL"].ToString();
           String successMessage =
ConfigurationManager.AppSettings["SUBMIT_MAIL_SUCCESS"].ToString();
           String failureMessage =
ConfigurationManager.AppSettings["SUBMIT_MAIL_FAILED"].ToString();
           try
           {
               String FilePath = String.Empty;
               if (FileUpload1.HasFile)
               {
                   try
                   {
                       string filename = FileUpload1.FileName;
                       string filename1 = filename.Substring(0,
filename.LastIndexOf("."));
                       string ext =
filename.Substring(filename.LastIndexOf(".") + 1);
                       filename = filename1 +
Guid.NewGuid().ToString() + "." + ext;
                       FilePath =
Server.MapPath("~/EmailAttachments/") + filename;
                       FileUpload1.SaveAs(FilePath);
                       StatusLabel.Text = "Upload status  File uploaded";
                   }


                   catch (Exception ex)
                   {
                       StatusLabel.Text = "Upload status  The file
could not be uploaded. The following error occured: " + ex.Message;
                   }
               }
               NetworkCredential basicAuthenticationInfo = new
NetworkCredential(MailUserName, MailPassword);
               MailMessage mail = new MailMessage();
               SmtpClient SmtpServer = new SmtpClient(SMTPServerName);
               mail.From = new MailAddress(adminFromEmail, adminDisplayName);
               mail.Subject = subject;
               mail.To.Add(new MailAddress(txtEmail.Text));
               if (FilePath != String.Empty)
               {
                   mail.Attachments.Add(new Attachment(FilePath));
               }
               String mailBody =
System.IO.File.ReadAllText(ConfigurationManager.AppSettings["SUBMIT_TEMPLATE_PATH"].ToString());
               mail.Body = mailBody;
               mail.IsBodyHtml = true;
               mail.DeliveryNotificationOptions =
DeliveryNotificationOptions.OnFailure;
               SmtpServer.Credentials = basicAuthenticationInfo;
               SmtpServer.UseDefaultCredentials = false;
               SmtpServer.Send(mail);
               ClientScript.RegisterStartupScript(this.GetType(),
"myalert", "alert('" + successMessage + "');", true);
               txtEmail.Text = "Enter your email address";


           }
           catch (Exception ex)
           {
               string exmsg = ex.Message;
               ClientScript.RegisterStartupScript(this.GetType(),
"myalert", "alert('" + failureMessage + "');", true);
           }
       }


   }
}

Upload the Files in Sharepoint Using C#






public class insertdatademo : System.Web.UI.WebControls.WebParts.WebPart
{
public FileUpload file; 
}


 public insertdatademo()
        {
           
          file=new FileUpload();
        }


protected override void CreateChildControls()
{


file=new FileUpload();
            file.DataBind();
             this.Controls.Add(file);
            oButtonSubmit.Click += new EventHandler(oButtonSubmit_Click);


}


 void oButtonSubmit_Click(object sender, EventArgs e)
{




if(file.HasFile==true)
                {
                    SPAttachmentCollection attach = myListItem.Attachments;
                    String fileName = file.PostedFile.FileName;
                    byte[] textfile = file.FileBytes;
                    attach.Add(fileName, textfile);




                }
}


protected override void Render(HtmlTextWriter writer)
{


writer.Write("<table class='ms-formtoolbar' cellpadding='2' cellspacing='0' border='0' width='100%'><tr><td width='99%' class='ms-toolbar' nowrap><IMG SRC='/_layouts/images/blank.gif' width='1' height='18' alt=''></td><td class='ms-toolbar' nowrap='true'><TABLE cellpadding='0' cellspacing='0' width='100%'><TR><TD align='right' width='100%' nowrap>");
            file.RenderControl(writer);
            writer.Write("</TD></TR></TABLE></td></tr></table>");


}