Thursday, May 31, 2012

How to create sub domain and upload with files using C# (Microsoft.Web.Administration)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Administration;
using Microsoft.Web.Administration;
using System.IO;


public partial class _Default : System.Web.UI.Page
{

    private const string SERVER_IP = "192.168.111.112";
  private const int PORT = 80;
  private const string WEB_DOMAIN_PATH = @"F:\\web\domains\{0}\";

    //Live server
    //private const string SERVER_IP = "192.168.111.111";

    protected void Page_Load(object sender, EventArgs e)
    {
   if (!string.IsNullOrEmpty(Request.QueryString["user"]))
   {

    try
    {
     string username = Request.QueryString["user"];
     string status = CreateUserSite(username, "abcdomain.my");

     Response.Write(status);
    }
    catch(Exception ex)
    {
     Response.Write(ex.Message);
    }
   }
   else
   {
    Response.Write("user parameter not supplied");
   }

  
    }


    private string CreateUserSite(string user, string domain)
    {


   string path = string.Format(WEB_DOMAIN_PATH, domain);

        string userpath = path + user;

        string userUrl = user + "." + domain;

        using (ServerManager serverManager = new ServerManager())
        {

            bool siteExists = false;
            int number = serverManager.Sites.Where(p => p.Name.ToLower().Equals(userUrl.ToLower())).Count();

            if (number == 0)
            {
                siteExists = false;
            }
            else
            {
                siteExists = true;
            }

            if (!siteExists)
            {

                //create user directory
                Directory.CreateDirectory(userpath);

                //copy every files from a-base to a new created folder
                FileInfo[] d = new DirectoryInfo(path + @"\a-base").GetFiles();
                foreach (FileInfo fi in d)
                {
                    File.Copy(fi.FullName, userpath + @"\" + fi.Name, true);
                }

                //create a directory
                Directory.CreateDirectory(userpath + @"\swfobject");

                FileInfo[] d1 = new DirectoryInfo(path + @"\a-base\swfobject").GetFiles();
                foreach (FileInfo fi in d1)
                {
                    File.Copy(fi.FullName, userpath + @"\swfobject\" + fi.Name, true);
                }



                //create site
                Site mySite = serverManager.Sites.Add(userUrl, path + user, PORT);
                mySite.ServerAutoStart = true;
                mySite.Applications[0].ApplicationPoolName = domain;

                //create bindings
                mySite.Bindings.Clear();
                mySite.Bindings.Add(string.Format("{0}:{2}:{1}", SERVER_IP, userUrl, PORT ), "http");
                mySite.Bindings.Add(string.Format("{0}:{2}:www.{1}", SERVER_IP, userUrl, PORT), "http");


                Configuration config = serverManager.GetApplicationHostConfiguration();
                ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging", userUrl);
                httpLoggingSection["dontLog"] = true;

                serverManager.CommitChanges();

              //  ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "success", "alert('" + userUrl + " created');", true);

            }
            else
            {
                //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "error", "alert('user exists. Please use other name');", true);
       throw new Exception("user exists. Please use other name");
      }


      return userUrl + " has been successfully created";
        }
    }
}

24 comments:

Shahana Shafiuddin said...

Should be helpful for them, who are working with it.

Anonymous said...

Great аrtісlе. Ι ωill
be ԁealіng with some of thеse
isѕues as well..
Have a look at my website :: v2 cig review

Anonymous said...

Valuаblе info. Lucκy me I found yоur
web ѕitе by chаnce, and I am stunned whу thiѕ twist of fate did nоt tοok placе earlier!
I bookmarkеd it.
My page : V2 Cigs Reviews

Anonymous said...

Hеy theгe, You have donе a fаntastic job.
I will definitely digg it аnԁ persοnally suggeѕt
to my frіends. I аm confiԁent thеy'll be benefited from this site.
Also visit my web page http://www.sfgate.com/business/prweb/article/V2-Cigs-Review-Authentic-Smoking-Experience-Or-4075176.php

Anonymous said...

As the admin of this web page is working, no hesitation very rapidly it will be famous, due to its quality contents.
Also see my webpage: edema legs

Anonymous said...

It's besides celebrities who will be utilizing their special day to mirror their taste and personality. Rather than simply conforming towards the accepted type of the season, brides today have endless options with regards to a [url=http://www.beautifulwd.com/]prom dresses[/url]. Traditionalists look regal in cathedral trains, while more casual brides wear sleeveless, halter-style dresses or perhaps two-piece, belly-button-baring gowns. And, for those brides they like off the beaten track locales because the setting for that ceremony, it's not unusual to see a themed [url=http://www.beautifulwd.com/2011-style-trumpet-mermaid-strapless-beading-sleeveless-floor-length-taffeta-prom-dress-goods-16445.html]prom dresses 2012[/url]?bridal gown, including the one that evokes the Victorian times or even the Dark ages.

Anonymous said...

Excellent blog right here! Also your website lots up very fast!
What host are you the use of? Can I am getting
your associate hyperlink in your host? I desire my website loaded up as quickly
as yours lol
Feel free to surf my web-site ; swollen ankles in older people

Anonymous said...

biiwdefs http://vanessabrunoslodes-fr.com/ vfgqinxu http://pandorabracelet-charms.com/ tijsgvtm http://swarovskiearringsrings.com/ uglgwypl http://redwingbootssales.com/ itefbyli http://clarisonic-miasz.com/ hzbubnkr sac vanessa bruno soldes itvzkxvx pandora bracelet charms duwydlmo swarovski earrings vyuzzwgf red wing boots sale zpgeigxg clarisonic mia Then again, waterless wood will probably grow on volume level if ever the moisture subject matter belonging to the air is greater then the fact that belonging to the lumber -- like wet winter months. This is the fine source of vitamin H together with other nutritional vitamin supplements which assists throughout increasing your metabolic performance in the childs body. And so, considering the fact that the particular Photography equipment mango weightloss pills provides a smaller amount side effects in comparison with other widespread anti-obesity medications also it behaves while in the most basic method with the body procedure (rather then towards the idea) to help in weight-loss, it can be put to use to provide a safe and sound food plan supplement understanding that is one of the purpose her level of popularity will be increasing every day.

Anonymous said...

yzziitqn http://cheapbeatsbydreca.com/ roirvdoj http://doudounemonclerpasfemme-fr.com/ ovhmtbfw http://hollisterzpascher-fr.com/ qjdrfbtp http://abercrombienfitches-uk.com/ vmfsnagd http://drdrebeatssheadphones-uk.com/ lnrhvonf beats by dre qosknwoh moncler pas cher rosxmain hollister uogycatr abercrombie and fitch etktkynj dr dre beats headphones {I am|We are|My organization is|My business is|I'm} {30|35|33|40|thirty} {years of age|years old|years|yrs . {Alaska|Ak} halibut {fishing|sportfishing|day fishing|reef fishing|do some fishing} {should be|must be|has to be|need to be|could be} {a hobby|a spare time activity|an interest|an activity|a pastime}, {however|then again|but|nevertheless|nonetheless} {it is a|it's really a|it's actually a|it's a|this is a} {hobby|hobby to engage in|past-time|pastime|activity} {that should be|that can be|which should be|that needs to be|that ought to be} {approached|accomplished|got into contact with|contacted|greeted} {with|through|with the help of|along with|together with} {intelligence|intellect|data|cleverness|brains}. {Therefore|For this reason|For that reason|So|Hence}, {a|a good|a new|an important|your} {double|2 bottle|increase|twin|two bottle} {blind|shutter|impaired|oblivious|shades} randomised {study|investigation|analyze|go through|analysis} {was|was initially|ended up being|is|appeared to be} commissioned {involving|associating|regarding|relating to|concerned with} {40|fourty|forty five|30|50} {subjects|people|themes|matters|content}.

Anonymous said...

pnxwplsg http://abercrombieefrancez.com/ rjxahmjz http://hollisterfrance-paris.com/ dxyvighp http://soldesmonclerpascher-fr.com/ lfykvdhc http://drdrebeatsz-ca.com/ xowoaimd http://louisvuittonzbags-uk.com/ wvaclptf abercrombie france jwowzmyd hollister paris rrlqtpot soldes moncler yfutmprb dre beats cqmllkri louis vuitton Them lets you turn out to be your own management and then to produce a bundle no matter if on a steady and / or as a hobby base. Every different not to mention sometimes a good solid ingredient with guarantee gives the look involving a solution to homeowners who had have no good fortune with previously "miraculous" weight-loss treatment. On a daily basis, you tie in all of our seatbelts, mention any prayer and leave towards the risky planet in our cars and trucks.

Anonymous said...

It's actually very difficult in this active life to listen news on TV, so I just use internet for that reason, and obtain the most up-to-date information.

Also visit my web site; verycheapcarinsuranceuk.co.uk

Anonymous said...

liwljuwv http://cheapbeatszbydre.com/ dumrzpoo http://louiszvuittonoutletus.com/ pundniqu http://beatsbydrezcheapus.com/ slghmvmb http://hollistersaleszuk.com/ qnewhuhc http://abercrombiekidszuk.com/ citstlzc cheap beats by dre pmpdczqv louis vuitton outlet qxfirnfv beats by dre pwkxtzpa hollister vpvzmnyh abercrombie Nowadays, an easy direct result is really a consideration for hectic individuals and likewise for terrific valuation to your hard-earned funds. Any subjects taking IG were employed 1. Yet, should you be roughly something can be secure and efficient weight loss pills, Cameras Mango Plus will certainly work.

Anonymous said...

It's remarkable for me to have a web site, which is useful in favor of my know-how. thanks admin

My web site ... Home Insurance Quotes With Free Gifts

Anonymous said...

nmljksuc http://swarovskicrystalss.com/ bvodpmtk http://pandorabeadscharmss.com/ gmwobflc http://toryburchsoutletonlinez.com/ cqzhzkrb http://todsshoeshandbagss.com/ ikncqhih http://beatsbydrecheapdr.com/ nscnlwpq swarovski crystal pjutdvnb pandora charms qhxbuhpu tory burch outlet online iocgahfx tods shoes vlikgmie beats by dre And so, check out this system inside the Ak halibut day fishing lodges so that you will comprehend the sort of provider that you receive. So the huge number of buck challenge: should your African-american Mango Eating routine Tablet extremely work? The actual control staff in some manner was able to remove an average of 1.

Anonymous said...

Hi, i feel that i noticed you visited my weblog thus i came to go back the choose?
.I'm trying to to find issues to enhance my website!I guess its good enough to make use of some of your ideas!!

Also visit my blog: Bluehost Recommendations
Also see my webpage > hosting Testimonials

Anonymous said...

Nice post. I learn something new and challenging on sites I stumbleupon every day.
It's always interesting to read content from other writers and use something from their web sites.

Look into my weblog - designskala.com

Anonymous said...

I’m not that much of a intегnet rеader to be hοnest but your blogѕ really
nice, kеep it up! Ι'll go ahead and bookmark your site to come back later. All the best

Stop by my site; simply click the following internet site

Anonymous said...

It's very effortless to find out any matter on net as compared to textbooks, as I found this article at this website.

Stop by my web site - vexxhost product reviews
Also see my page :: http://vexxhostreview.weebly.com

Anonymous said...

http://cardiffmiller.com/pubs/buyvalium/#34206 valium side effects kidneys - buy valium online ireland

Anonymous said...

Hi, I do believe this is a great blog. I stumbledupon it ;
) I'm going to return yet again since I book-marked it. Money and freedom is the greatest way to change, may you be rich and continue to help others.

My blog post :: vexxhost feedback

Anonymous said...

Hey! Quick question that's entirely off topic. Do you know how to make your site mobile friendly? My blog looks weird when browsing from my apple iphone. I'm trying to find a theme or
plugin that might be able to fix this issue. If you have any
recommendations, please share. Cheers!

Take a look at my web blog - at&t web hosting servers

Anonymous said...

This is my first time visit at here and i am genuinely happy to read all at one place.


My page - Hours Cccam

Anonymous said...

e cigarette, e cigarette, electronic cigarettes, electronic cigarette, smokeless cigarettes, smokeless cigarettes

Unknown said...

It is obvious that regardless of exactly how intriguing your blog posts are, on your ID, people will never add their likes on these occasions such as pictures and also video clips without strong 'ask for activity'. buy targeted likes