Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I am making this if statement and inside i am setting this SPWebTemplate which is a type. I think it would work fine, but it says that it does not exist in the current context.

if (properties.WebUrl == "http://sharepointdev")
{
     SPWebTemplate spWebTemplate = oWebsite.Site.GetWebTemplates(1030)["{378B494F-F38C-4F07-8D25-CA50E64C209F}#TemplateKSI"];
} else {
     SPWebTemplate spWebTemplate = oWebsite.Site.GetWebTemplates(1030)["{5FC51B7F-355E-431F-9C65-3663590346F4}#Sag"];
}

The name 'spWebTemplate' does not exist in the current context

How can that be?

And it does not help setting the variable before like

SPWebTemplate spWebTemplate;
if(...

It then says:

A local variable named 'spWebTemplate' cannot be declared in this scope because it would give a different meaning to 'spWebTemplate', which is already used in a 'parent or current' scope to denote something else.

but this example works fine:

 long websiteid;
 if (properties.ListItem["LP_SagsID"] == null)
 {
      websiteid = long.Parse(properties.ListItemId.ToString()) + startnumber;
 }  else   {
      websiteid = long.Parse(properties.ListItem["LP_SagsID"].ToString()); 

 }

---------- CODE -------------

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace Lars_Printz_Create_Sagsside.Sags_Info_Receiver
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class Sags_Info_Receiver : SPItemEventReceiver
    {
       /// <summary>
       /// An item was added.
       /// </summary>
       public override void ItemAdded(SPItemEventProperties properties)
       {
           base.ItemAdded(properties);

           if (properties.ListTitle == "Sags Info")
           {
               // Local



               SPWeb createWebsite = null;

               //long startnumber = 1166;
               long startnumber = 1566;

               using (SPSite site = new SPSite(properties.WebUrl))
               using (SPWeb oWebsite = site.OpenWeb("Sager"))
               {

                   if (properties.WebUrl == "http://sharepointdev")
                   {
                       SPWebTemplate spWebTemplate = oWebsite.Site.GetWebTemplates(1030)["{378B494F-F38C-4F07-8D25-CA50E64C209F}#TemplateKSI"];
                   }
                   else {
                       SPWebTemplate spWebTemplate = oWebsite.Site.GetWebTemplates(1030)["{5FC51B7F-355E-431F-9C65-3663590346F4}#Sag"];
                   }

                   long websiteid;
                   if (properties.ListItem["LP_SagsID"] == null)
                   {
                       websiteid = long.Parse(properties.ListItemId.ToString()) + startnumber;
                   }
                   else
                   {
                       websiteid = long.Parse(properties.ListItem["LP_SagsID"].ToString()); 

                   }

                   try
                   {
                       createWebsite = oWebsite.Webs.Add(websiteid.ToString(), websiteid.ToString() + " " + properties.ListItem.Title, properties.ListItem.Title, 1030, spWebTemplate, true, false);
                       SPGroup owner = createWebsite.ParentWeb.AssociatedVisitorGroup;
                       createWebsite.SiteGroups.Add(websiteid.ToString() + " " + properties.ListItem.Title + "-Gæster", owner, null, "Gæstegruppen");


                       if (properties.WebUrl == "http://sharepointdev")
                       {
                           SPGroup spGroup = oWebsite.SiteGroups["SharePointdev-medlemmer"];
                       }
                       else {
                           SPGroup spGroup = oWebsite.SiteGroups["Lars Printz-medlemmer"];
                       }
                       SPRoleAssignment roleAssignment = new SPRoleAssignment(spGroup);
                       SPRoleDefinition roleDefinition = oWebsite.RoleDefinitions.GetByType(SPRoleType.Contributor);
                       roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
                       createWebsite.Update();
                       if (!createWebsite.HasUniqueRoleAssignments)
                       {
                           createWebsite.BreakRoleInheritance(false); // Ensure we don't inherit permissions from parent
                       }
                       createWebsite.RoleAssignments.Add(roleAssignment);
                       createWebsite.Update();

                   }
                   catch (Exception)
                   {

                       properties.ListItem["Title"] = "Fejl med at lave site";
                       this.EventFiringEnabled = false;
                       properties.ListItem.SystemUpdate(false);
                       this.EventFiringEnabled = true;
                   }
                   finally
                   {
                       SPList l = createWebsite.Lists["SagsInfo"]; // Lars Printz
                       SPListItem li = l.Items.Add();
                       li["Title"] = properties.ListItem.Title;
                       li["LP_Postal"] = properties.ListItem["LP_Postal"];
                       li["LP_Address"] = properties.ListItem["LP_Address"];

                       if (properties.ListItem["LP_Sagstype"] != null)
                       {
                           string sagstypelookup = properties.ListItem["LP_Sagstype"].ToString();
                           string[] sagstypelookupArray = sagstypelookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

                           li["LP_Sagstype"] = sagstypelookupArray[0].ToString();
                       }
                       if (properties.ListItem["LP_Budtype"] != null)
                       {
                           string budtypelookup = properties.ListItem["LP_Budtype"].ToString();
                           string[] budtypelookupArray = budtypelookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

                           li["LP_Budtype"] = budtypelookupArray[0].ToString();
                       }
                       if (properties.ListItem["SagsStatus"] != null)
                       {
                           string sagsstatuslookup = properties.ListItem["SagsStatus"].ToString();
                           string[] sagsstatuslookupArray = sagsstatuslookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

                           li["SagsStatus"] = sagsstatuslookupArray[0].ToString();

                       }

                       li["LP_SagsID"] = websiteid.ToString();
                       li["Ansvarlig"] = properties.ListItem["Ansvarlig"];
                       li.Update();

                   } // End Finally


                   SPFieldUrlValue value = new SPFieldUrlValue();

                   value.Description = properties.ListItem.Title + " - " + websiteid.ToString();

                   if (properties.WebUrl == "http://sharepointdev")
                   {
                       value.Url = "http://sharepointdev/sager/" + websiteid.ToString();
                   }
                   else
                   {
                       value.Url = "https://printz.sharepoint.com/Sager/" + websiteid.ToString();
                   }

                   properties.ListItem["LP_Sagslink"] = value;
                   properties.ListItem["LP_SagsID"] = websiteid.ToString();

                   try
                   {
                       this.EventFiringEnabled = false;
                       properties.ListItem.SystemUpdate(false);
                       this.EventFiringEnabled = true;
                   }
                   catch (Exception)
                   {

                       throw;
                   }


               } // End Openweb






           } // End if ListTitle == "Sags Info"

       } // End ItemAdded

       /// <summary>
       /// An item was updated
       /// </summary>
       public override void ItemUpdated(SPItemEventProperties properties)
       {
           base.ItemUpdated(properties);
           if (properties.ListTitle == "Sags Info")
           {

               string strUrl = properties.WebUrl;


               long websiteid = int.Parse(properties.ListItem["LP_SagsID"].ToString());
               using (SPSite site = new SPSite(strUrl))
               using (SPWeb oWebsite = site.OpenWeb("Sager/" + websiteid.ToString()))
               {

                       SPList newl = oWebsite.Lists["SagsInfo"]; // Lars Printz
                   if (newl.ItemCount == 0)
                    {
                        SPListItem newli = newl.Items.Add();
                        newli["Title"] = "Ny Sagsinfo";
                        newli.Update();

                    }
                   SPList l = oWebsite.Lists["SagsInfo"]; // Lars Printz
                       SPListItem li = l.Items[0];
                       li["Title"] = properties.ListItem.Title;
                       li["LP_Postal"] = properties.ListItem["LP_Postal"];
                       li["LP_Address"] = properties.ListItem["LP_Address"];

                       if (properties.ListItem["LP_Sagstype"] != null)
                       {
                           string sagstypelookup = properties.ListItem["LP_Sagstype"].ToString();
                           string[] sagstypelookupArray = sagstypelookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

                           li["LP_Sagstype"] = sagstypelookupArray[0].ToString();
                       }
                       if (properties.ListItem["LP_Budtype"] != null)
                       {
                           string budtypelookup = properties.ListItem["LP_Budtype"].ToString();
                           string[] budtypelookupArray = budtypelookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

                           li["LP_Budtype"] = budtypelookupArray[0].ToString();
                       }
                       if (properties.ListItem["SagsStatus"] != null)
                       {
                           string sagsstatuslookup = properties.ListItem["SagsStatus"].ToString();
                           string[] sagsstatuslookupArray = sagsstatuslookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

                           li["SagsStatus"] = sagsstatuslookupArray[0].ToString();

                       }

                       li["Ansvarlig"] = properties.ListItem["Ansvarlig"];
                       li.Update();



                   SPFieldUrlValue value = new SPFieldUrlValue();

                   value.Description = properties.ListItem.Title + " - " + websiteid.ToString();

                   if (properties.WebUrl == "http://sharepointdev")
                   {
                       value.Url = "http://sharepointdev/sager/" + websiteid.ToString();
                   }
                   else
                   {
                       value.Url = "https://printz.sharepoint.com/Sager/" + websiteid.ToString();
                   }


                   properties.ListItem["LP_Sagslink"] = value;

                   try
                   {
                       this.EventFiringEnabled = false;
                       properties.ListItem.SystemUpdate(false);
                       this.EventFiringEnabled = true;
                   }
                   catch (Exception)
                   {

                       throw;
                   }


               } // End Openweb






           } // End if ListTitle == "Sags Info"

       }  // End ItemUpdated






    }
}

ERROR CODES:

Error   1   The name 'spWebTemplate' does not exist in the current context  C:\Lars Printz\Lars Printz Create Sagsside\Lars Printz Create Sagsside\Sags Info Receiver\Sags Info Receiver.cs 58  169 Lars Printz Create Sagsside
Error   2   The name 'spGroup' does not exist in the current context    C:\Lars Printz\Lars Printz Create Sagsside\Lars Printz Create Sagsside\Sags Info Receiver\Sags Info Receiver.cs 70  79  Lars Printz Create Sagsside
share|improve this question
    
Are you using the correct namespace? –  TZHX Aug 22 '12 at 11:32
    
i am using using to open the web. I have a development env. and a production env. and before i commented out every time and would upload the code. So the code works. –  Kevin Simper Aug 22 '12 at 11:43
add comment

3 Answers

up vote 1 down vote accepted

Have you tried debugging the code where you attach to process and see whats going on?

is this similar to what your doing?

http://forums.asp.net/t/1006588.aspx

you can try this, iv removed SPWebTemplate spWebTemplate; and set it as global

using System; 
using System.Security.Permissions; 
using Microsoft.SharePoint; 
using Microsoft.SharePoint.Security; 
using Microsoft.SharePoint.Utilities; 
using Microsoft.SharePoint.Workflow; 

namespace Lars_Printz_Create_Sagsside.Sags_Info_Receiver 
{ 
    /// <summary> 
    /// List Item Events 
    /// </summary> 
    public class Sags_Info_Receiver : SPItemEventReceiver 
    { 

       private SPWebTemplate spWebTemplate;

       /// <summary> 
       /// An item was added. 
       /// </summary> 
       public override void ItemAdded(SPItemEventProperties properties) 
       { 
           base.ItemAdded(properties); 

           if (properties.ListTitle == "Sags Info") 
           { 
               // Local 



               SPWeb createWebsite = null; 

               //long startnumber = 1166; 
               long startnumber = 1566; 

               using (SPSite site = new SPSite(properties.WebUrl)) 
               using (SPWeb oWebsite = site.OpenWeb("Sager")) 
               { 

                   if (properties.WebUrl == "http://sharepointdev") 
                   { 
                       spWebTemplate = oWebsite.Site.GetWebTemplates(1030)["{378B494F-F38C-4F07-8D25-CA50E64C209F}#TemplateKSI"]; 
                   } 
                   else { 
                       spWebTemplate = oWebsite.Site.GetWebTemplates(1030)["{5FC51B7F-355E-431F-9C65-3663590346F4}#Sag"]; 
                   } 

                   long websiteid; 
                   if (properties.ListItem["LP_SagsID"] == null) 
                   { 
                       websiteid = long.Parse(properties.ListItemId.ToString()) + startnumber; 
                   } 
                   else 
                   { 
                       websiteid = long.Parse(properties.ListItem["LP_SagsID"].ToString());  

                   } 

                   try 
                   { 
                       createWebsite = oWebsite.Webs.Add(websiteid.ToString(), websiteid.ToString() + " " + properties.ListItem.Title, properties.ListItem.Title, 1030, spWebTemplate, true, false); 
                       SPGroup owner = createWebsite.ParentWeb.AssociatedVisitorGroup; 
                       createWebsite.SiteGroups.Add(websiteid.ToString() + " " + properties.ListItem.Title + "-Gæster", owner, null, "Gæstegruppen"); 


                       if (properties.WebUrl == "http://sharepointdev") 
                       { 
                           SPGroup spGroup = oWebsite.SiteGroups["SharePointdev-medlemmer"]; 
                       } 
                       else { 
                           SPGroup spGroup = oWebsite.SiteGroups["Lars Printz-medlemmer"]; 
                       } 
                       SPRoleAssignment roleAssignment = new SPRoleAssignment(spGroup); 
                       SPRoleDefinition roleDefinition = oWebsite.RoleDefinitions.GetByType(SPRoleType.Contributor); 
                       roleAssignment.RoleDefinitionBindings.Add(roleDefinition); 
                       createWebsite.Update(); 
                       if (!createWebsite.HasUniqueRoleAssignments) 
                       { 
                           createWebsite.BreakRoleInheritance(false); // Ensure we don't inherit permissions from parent 
                       } 
                       createWebsite.RoleAssignments.Add(roleAssignment); 
                       createWebsite.Update(); 

                   } 
                   catch (Exception) 
                   { 

                       properties.ListItem["Title"] = "Fejl med at lave site"; 
                       this.EventFiringEnabled = false; 
                       properties.ListItem.SystemUpdate(false); 
                       this.EventFiringEnabled = true; 
                   } 
                   finally 
                   { 
                       SPList l = createWebsite.Lists["SagsInfo"]; // Lars Printz 
                       SPListItem li = l.Items.Add(); 
                       li["Title"] = properties.ListItem.Title; 
                       li["LP_Postal"] = properties.ListItem["LP_Postal"]; 
                       li["LP_Address"] = properties.ListItem["LP_Address"]; 

                       if (properties.ListItem["LP_Sagstype"] != null) 
                       { 
                           string sagstypelookup = properties.ListItem["LP_Sagstype"].ToString(); 
                           string[] sagstypelookupArray = sagstypelookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries); 

                           li["LP_Sagstype"] = sagstypelookupArray[0].ToString(); 
                       } 
                       if (properties.ListItem["LP_Budtype"] != null) 
                       { 
                           string budtypelookup = properties.ListItem["LP_Budtype"].ToString(); 
                           string[] budtypelookupArray = budtypelookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries); 

                           li["LP_Budtype"] = budtypelookupArray[0].ToString(); 
                       } 
                       if (properties.ListItem["SagsStatus"] != null) 
                       { 
                           string sagsstatuslookup = properties.ListItem["SagsStatus"].ToString(); 
                           string[] sagsstatuslookupArray = sagsstatuslookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries); 

                           li["SagsStatus"] = sagsstatuslookupArray[0].ToString(); 

                       } 

                       li["LP_SagsID"] = websiteid.ToString(); 
                       li["Ansvarlig"] = properties.ListItem["Ansvarlig"]; 
                       li.Update(); 

                   } // End Finally 


                   SPFieldUrlValue value = new SPFieldUrlValue(); 

                   value.Description = properties.ListItem.Title + " - " + websiteid.ToString(); 

                   if (properties.WebUrl == "http://sharepointdev") 
                   { 
                       value.Url = "http://sharepointdev/sager/" + websiteid.ToString(); 
                   } 
                   else 
                   { 
                       value.Url = "https://printz.sharepoint.com/Sager/" + websiteid.ToString(); 
                   } 

                   properties.ListItem["LP_Sagslink"] = value; 
                   properties.ListItem["LP_SagsID"] = websiteid.ToString(); 

                   try 
                   { 
                       this.EventFiringEnabled = false; 
                       properties.ListItem.SystemUpdate(false); 
                       this.EventFiringEnabled = true; 
                   } 
                   catch (Exception) 
                   { 

                       throw; 
                   } 


               } // End Openweb 






           } // End if ListTitle == "Sags Info" 

       } // End ItemAdded 

       /// <summary> 
       /// An item was updated 
       /// </summary> 
       public override void ItemUpdated(SPItemEventProperties properties) 
       { 
           base.ItemUpdated(properties); 
           if (properties.ListTitle == "Sags Info") 
           { 

               string strUrl = properties.WebUrl; 


               long websiteid = int.Parse(properties.ListItem["LP_SagsID"].ToString()); 
               using (SPSite site = new SPSite(strUrl)) 
               using (SPWeb oWebsite = site.OpenWeb("Sager/" + websiteid.ToString())) 
               { 

                       SPList newl = oWebsite.Lists["SagsInfo"]; // Lars Printz 
                   if (newl.ItemCount == 0) 
                    { 
                        SPListItem newli = newl.Items.Add(); 
                        newli["Title"] = "Ny Sagsinfo"; 
                        newli.Update(); 

                    } 
                   SPList l = oWebsite.Lists["SagsInfo"]; // Lars Printz 
                       SPListItem li = l.Items[0]; 
                       li["Title"] = properties.ListItem.Title; 
                       li["LP_Postal"] = properties.ListItem["LP_Postal"]; 
                       li["LP_Address"] = properties.ListItem["LP_Address"]; 

                       if (properties.ListItem["LP_Sagstype"] != null) 
                       { 
                           string sagstypelookup = properties.ListItem["LP_Sagstype"].ToString(); 
                           string[] sagstypelookupArray = sagstypelookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries); 

                           li["LP_Sagstype"] = sagstypelookupArray[0].ToString(); 
                       } 
                       if (properties.ListItem["LP_Budtype"] != null) 
                       { 
                           string budtypelookup = properties.ListItem["LP_Budtype"].ToString(); 
                           string[] budtypelookupArray = budtypelookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries); 

                           li["LP_Budtype"] = budtypelookupArray[0].ToString(); 
                       } 
                       if (properties.ListItem["SagsStatus"] != null) 
                       { 
                           string sagsstatuslookup = properties.ListItem["SagsStatus"].ToString(); 
                           string[] sagsstatuslookupArray = sagsstatuslookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries); 

                           li["SagsStatus"] = sagsstatuslookupArray[0].ToString(); 

                       } 

                       li["Ansvarlig"] = properties.ListItem["Ansvarlig"]; 
                       li.Update(); 



                   SPFieldUrlValue value = new SPFieldUrlValue(); 

                   value.Description = properties.ListItem.Title + " - " + websiteid.ToString(); 

                   if (properties.WebUrl == "http://sharepointdev") 
                   { 
                       value.Url = "http://sharepointdev/sager/" + websiteid.ToString(); 
                   } 
                   else 
                   { 
                       value.Url = "https://printz.sharepoint.com/Sager/" + websiteid.ToString(); 
                   } 


                   properties.ListItem["LP_Sagslink"] = value; 

                   try 
                   { 
                       this.EventFiringEnabled = false; 
                       properties.ListItem.SystemUpdate(false); 
                       this.EventFiringEnabled = true; 
                   } 
                   catch (Exception) 
                   { 

                       throw; 
                   } 


               } // End Openweb 






           } // End if ListTitle == "Sags Info" 

       }  // End ItemUpdated 






    } 
} 

EDIT below code is an example only

A global varible like I did for your object is simple, if you put where you create the object like I did at the top within the class like so:

namespace Lars_Printz_Create_Sagsside.Sags_Info_Receiver 
{ 
    /// <summary> 
    /// List Item Events 
    /// </summary> 
    public class Sags_Info_Receiver : SPItemEventReceiver 
    { 
       //this is global and can be access anywhere within the class
       private SPWebTemplate spWebTemplate;

       public overried void creatChildControls()
       {
           //this is calling the global spWebTemplate and creating a new object
           spWebTemplate = SPWebTemplate();

           //call this method
           hellomethodTakeObjectFromChildControls();
       }

       public void hellomethod()
       {
            //this method is creating a local spWebTemplateLocal that can only be access within this method but with a different name otherwise we would get the same issue as you did before with it saying its already defined 
            SPWebTemplate spWebTemplateLocal = SPWebTemplate();

       }

       public void hellomethodFail()
       {
            //this is the same as above but it is the same issue you had
            bool a = true;

            If (a == true)
            {   
                //here your creating the object but its only accessible in this "if" statment only
                SPWebTemplate spWebTemplateLocal = SPWebTemplate();
                //this is accessible as its within the if function
                spWebTemplateLocal.IsHidden = true;
            }

             //here your calling the object that you made above but you cant access it as its not within this scope, the created object is only within the If statment an will throw an error.
             spWebTemplateLocal.IsHidden = true;
       }

       public void hellomethodWorks()
       {

            //this is the same as above but its object is accessible
            //create the object as local to this method "hellomethodWorks()"
            SPWebTemplate spWebTemplateLocal;

            bool a = true;

            If (a == true)
            {   
                //create the new object
                spWebTemplateLocal = SPWebTemplate();
                spWebTemplateLocal.IsHidden = false;
            }

             //use the local object 
             spWebTemplateLocal.IsHidden = true;
       }

       public void hellomethodTakeObjectFromChildControls()
       {
             spWeb createWebsite = null;

             //here we are calling the global createWebsite but we dont need to make a new object as we did that in the create child controls so we are going to just use the current one :)
             createWebsite = oWebsite.Webs.Add(websiteid.ToString(), websiteid.ToString() + " " + properties.ListItem.Title, properties.ListItem.Title, 1030, spWebTemplate, true, false); 
       }
    }
}

I hope this explains what i mean by global and local, If the object that your creating is encapsulated within a if function or using or try catch block its only accessible within that area and not outside of it! Making the object global should only be used if your going to use the object more than once in different methods or would like to use the same object within the class. The local method/object is only accessible localy to the mthod and has the same rules to being only accessible to whatever its encapsulated by!

http://www.blackwasp.co.uk/CSharpVariableScopes.aspx

the last part in the link also explains your issue ;) , btw the code example that i gave below the edit is only for explaining copes and doesnt work as its not ment to its just a quick example :)

share|improve this answer
    
The debugger can not run because of the problems, but your solution with putting them as private outside made it work! Thank you! Do you know where i learn about it, what is it name for that kind of function? –  Kevin Simper Aug 22 '12 at 12:22
    
Glad to see it works, Iv made an edit explaining the different types of scopes for you :) –  ali Sharepoint Aug 22 '12 at 15:18
    
WOW thanks, that is really amazing help! –  Kevin Simper Aug 22 '12 at 22:18
add comment

In the first section of the if, try removing spWebTemplateSPWebTemplate which seems to have got into your code, like below:

if (properties.WebUrl == "http://sharepointdev") 
{ 
     SPWebTemplate spWebTemplate = oWebsite.Site.GetWebTemplates(1030)["{378B494F-F38C-4F07-8D25-CA50E64C209F}#TemplateKSI"]; 
} else { 
     SPWebTemplate spWebTemplate = oWebsite.Site.GetWebTemplates(1030)["{5FC51B7F-355E-431F-9C65-3663590346F4}#Sag"]; 
} 

Let's try again.

If you declare the variable inside the if statement, that's where it is scoped, so it will be removed once the code is passed. To avoid this, you can structure your code as follows:

SPWebTemplate spWebTemplate;
if (properties.WebUrl == "http://sharepointdev") 
{ 
     spWebTemplate = oWebsite.Site.GetWebTemplates(1030)["{378B494F-F38C-4F07-8D25-CA50E64C209F}#TemplateKSI"]; 
} else { 
     spWebTemplate = oWebsite.Site.GetWebTemplates(1030)["{5FC51B7F-355E-431F-9C65-3663590346F4}#Sag"]; 
} 

This is similar to what you tried before, but without re-declaring the variable; merely assigning a value to it.


And again...

Copy and paste this code:

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace Lars_Printz_Create_Sagsside.Sags_Info_Receiver
{
    /// <summary> 
    /// List Item Events 
    /// </summary> 
    public class Sags_Info_Receiver : SPItemEventReceiver
    {
        /// <summary> 
        /// An item was added. 
        /// </summary> 
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);

            if (properties.ListTitle == "Sags Info")
            {
                // Local 
                SPWeb createWebsite = null;

                //long startnumber = 1166; 
                long startnumber = 1566;

                using (SPSite site = new SPSite(properties.WebUrl))
                using (SPWeb oWebsite = site.OpenWeb("Sager"))
                {

                    SPWebTemplate spWebTemplate;
                    if (properties.WebUrl == "http://sharepointdev")
                    {
                        spWebTemplate = oWebsite.Site.GetWebTemplates(1030)["{378B494F-F38C-4F07-8D25-CA50E64C209F}#TemplateKSI"];
                    }
                    else
                    {
                        spWebTemplate = oWebsite.Site.GetWebTemplates(1030)["{5FC51B7F-355E-431F-9C65-3663590346F4}#Sag"];
                    }

                    long websiteid;
                    if (properties.ListItem["LP_SagsID"] == null)
                    {
                        websiteid = long.Parse(properties.ListItemId.ToString()) + startnumber;
                    }
                    else
                    {
                        websiteid = long.Parse(properties.ListItem["LP_SagsID"].ToString());

                    }

                    try
                    {
                        createWebsite = oWebsite.Webs.Add(websiteid.ToString(), websiteid.ToString() + " " + properties.ListItem.Title, properties.ListItem.Title, 1030, spWebTemplate, true, false);
                        SPGroup owner = createWebsite.ParentWeb.AssociatedVisitorGroup;
                        createWebsite.SiteGroups.Add(websiteid.ToString() + " " + properties.ListItem.Title + "-Gæster", owner, null, "Gæstegruppen");


                        if (properties.WebUrl == "http://sharepointdev")
                        {
                            SPGroup spGroup = oWebsite.SiteGroups["SharePointdev-medlemmer"];
                        }
                        else
                        {
                            SPGroup spGroup = oWebsite.SiteGroups["Lars Printz-medlemmer"];
                        }
                        SPRoleAssignment roleAssignment = new SPRoleAssignment(owner);
                        SPRoleDefinition roleDefinition = oWebsite.RoleDefinitions.GetByType(SPRoleType.Contributor);
                        roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
                        createWebsite.Update();
                        if (!createWebsite.HasUniqueRoleAssignments)
                        {
                            createWebsite.BreakRoleInheritance(false); // Ensure we don't inherit permissions from parent 
                        }
                        createWebsite.RoleAssignments.Add(roleAssignment);
                        createWebsite.Update();

                    }
                    catch (Exception)
                    {

                        properties.ListItem["Title"] = "Fejl med at lave site";
                        this.EventFiringEnabled = false;
                        properties.ListItem.SystemUpdate(false);
                        this.EventFiringEnabled = true;
                    }
                    finally
                    {
                        SPList l = createWebsite.Lists["SagsInfo"]; // Lars Printz 
                        SPListItem li = l.Items.Add();
                        li["Title"] = properties.ListItem.Title;
                        li["LP_Postal"] = properties.ListItem["LP_Postal"];
                        li["LP_Address"] = properties.ListItem["LP_Address"];

                        if (properties.ListItem["LP_Sagstype"] != null)
                        {
                            string sagstypelookup = properties.ListItem["LP_Sagstype"].ToString();
                            string[] sagstypelookupArray = sagstypelookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

                            li["LP_Sagstype"] = sagstypelookupArray[0].ToString();
                        }
                        if (properties.ListItem["LP_Budtype"] != null)
                        {
                            string budtypelookup = properties.ListItem["LP_Budtype"].ToString();
                            string[] budtypelookupArray = budtypelookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

                            li["LP_Budtype"] = budtypelookupArray[0].ToString();
                        }
                        if (properties.ListItem["SagsStatus"] != null)
                        {
                            string sagsstatuslookup = properties.ListItem["SagsStatus"].ToString();
                            string[] sagsstatuslookupArray = sagsstatuslookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

                            li["SagsStatus"] = sagsstatuslookupArray[0].ToString();

                        }

                        li["LP_SagsID"] = websiteid.ToString();
                        li["Ansvarlig"] = properties.ListItem["Ansvarlig"];
                        li.Update();

                    } // End Finally 


                    SPFieldUrlValue value = new SPFieldUrlValue();

                    value.Description = properties.ListItem.Title + " - " + websiteid.ToString();

                    if (properties.WebUrl == "http://sharepointdev")
                    {
                        value.Url = "http://sharepointdev/sager/" + websiteid.ToString();
                    }
                    else
                    {
                        value.Url = "https://printz.sharepoint.com/Sager/" + websiteid.ToString();
                    }

                    properties.ListItem["LP_Sagslink"] = value;
                    properties.ListItem["LP_SagsID"] = websiteid.ToString();

                    try
                    {
                        this.EventFiringEnabled = false;
                        properties.ListItem.SystemUpdate(false);
                        this.EventFiringEnabled = true;
                    }
                    catch (Exception)
                    {

                        throw;
                    }


                } // End Openweb 


            } // End if ListTitle == "Sags Info" 

        } // End ItemAdded 

        /// <summary> 
        /// An item was updated 
        /// </summary> 
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            if (properties.ListTitle == "Sags Info")
            {

                string strUrl = properties.WebUrl;


                long websiteid = int.Parse(properties.ListItem["LP_SagsID"].ToString());
                using (SPSite site = new SPSite(strUrl))
                using (SPWeb oWebsite = site.OpenWeb("Sager/" + websiteid.ToString()))
                {

                    SPList newl = oWebsite.Lists["SagsInfo"]; // Lars Printz 
                    if (newl.ItemCount == 0)
                    {
                        SPListItem newli = newl.Items.Add();
                        newli["Title"] = "Ny Sagsinfo";
                        newli.Update();

                    }
                    SPList l = oWebsite.Lists["SagsInfo"]; // Lars Printz 
                    SPListItem li = l.Items[0];
                    li["Title"] = properties.ListItem.Title;
                    li["LP_Postal"] = properties.ListItem["LP_Postal"];
                    li["LP_Address"] = properties.ListItem["LP_Address"];

                    if (properties.ListItem["LP_Sagstype"] != null)
                    {
                        string sagstypelookup = properties.ListItem["LP_Sagstype"].ToString();
                        string[] sagstypelookupArray = sagstypelookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

                        li["LP_Sagstype"] = sagstypelookupArray[0].ToString();
                    }
                    if (properties.ListItem["LP_Budtype"] != null)
                    {
                        string budtypelookup = properties.ListItem["LP_Budtype"].ToString();
                        string[] budtypelookupArray = budtypelookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

                        li["LP_Budtype"] = budtypelookupArray[0].ToString();
                    }
                    if (properties.ListItem["SagsStatus"] != null)
                    {
                        string sagsstatuslookup = properties.ListItem["SagsStatus"].ToString();
                        string[] sagsstatuslookupArray = sagsstatuslookup.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

                        li["SagsStatus"] = sagsstatuslookupArray[0].ToString();

                    }

                    li["Ansvarlig"] = properties.ListItem["Ansvarlig"];
                    li.Update();



                    SPFieldUrlValue value = new SPFieldUrlValue();

                    value.Description = properties.ListItem.Title + " - " + websiteid.ToString();

                    if (properties.WebUrl == "http://sharepointdev")
                    {
                        value.Url = "http://sharepointdev/sager/" + websiteid.ToString();
                    }
                    else
                    {
                        value.Url = "https://printz.sharepoint.com/Sager/" + websiteid.ToString();
                    }


                    properties.ListItem["LP_Sagslink"] = value;

                    try
                    {
                        this.EventFiringEnabled = false;
                        properties.ListItem.SystemUpdate(false);
                        this.EventFiringEnabled = true;
                    }
                    catch (Exception)
                    {

                        throw;
                    }


                } // End Openweb 


            } // End if ListTitle == "Sags Info" 

        }  // End ItemUpdated 

    }
}

The differences are:

  • as decribed above, not re-declaring the variable.
  • you didn't declare an spGroup variable, I've assumed you actually want to use the SPGroup object that you called owner.

The code compiles now.

share|improve this answer
    
That was a copy paste error when i made the post. I am reference spWebTemplate later in my code, it is there the red underline is in visual studio. –  Kevin Simper Aug 22 '12 at 11:36
    
@KevinSimper ok, another solution proposed. –  TZHX Aug 22 '12 at 11:42
    
When i do that it says: A local variable named 'spWebTemplate' cannot be declared in this scope because it would give a different meaning to 'spWebTemplate', which is already used in a 'parent or current' scope to denote something else. –  Kevin Simper Aug 22 '12 at 11:48
    
that means you have 'spWebTemplate' already defined above the code " SPWebTemplate spWebTemplate; " just remove SPWebTemplate spWebTemplate; if spWebTemplate is SPWebTemplate ;) –  ali Sharepoint Aug 22 '12 at 11:50
    
@KevinSimper ... yes. So don't re-declare it, simply use it. –  TZHX Aug 22 '12 at 11:52
show 6 more comments

The answer you marked as solution will work yes. However looking at your comment you don't seem to understand why your original code is not working. It is all about scope. So your homework today is to read about scope.

You declare your variables in the scope of an if-statement and then try to use them outside of said if-statement, it won't work, and it simple. your spWebTemplate and spGroup variables don't exist outside the scope where they are declared. And the error your receive is really clear on that point.

As you later did was putting the spWebTemplate and spGroup variables in a class scope which made your code work. Because now the variables are declared in the scope of the class and is there by accessibly to all your methods in that class.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.