Welcome to blogs.conchango.com Sign in | Join | Help

Welcome to blogs.conchango.com

Kalpesh Prajapati

  • Create and post form through Java Script to new window

    Very basic Java Script which require once in awhile in the world of ASP.NET.

    I came across the situation where requirement was to post form to basic ASP page from asp.net page. That can be done by using PostBackUrl property available in Button control. Now that is simple but PostBackUrl will post entire ASP.NET form and extra data will be posted.

     

    Complexity in requirement was that form should be posted to asp page to new window. I tried to find a lot to post data to new window using asp.net button control and PostBackUrl property. If you find please let me know. Then I had to write Java Script.

     

    Ok. Now here is code after lots of text and description.

     

    //Create form

    function createForm(formName, actionURL, target, method)

    {

        var oForm = document.createElement("form");

        oForm.name = formName; //Form name

        oForm.id = formName; // Form ID

        oForm.action = actionURL; // URL to post back

        oForm.target = target; // This is important. Use “_blank” if you wish to post back to new window

        oForm.method = method; // Method GET or POST

        return oForm;

    }

     

    //Create input fields

    function createInputField(name, value, type)

    {

        var oField = document.createElement("input");

        oField.name = name;

        oField.id = name;

        oField.value = value;

        oField.type = type; // Type normally “hidden”

        return oField;

    }

     

     

    //Append Field to form

    function appendField(oForm, oField)

    {

        oForm.appendChild(oField);

    }

     

    //Here is code to create form, field and submit the form

    function submitEligibilityForm(sNewFormAction, Field1Value, Field2Value)

    {

        var oForm = createForm("FormName", sNewFormAction,"_blank","POST");

     

        var oField = createInputField("Field1", Field1Value,"hidden");

        appendField(oForm,oField);

     

        oField = createInputField("Field2", Field2Value,"hidden");

        appendField(oForm,oField);

     

        document.appendChild(oForm); //This is required to add form to document

     

        oForm.submit();

    }

     

    Here is HTML code to create and submit the form

    <input tyep=”button” text=”click me” onlick=”submitToEligibilityHandoff('submitpage.asp',' Field2Value ', 'Field2Value'); return false;">

     

     

  • Playing with SharePoint web application's web.config file programmatically

    As a part deployment you may find it necessary to push out a change to a SharePoint web application's web.config. A web.config modification definition is expressed as a set of commands that, when processed by the web.config manipulator in Windows SharePoint Services, changes the state of web.config.

    I used the WebConfigModifications property of the SPWebApplication class to get the collection of web.config modifications in the Web application.

    There are different types of changes you may want to do in web.config.

    1)    Modify Attribute of some element .
    Let’s change trust level to Full. Trust element is child element of section <configuration><system.web> and Trust element has attribute “level”. Code to do this
       
       private void SetWebConfig(SPSite site)   // Site can be pass from Activate feature of any other context

            {

                SPWebApplication webApp = site.WebApplication;

                System.Collections.ObjectModel.Collection<SPWebConfigModification> allModifications = webApp.WebConfigModifications;

               

                SPWebConfigModification myModification = new SPWebConfigModification("level", "configuration/system.web/trust");

                myModification.Value = "Full"; // the value of the item to set.

                myModification.Owner = typeof(FeatureReceiver).FullName; // owner of the web.config modification

                myModification.Sequence = 1; // Sequence number the modification if more than one modification to be done increase this by one in each modification

                myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute; // the type of modification implied by the class in our case it is Ensure Attribute

                allModifications.Add(myModification);

               

                SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();

                webApp.Update(); 

            }



    2)    Add new Element in some section
    Let’s add new Assembly System.Web.Extensions.dll. Here is code to do this
          
          
           myModification = new SPWebConfigModification("add[@name=\"assembly\"]", "/configuration/system.web/compilation/assemblies");

                myModification.Value = "<add assembly=\"System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>";

                myModification.Sequence = 2;

                myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;

                myModification.Owner = typeof(FeatureReceiver).FullName;

                allModifications.Add(myModification);
               

    3)    Add new Section
    Let’s add new section <testSection></testSection> inside configuration . Here is code to do this

                
                myModification = new SPWebConfigModification ("testSection", "configuration");

                myModification.Value = “"<testSection></testSection>";

                myModification.Sequence = 3;

                myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureSection;

                myModification.Owner = typeof(FeatureReceiver).FullName;

                allModifications.Add(myModification);
               

    If you are doing multiple changes, call ApplyWebConfigModifications() after all changes added. I have used this code to create MOSS 2007 feature that enables MS AJAX Extension in MOSS site.



  • Programmatically creating Web Application, Site Collection and Web in MOSS 2007

    Classes and Object used…

    ·         SPWebApplicationBuilder: Creates an SPWebApplication object, providing default settings for all the required values and allowing the caller to change only those properties that need values different from the default

    ·         SPFarm: Represents a Windows SharePoint Services farm. To access the current server farm object, you can use members on SPFarm.Local.

    ·         SPWebApplication: Represents an Internet Information Services (IIS) load-balanced Web application that is installed on the server farm.

    ·         SPSiteCollection : Represents a collection of SPSite objects, or site collections.

    ·         SPSite : Represents a collection of sites on a virtual server, including a top-level site and all its subsites. Each SPSite object, or site collection, is represented within an SPSiteCollection object that consists of the collection of all site collections.

    ·         System.Security.SecureString: Represents text that should be kept confidential. The text is encrypted for privacy when being used, and deleted from computer memory when no longer needed. A SecureString object is similar to a String object in that it has a text value. However, the value of a SecureString object is automatically encrypted, can be modified until your application marks it as read-only, and can be deleted from computer memory by either your application or the .NET Framework garbage collector

     

    Let’s start...

     

    Creating web Application at Port no 2007 ( Assuming user spuser with password Password is present in system administrator group)

    SPWebApplicationBuilder webAppBuilder = new SPWebApplicationBuilder(SPFarm.Local);

    SPWebApplication newApplication;
    int myPort = 2007;

    webAppBuilder.Port = myPort;

    webAppBuilder.ApplicationPoolId = "site-appol"; // application pool

    webAppBuilder.ApplicationPoolUsername = webAppBuilder.DefaultZoneUri.Host + \\spuser;

    System.Security.SecureString password = new System.Security.SecureString();               

    string strName = "Password";               

    char[] pass = strName.ToCharArray();               

    foreach (char c in pass)               

        password.AppendChar(c);              

    webAppBuilder.ApplicationPoolPassword = password;

    webAppBuilder.CreateNewDatabase = true; // Create new database           

    webAppBuilder.DatabaseName = "wss_site2007_content";    // database name           

    webAppBuilder.DatabaseServer = webAppBuilder.DefaultZoneUri.Host;  //Host name/computer name          

    webAppBuilder.UseNTLMExclusively = true;  // Use NTLM authentication

    newApplication = webAppBuilder.Create(); // Create new web application
    newApplication.Provision();           //Provision it into web farm    

     

    Creating site Collection at root level with Blank site template

    SPSite mySiteCollection = newApplication.Sites.Add("/",                       //Root

    "Cgosite",              // site title

     "Conchango.com",             //description

    1033,                         //language

    "STS#1",                //Blank site template  

    webAppBuilder.ApplicationPoolUsername, // Site owner

    "Name",                 // Name

    "name@name.com"); //Email

     

    Creating web

    mySiteCollection.AllWebs.Add("/webname");

     

    Activating publishing feature at site collection
    mySiteCollection.Features.Add(SPFarm.Local.FeatureDefinitions["PublishingSite"].Id);

    SPFarm.Local.FeatureDefinitions["PublishingSite"].Provision()

     

    Close Site Collection
    mySiteCollection.Close();

  • How to Extend Virtual Machine Hard Disk ( VMWare)

    After long process of Goggling and experimenting I found few documents which partial solution to Extending Hard Disk is given. I have create straight forward steps for future reference and going to blog this next. Please let me know if steps need more info or typo found. It took my 2:30 hours and let me know how much time you will need to do same thing using following steps

    Here are steps to extend Virtual Machine’s Primary hard Disk

    Scenario:

    I have Virtual Machine(M1) with pre-allocated hard disk of size 6 GB. All the software and OS is installed on this disk. Latter state I need to install more software but disk is full and new software has to be installed on primary hark disk only. I have VM Server installed on Primary Drive. Let’s say Primary Drive is C. I want to make increase size to 10GB. My Virtual Hard Disk file is located at c:\mydisk.wmdk.

    How to do?

    This can be achieved by extending primary hard disk. Here are steps to do this. For this you need one more Virtual Machine. Assume we have two Virtual Machine M1 and M2. M1 is my working VM. M2 had Windows 2003 installed on it.

    1.    Turn off virtual Machine.

    2.    Start Command Window on Host Machine.

    3.    Move to VM Server directory. i.e. C:\Program Files\VMware\VMware Server

    4.    Type Command  vmware-vdiskmanager.exe -x 30Gb c:\myDisk.vmdk ( This will create 10 – 6 = 4GB of unallocated space on primary drive)

    5.    Now Move to M2’s Edit Virtual Machine Settings. Select Hard Disk and Click Add button.

    6.    Select Hardware Type Hard Disk and Press Next

    7.    Select Use an existing Virtual Disk and Press Next

    8.    Select Primary drive of Machine M1 and Press Finish

    9.    Start Virtual Machine M2.

    10. Move to Control Panel -> Administrative Tools -> Computer Management -> Storage -> Disk Management.

    11. You will see you list of Virtual Disk with allocated and unallocated space.  Let’s say new Virtual Disk is listed as Disk 1.

    12. From the run menu type "diskpart.exe" to enter the command line utility to resize disk partitions in Windows Server 2003.


    13. The command list volume will show you all the available volumes. Select your volume as shown below. select volume 1 corresponds to the "D" volume that I want to extend. Finally extend the volume with the extend command.


    14. If all goes well, the partition will be immediately extended under the Disk Management snap in.


    15.  Shut down the second Virtual Machine(M2) and remove the disk from the second Virtual Machine. Power on the first Virtual Machine(M1) and check out your new space.


     

  • Using ASP.NET Web Part into MOSS 2007 Web Site - Just Export and Import

    You can reuse ASP.NET Web Parts in your MOSS Web Site by exporting them to create .webpart files, which are XML files that contain details about your Web Part. To enable export functinality you need to do some modifications to your Web Part code and your configuration settings.

    After you have a .webpart file, you can import it into any MOSS Web Site.

    Step 1: To export an ASP.NET Web Part

    1.    In your Web Part code, set the ExportMode property to allow properties to be exported. In the following code, we set the value to All, which allows sensitive properties to be exported.
    this.ExportMode = WebPartExportMode.All;

    2.    Modify the <system.web> section of the web.config file as follows:
    <system.web> <webParts enableExport ="true"/> </system.web>

    3.    From the Web Part menu, choose Export to create a .webpart file you can import into a Windows SharePoint Services Web Part Page.
    Save file on Disk. Let’s say file name is mywebpart.webpart Please not you may get some security warning about properties set for the Web Part. Reset properties if you do not want this values to be exported.

    Step 2: To import a mywebpart.webpart file into Windows SharePoint Services

    1.    Place the assembly for your Web Part in the bin or the global assembly cache.

    If you place your assembly in the global assembly cache, your assembly must be strong named and run with full trust code permissions by default. The Web Part is available to all Web applications.

    If you place your assembly in the bin, you do not have full trust code permissions when your Web Part executes. Because the permissions for the bin directory are very low by default, for this add following code into AssemblyInfo.cs file of your web part project.
    [assembly: System.Security.AllowPartiallyTrustedCallers]

    2.    Add the Web Part to the Safe Controls list in your web.config file, for example:
    <SafeControl   Assembly="MyWebPart"   Namespace="MyWebParts"   TypeName="*"    Safe="True"/>

    3.    In Design mode, select Add a web part. At the bottom of the Add Web Parts dialog box, click Advanced Web Part gallery and options.

    4.    On the Add Web Parts pane, select Browse ->Import menu and then navigate to the .webpart file you created in the preceding procedure.

    5.    Click Upload and your Web Part appears in the list of Uploaded Web Parts.

    6.    Drag it into a Web Part zone on the page and you should see the same Web Part as on your ASP.NET page.

  • Enabling anonymous access for a site collection in MOSS 2007

    Suppose my Site Collection is http://servername/sites/CGOmain on MOSS 2007

    Steps 1:

    Go to “SharePoint 3.0 Central Administration”
    Select “Application Management” Tab
    Select “Authentication Provider” under “Application Security” group
    Select your web application.
    Select on the zone where you want o enable anonymous access. You will find check box “Enable Anonymous access”. Check it.
    Click “Save”
    When you set this option, anonymous access will also be enabled in IIS on your front-end servers.

    Steps 2:

    Open New Browser and navigate to your site where you want enable anonymous access.
    Select “Site Actions” Menu.
    In side menu select “Site Settings” -> “Modify All Site settings”.
    Now you are on “Site Settings” page. Select “Advanced permissions” under “Users and Permissions” group.
    Now you are on “Permissions” page. Select Menu “Settings” -> “Anonymous Access”.
    Now you are on “Change Anonymous Access Settings” page. Select radio button “Entire Web Site”
    Press “OK” button.

    Here we go. Site is now configured for anonymous access.

  • Exploring MOSS 2007

    Building Development Environment

    To start with SharePoint Server 2007 SDK
    The Microsoft Office SharePoint Server 2007 Software Development Kit (SDK) includes documentation, as well as code examples within the topics, for Microsoft Office SharePoint Server 2007

    Administrator's Guide for Windows SharePoint Services

    Share Point Blogs
    Login required. You need to create new account to access all the features

    Microsoft SharePoint Products and Technologies Team Blog - The official blog of the SharePoint Product Group

  • Community Recognition - Part 2

    Journey from “Member” to “Participant

     

    During Journey,

     

    I Learn
    How small missing piece of knowledge becomes problem in development.

    How to solve problem by asking question rather then directing to information and web links.

     

     

    Experience,

    During this phase, I come across many new problems and found solution by experimenting and learning from other’s experience.

     

     

    I Enjoy,

    Question from peoples that are very basic but answers are very tricky.
    To see how small mistakes becomes issue in development and takes many days.

     

    Did I really resolve the issues?

    Yes I resolved 35 forums where 1 marked as not resolved latter.

  • Accessing Non-public member of Class in .NET Framework

    Few days back I was looking into .NET Framework design. While playing with server controls I come across requirement where I need to invoke protected member of Object before doing some processing. I found one of the way to access non-public member of Class using reflection.

    Here is sample working code

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Reflection;

    namespace Reflection
    {
        public class A
        {
            private int m_nMember;
            public A()
            {
                m_nMember = 1;
            }
            protected int Member
            {
                get
                {
                    return m_nMember;
                }
                set
                {
                    m_nMember = value;
                }
            }

        }

        class Program
        {
            static void Main(string[] args)
            {
                A ObjectA = new A();
                Type type = typeof(A);
                PropertyInfo oPropertyInfo = type.GetProperty("Member", BindingFlags.Instance | //Specifies that instance members are to be included in the search.
                                                                        BindingFlags.NonPublic
                                                                    );
                //Get Value of protected property
                Object propvalue = oPropertyInfo.GetValue(ObjectA, null);
                //Print value of property
                Console.WriteLine("Value of " + oPropertyInfo.Name + " = " + propvalue.ToString());

                //Set Value of protected property
                oPropertyInfo.SetValue(ObjectA, 2, null );

                //Again Get Value of protected property
                propvalue = oPropertyInfo.GetValue(ObjectA, null);

                //Print value of property
                Console.WriteLine("Value of " + oPropertyInfo.Name + " = " + propvalue.ToString());

                Console.ReadLine();
            }
        }
    }

  • Community Recognition

    Few days back I was wondering for ASP.NET control related problem. I found interesting program run by asp.net web site. Please have look at http://www.asp.net/resources/community-recognition/default.aspx?tabid=41

    What is Community Recognition Program?
    The Community Recognition Program is a way to recognize each person’s contributions to the ASP.NET community.

    Community Recognition Levels
    The Program awards points for each person’s contributions to the site

Powered by Community Server (Personal Edition), by Telligent Systems