Programatically create an IIS website on button click [duplicate] - c#

We have been able to create a web site. We did this using the information in this link:
https://msdn.microsoft.com/en-us/library/ms525598.aspx
However, we would like to use a port number other that port 80. How do we do this?
We are using IIS 6

If you're using IIS 7, there is a new managed API called Microsoft.Web.Administration
An example from the above blog post:
ServerManager iisManager = new ServerManager();
iisManager.Sites.Add("NewSite", "http", "*:8080:", "d:\\MySite");
iisManager.CommitChanges();
If you're using IIS 6 and want to do this, it's more complex unfortunately.
You will have to create a web service on every server, a web service that handles the creation of a website because direct user impersonation over the network won't work properly (If I recall this correctly).
You will have to use Interop Services and do something similar to this (This example uses two objects, server and site, which are instances of custom classes that store a server's and site's configuration):
string metabasePath = "IIS://" + server.ComputerName + "/W3SVC";
DirectoryEntry w3svc = new DirectoryEntry(metabasePath, server.Username, server.Password);
string serverBindings = ":80:" + site.HostName;
string homeDirectory = server.WWWRootPath + "\\" + site.FolderName;
object[] newSite = new object[] { site.Name, new object[] { serverBindings }, homeDirectory };
object websiteId = (object)w3svc.Invoke("CreateNewSite", newSite);
// Returns the Website ID from the Metabase
int id = (int)websiteId;
See more here

Heres the solution.
Blog article : How to add new website in IIS 7
On Button click :
try
{
ServerManager serverMgr = new ServerManager();
string strWebsitename = txtwebsitename.Text; // abc
string strApplicationPool = "DefaultAppPool"; // set your deafultpool :4.0 in IIS
string strhostname = txthostname.Text; //abc.com
string stripaddress = txtipaddress.Text;// ip address
string bindinginfo = stripaddress + ":80:" + strhostname;
//check if website name already exists in IIS
Boolean bWebsite = IsWebsiteExists(strWebsitename);
if (!bWebsite)
{
Site mySite = serverMgr.Sites.Add(strWebsitename.ToString(), "http", bindinginfo, "C:\\inetpub\\wwwroot\\yourWebsite");
mySite.ApplicationDefaults.ApplicationPoolName = strApplicationPool;
mySite.TraceFailedRequestsLogging.Enabled = true;
mySite.TraceFailedRequestsLogging.Directory = "C:\\inetpub\\customfolder\\site";
serverMgr.CommitChanges();
lblmsg.Text = "New website " + strWebsitename + " added sucessfully";
}
else
{
lblmsg.Text = "Name should be unique, " + strWebsitename + " is already exists. ";
}
}
catch (Exception ae)
{
Response.Redirect(ae.Message);
}
Looping over sites whether name already exists
public bool IsWebsiteExists(string strWebsitename)
{
Boolean flagset = false;
SiteCollection sitecollection = serverMgr.Sites;
foreach (Site site in sitecollection)
{
if (site.Name == strWebsitename.ToString())
{
flagset = true;
break;
}
else
{
flagset = false;
}
}
return flagset;
}

Try the following Code to Know the unUsed PortNo
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
// Find unused ID PortNo for new web site
bool found_valid_port_no = false;
int random_port_no = 1;
do
{
bool regenerate_port_no = false;
System.Random random_generator = new Random();
random_port_no = random_generator.Next(9000,15000);
foreach (DirectoryEntry e in root.Children)
{
if (e.SchemaClassName == "IIsWebServer")
{
int site_id = Convert.ToInt32(e.Name);
//For each detected ID find the port Number
DirectoryEntry vRoot = new DirectoryEntry("IIS://localhost/W3SVC/" + site_id);
PropertyValueCollection pvcServerBindings = vRoot.Properties["serverbindings"];
String bindings = pvcServerBindings.Value.ToString().Replace(":", "");
int port_no = Convert.ToInt32(bindings);
if (port_no == random_port_no)
{
regenerate_port_no = true;
break;
}
}
}
found_valid_port_no = !regenerate_port_no;
} while (!found_valid_port_no);
int newportId = random_port_no;

I have gone though all answer here and also tested. Here is the most clean smarter version of answer for this question. However this still cant work on IIS 6.0. so IIS 8.0 or above is required.
string domainName = "";
string appPoolName = "";
string webFiles = "C:\\Users\\John\\Desktop\\New Folder";
if (IsWebsiteExists(domainName) == false)
{
ServerManager iisManager = new ServerManager();
iisManager.Sites.Add(domainName, "http", "*:8080:", webFiles);
iisManager.ApplicationDefaults.ApplicationPoolName = appPoolName;
iisManager.CommitChanges();
}
else
{
Console.WriteLine("Name Exists already");
}
public static bool IsWebsiteExists(string strWebsitename)
{
ServerManager serverMgr = new ServerManager();
Boolean flagset = false;
SiteCollection sitecollection = serverMgr.Sites;
flagset = sitecollection.Any(x => x.Name == strWebsitename);
return flagset;
}

This simplified method will create a site with default binding settings, and also create the application pool if needed:
public void addIISApplication(string siteName, string physicalPath, int port, string appPoolName)
{
using (var serverMgr = new ServerManager())
{
var sitecollection = serverMgr.Sites;
if (!sitecollection.Any(x => x.Name.ToLower() == siteName.ToLower()))
{
var appPools = serverMgr.ApplicationPools;
if (!appPools.Any(x => x.Name.ToLower() == appPoolName.ToLower()))
{
serverMgr.ApplicationPools.Add(appPoolName);
}
var mySite = serverMgr.Sites.Add(siteName, physicalPath, port);
mySite.ApplicationDefaults.ApplicationPoolName = appPoolName;
serverMgr.CommitChanges();
}
}
}

In properties of site select "Web Site" tab and specify TCP Port.
In studio to debug purpose specify http://localhost:<port>/<site> at tab Web for "Use Local IIS Web Server"

Related

Winform Cefsharp: Can't clear cache directory

I'm using CefSharp in my WinForm project.
I wan't to clear the cache directory in real time:
if (browser != null)
{
BrowserPanel.Controls.Remove(browser);
browser = null;
}
String cachePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + #"\TelegramParser\Users\" + userName;
if (Directory.Exists(cachePath))
{
Directory.Delete(cachePath, true);
}
But I always get an error that it is not possible to delete this directory.
This is how I declare the browser:
String cachePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + #"\TelegramParser\Users\" + userName;
if (!System.IO.Directory.Exists(cachePath))
{
System.IO.Directory.CreateDirectory(cachePath);
}
var requestContextSettings = new RequestContextSettings { CachePath = cachePath };
if (browser != null && BrowserPanel.Controls.Contains(browser))
BrowserPanel.Controls.Remove(browser);
browser = new ChromiumWebBrowser();
browser.RequestContext = new RequestContext(requestContextSettings, new CustomRequestContextHandler());
browser.Dock = DockStyle.Fill;
JsDialogHandler js1 = new JsDialogHandler();
browser.JsDialogHandler = js1;
BrowserPanel.Controls.Add(browser);
browser.Load("https://google.com/");
What can I do to fix this?
As of 85.4 it is possible to delete cache of a running CefSharp browser using DevToolsClient and Network.ClearBrowserChache. As mentioned on General Usage wiki of CefSharp.
private async Task ClearCache(object sender)
{
using (var devToolsClient = Browser.GetDevToolsClient())
{
var response = await devToolsClient.Network.ClearBrowserCacheAsync();
}
}
Note: this will not deleted the entire folder, it will however clear cached objects.

Assign App pool to site in IIS6 using c#

I am trying to create and assign application pool to a website in IIS6 and IIS7 using c#. I managed to do this for IIS7 using Microsoft.Web.Administration; but since its not supported in IIS6 i want to accomplish this using System.DirectoryServices;. I have managed to create the application pool but the assigning application pool does not work.
Here is what I have so far...
private static string DefaultAppPool = "DefaultAppPool";
public static void SetApplicationPoolIIS6(string websiteName)
{
string metabasePath = "IIS://localhost/W3SVC";
string appPoolName = GetSavedApplicationPoolName(websiteName);
if (string.IsNullOrEmpty(appPoolName) || appPoolName.Equals(DefaultAppPool))
appPoolName = websiteName + "AppPool";
bool isAppPoolCreated = IsAppPoolCreatedIIS6(websiteName, appPoolName);
if (!isAppPoolCreated)
CreateApplicationPoolIIS6(appPoolName, metabasePath);
DirectoryEntry w3svc = new DirectoryEntry(metabasePath);
w3svc.RefreshCache();
foreach (DirectoryEntry item in w3svc.Children)
{
string siteName = item.Properties["ServerComment"].Value == null ? "" : item.Properties["ServerComment"].Value.ToString();
if (string.IsNullOrEmpty(siteName))
continue;
if (siteName.Equals(websiteName))
{
item.Invoke("Stop", null);
item.Properties["AppPoolId"].Value = appPoolName;
item.CommitChanges();
item.Invoke("Start", null);
break;
}
}
w3svc.CommitChanges();
DirectoryEntry w3svc2 = new DirectoryEntry(metabasePath);
w3svc2.RefreshCache();
SaveWebSiteSettingsIIS6(websiteName, appPoolName);
}
Any idea why the below lines don't assign the created app pool ?
item.Properties["AppPoolId"].Value = appPoolName;
item.CommitChanges();
Any help is much appreciated. Thank you.

ProcessEvent not called in TFS plugin

Recently i have decided to create a plugin for the TFS for tracking work item changes based on ISubscriber interface.
So the workflow would be the following:
1) Work item state changes
2) Plugin catches the WorkItemChangedEvent
3) Send an email to the person specified in the Requester
As the base for my project, i used the following project from CodePlex - The Mail Alert
After i adopted it to my needs and saved compiled binaries in %TFS-DIR%\Microsoft Team Foundation Server 14.0\Application Tier\Web Services\bin\Plugins the TFS restarted the tier and... that's it. On work item change the ProcessEvent method is not called, but it should be.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Server;
using System.Diagnostics;
using System.Xml.Linq;
using System.Xml;
using System.DirectoryServices;
using System.Net.Mail;
using System.Xml.Xsl;
using System.Configuration;
using System.Reflection;
namespace MailAlert
{
public class WorkItemChangedEventHandler : ISubscriber
{
static string serverPath = "";
static string ExternalURL = "";
static string MailAddressFrom = "";
static string SMTPHost = "";
static string Password = "";
static int Port = 25;
static int index = 0;
static string projectCollectionFolder;
static Uri projectCollectionUri;
static WorkItemStore wiStore;
static WorkItem wItem;
static WorkItemChangedEvent workItemChangedEvent;
static string teamProjectPath = "";
static VersionControlServer versionControlServer;
static TfsTeamProjectCollection projectCollection;
static Dictionary<IdentityDescriptor, TeamFoundationIdentity> m_identities = new Dictionary<IdentityDescriptor, TeamFoundationIdentity>(IdentityDescriptorComparer.Instance);
public Type[] SubscribedTypes()
{
return new Type[1] { typeof(WorkItemChangedEvent) };
}
public WorkItemChangedEventHandler()
{
TeamFoundationApplicationCore.Log("WorkItemChangedEvent Started", index++, EventLogEntryType.Information);
}
public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext, NotificationType notificationType,
object notificationEventArgs, out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
{
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: ProcessEvent entered", index++, EventLogEntryType.Information);
statusCode = 0;
properties = null;
statusMessage = String.Empty;
GetTfsServerName();
projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(TfsTeamProjectCollection.GetFullyQualifiedUriForName(serverPath));
try
{
if (notificationType == NotificationType.Notification && notificationEventArgs is WorkItemChangedEvent)
{
workItemChangedEvent = notificationEventArgs as WorkItemChangedEvent;
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: WorkItem " + workItemChangedEvent.WorkItemTitle + " was modified", index++, EventLogEntryType.Information);
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: serverPath - " + serverPath, index++, EventLogEntryType.Information);
projectCollectionFolder = requestContext.ServiceHost.VirtualDirectory.ToString();
projectCollectionUri = new Uri(serverPath + projectCollectionFolder);
projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(projectCollectionUri);
wiStore = projectCollection.GetService<WorkItemStore>();
versionControlServer = projectCollection.GetService<VersionControlServer>();
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: Before process workitem", index++, EventLogEntryType.Information);
ProcessWorkItem();
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: After process workitem", index++, EventLogEntryType.Information);
}
}
catch (Exception ex)
{
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: FUCKING EXCEPTION! =>\n" + ex.Message, index++, EventLogEntryType.Error);
}
return EventNotificationStatus.ActionPermitted;
}
private static void GetTfsServerName()
{
try
{
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.Load(assemblyFolder + #"\Settings.xml");
// Declare the xpath for finding objects inside the XML file
XmlNodeList XmlDocNodes = XmlDoc.SelectNodes("/configuration/tfssettings");
XmlNodeList XmlDocExt = XmlDoc.SelectNodes("/configuration/Externaltfssettings");
// Define a new List, to store the objects we pull out of the XML
serverPath = XmlDocNodes[0].InnerText;
ExternalURL = XmlDocExt[0].InnerText;
XmlNodeList XmlDocNodes2 = XmlDoc.SelectNodes("/configuration/appSettings");
foreach (XmlNode mailNode in XmlDocNodes2)
{
foreach (XmlNode varElement in mailNode.ChildNodes)
{
switch (varElement.Attributes["key"].Value)
{
case "MailAddressFrom":
MailAddressFrom = varElement.Attributes["value"].Value;
break;
case "SMTPHost":
SMTPHost = varElement.Attributes["value"].Value;
break;
case "Password":
Password = varElement.Attributes["value"].Value;
break;
case "Port":
Port = Convert.ToInt32(varElement.Attributes["value"].Value);
break;
}
}
}
}
catch (Exception ex)
{
EventLog.WriteEntry("WorkItemChangedEventHandler", ex.Message);
}
}
public string Name
{
get { return "WorkItemChangedEventHandler"; }
}
public SubscriberPriority Priority
{
get { return SubscriberPriority.High; }
}
private static void ProcessWorkItem()
{
var teamProjects = versionControlServer.GetAllTeamProjects(false);
for (int i = 0; i < teamProjects.Length; i++)
{
string teamProjectName = teamProjects[i].Name;
var teamProject = teamProjects[i];
Project teamProjectWI = wiStore.Projects[i];
teamProjectPath = projectCollectionUri + teamProject.Name;
if (workItemChangedEvent.PortfolioProject == teamProjectName)
{
//get the workitem by ID ( CoreFields.IntegerFields[0] == ID ?!)
//check if any of String changed fields
foreach(StringField sf in workItemChangedEvent.ChangedFields.StringFields)
{
//is the State field
if (sf.Name.Equals("State"))
{
//then notify Reuqester
wItem = wiStore.GetWorkItem(workItemChangedEvent.CoreFields.IntegerFields[0].NewValue);
string CollGuid = projectCollection.InstanceId.ToString();
string Requester = wItem.Fields["Requester"].Value.ToString();
string WorkItemId = wItem.Id.ToString();
string mail = GetEmailAddress(Requester);
SendMail(CollGuid, WorkItemId, mail);
}
}
}
}
}
private static string GetEmailAddress(string userDisplayName)
{
DirectorySearcher ds = new DirectorySearcher();
ds.PropertiesToLoad.Add("mail");
ds.Filter = String.Format("(&(displayName={0})(objectCategory=person)((objectClass=user)))", userDisplayName);
SearchResultCollection results = ds.FindAll();
if (results.Count == 0)
{
return string.Empty;
}
ResultPropertyValueCollection values = results[0].Properties["mail"];
if (values.Count == 0)
{
return string.Empty;
}
return values[0].ToString();
}
private static void SendMail(string collID,string workItemId,string tomailAddrees)
{
MailMessage objeto_mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = Port;
client.Host = SMTPHost;
client.Timeout = 200000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential(MailAddressFrom, Password);
objeto_mail.From = new MailAddress(MailAddressFrom);
objeto_mail.To.Add(new MailAddress(tomailAddrees));
//objeto_mail.CC.Add(new MailAddress("nagarajb#hotmail.com"));
objeto_mail.Subject = "Work Item Changed:"+workItemId;
string mailbody = serverPath+"/tfs/web/wi.aspx?pcguid=" + collID + "&id=" + workItemId;
string mailbody2 = "";
if (ExternalURL.Length > 0)
{
mailbody2 = ExternalURL + "/tfs/web/wi.aspx?pcguid=" + collID + "&id=" + workItemId;
}
string tables = "<table border=1><tr><td>Work Item ID</td><td>" + wItem.Id.ToString() + "</td></tr><tr><td>Title</td><td>" + wItem.Title + "</td></tr><tr><td>State</td><td>" + wItem.State + "</td></tr><tr><td>Assigned To</td><td>" + wItem.Fields["Assigned to"].Value.ToString() + "</td></tr><tr><td>Internal URL</td><td>" + mailbody + "</td></tr><tr><td>External URL</td><td>" + mailbody2 + "</td></tr></table>";
objeto_mail.IsBodyHtml = true;
objeto_mail.Body = "<i>Hi " + wItem.Fields["Requester"].Value.ToString() + ","+"</i></br></br></br>" + tables + " </br></br> Best regards; </br></br>Configuration Management Team</br></br></br>";
client.Send(objeto_mail);
EventLog.WriteEntry("WorkItemChangedEventHandler", "Email Sent");
}
}
}
No errors or exceptions are thrown in the Event Log either. Tracing TFS (trace=true property in web.config) also was of no help.
Maybe someone could help or shed light on this mysterious case?
UPDATE:
Thanks for a reply Giulio Vian!
Here how it goes:
1) I haven't seen the dependencies broken, plus the constructor WorkItemChangedEventHandler is successfully called. That is seen in the Windows Event Log - WorkItemChangedEvent Started message is written.
2) I am not sure how to register the event handler.... i'll look that up
3) I am not sure how this works. I thought just copy-pasting dlls in the appropriate folder will do the trick, and there is no need for an account for the plugin. Mind giving a bit more info on this?
4) yes. Web.config in the main Web config in Application Tier\Web Services
5) Yes. Using an account with Administer rights. if i set a break point in the constructor, it is reached. Any other place in the code is not reached.
Many things can be wrong.
If any dependency is broken, you should see an error in the Event log
If you do not register the "WorkItemChangedEventHandler" event source, no message is written
Can the user account running the plugin access TFS?
How did you enabled the tracing (you pasted a bunch of code, but no configuration)?
Have you attached the debugger to the TFS process and set a breakpoint (do not this on a production TFS)?
We have collected similar suggestions in the documentation for our plugin at
https://github.com/tfsaggregator/tfsaggregator/wiki.

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'. when access local database

I have no idea.. why this occurs.
In debug mode it is running well .
however, now I am trying to run my project in IIS web server and
it doesn't runs well.
I can access the main page of my project. but when I try to access the local database, the following error shows up.
this is my log file and codes:
catch (Exception ex)
{
Debug.WriteLine("Error in integration: " + ex.Message);
Debug.Flush();
StreamWriter file2 = new StreamWriter("c:\\resources\\file.log", true);
file2.WriteLine("아님여기?"+ex.Message);
file2.Close(); //디버깅 계속................
}
In this catch I have the following error:
provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server
I am sorry that I can not explain which line is generating this exception because there's no exception occurring in debug mode...
Here is the code for Page Load:
protected void Page_Load(object sender, EventArgs e)
{
this.Page.Form.Enctype = "multipart/form-data";
WA = Request.QueryString["WA"];
if (string.IsNullOrEmpty(WA)) WA = "off";
string qstr = null;
qstr = Request.QueryString["vCnt"]; //ㅇㅈ이파라메터 들은 어디서...??
if (qstr != null && qstr != "") vCnt = Int32.Parse(qstr);
if (!IsPostBack)
{
Keywords = Request.QueryString["keywords"]; //ㅇㅈ search main -> searh 버튼 클릭
VideoSearch = Request.QueryString["VideoSearch"];//ㅇㅈ ~^~^~
// 스마트폰에서 포스팅 되었을 때
if (Request.UserAgent.Contains("Android"))
{
if (Request.Cookies["VIDEOSEARCH"] != null && Request.Cookies["VIDEOSEARCH"].Value != "")
{
VideoSearch = Request.Cookies["VIDEOSEARCH"].Value;
MAM.Models.Utils.CookieManager("VIDEOSEARCH", "");
}
}
if (!String.IsNullOrEmpty(Keywords) && !Keywords.Contains("null")) SearchTextbox2.Text = Keywords;
Debug.WriteLine("search text is " + SearchTextbox2.Text);
Debug.Flush();
try
{
if (!string.IsNullOrEmpty(VideoSearch))
{
//ㅇㅈ DNA를 추출하여 유사 동영상을 돌려받음.
string results = RetrieveDNAfromVideo(System.Web.HttpUtility.UrlDecode(VideoSearch)/*video name*/);
string[] lines = results.Split(new string[] { "\r\n" }, StringSplitOptions.None);
vSearchResults = new List<VSearchResult>();
foreach (string line in lines)
{
string[] words = line.Split(',');
VSearchResult vSearchResult = new VSearchResult();
vSearchResult.VideoID = Int32.Parse(words[0]);
vSearchResult.idx = Int32.Parse(words[1]);
vSearchResult.RGBdifferce = Int32.Parse(words[2]);
vSearchResults.Add(vSearchResult);
} //ㅇㅈ vSearchResults : RetrieveDNAfromVideo가 알려준유사동영상정보
MAMDataContext db = new MAMDataContext();
List<int> VideoIDs = (List<int>)vSearchResults.Select(v => v.VideoID).ToList();
//vdo = (List<Video>)(from a in db.Video
// join b in vSearchResults
// on a.id equals b.VideoID
// orderby b.RGBdifferce
// select a).ToList();
vdo = (List<Video>)(from a in db.Videos
where VideoIDs.Contains(a.id)
select a).ToList(); //ㅇㅈ vdo는 결국, RetrieveDNAfromVideo가 알려준유사동영상정보-> id가 같은동영상들
vSearchResults2 = new List<VSearchResult2>();
VSearchResult v1 = null;
foreach (Video v in vdo)
{
VSearchResult2 v2 = new VSearchResult2();
v2.VideoID = v.id;
v2.overview = v.overview;
v2.title = v.title;
v2.filename720 = v.filename720;
v2.filename360 = v.filename360;
v1 = vSearchResults.Where(t => t.VideoID == v.id).OrderBy(t => t.RGBdifferce).FirstOrDefault();//ㅇㅈ ㅇㄱㅁㅇ
// ㅇㅈ RetrieveDNAfromVideo가 알려준유사동영상정보-> id가 같은동영상들[-> RGBdifferce가 가장작은 애] [] 무슨의미??
v2.idx = v1.idx;
v2.RGBdifferce = v1.RGBdifferce;
vSearchResults2.Add(v2);
}
Debug.WriteLine("Video Serach done");
Debug.Flush();
}
if (!string.IsNullOrEmpty(Keywords))
{
string ret2 = null;
string str1 = null;
if (string.IsNullOrEmpty(Keywords))
{
Keywords = SearchTextbox2.Text;
}
if (string.IsNullOrEmpty(str1)) str1 = Keywords; //ㅇㅈ str1 은 질의의도??
string[] searchTextArray = str1.Split(' ');
int cnt1 = searchTextArray.Count();
string st1 = ""; string st2 = ""; string st3 = "";
if (cnt1 > 0) st1 = searchTextArray[0];
if (cnt1 > 1) st2 = searchTextArray[1];
if (cnt1 > 2) st3 = searchTextArray[2];
MAMDataContext db = new MAMDataContext();
vdo = (List<Video>)db.Videos.Where(v => v.overview.Contains(st1)
|| (cnt1 > 1 ? v.overview.Contains(st2) : false)
|| (cnt1 > 2 ? v.overview.Contains(st3) : false)).ToList();//ㅇㅈ 검색어를 overview에 가지고 있는 동영상 리스트
vSearchResults2 = new List<VSearchResult2>();
foreach (Video v in vdo)
{
VSearchResult2 v2 = new VSearchResult2();
v2.VideoID = v.id;
v2.overview = v.overview;
v2.title = v.title;
v2.filename720 = v.filename720;
v2.filename360 = v.filename360;
v2.idx = 0;
v2.RGBdifferce = 0;
vSearchResults2.Add(v2);
}
Debug.WriteLine("Video Search");
}
}
catch (Exception ex)
{
Debug.WriteLine("Error in integration: " + ex.Message);
Debug.Flush();
StreamWriter file2 = new StreamWriter("c:\\resources\\file.log", true);
file2.WriteLine(ex.Message);
file2.Close(); //디버깅 계속................
}
Debug.WriteLine("Search End");
}
if (fUpload.PostedFile != null) //ㅇㅈ
{
fileupload1();
}
else
{
}
}
this is a guess because you did not provide a key information: the connection string.
my guess is that the application is using integrated authentication hence while debugging the access to the database is done using your credentials: as the developer you are likely allowed to do almost everything on the db so the application works correctly.
when the application is deployed the login to the database is performed using the credentials of the application pool used to run the application itself.
as a test you can change the user of the application pool on the iis server to use an account enabled on the db and retry to login.
there are two solutions:
- configure the application pool to use a specific windows user that is allowed to interact with the db
- change the connection string to log onto the db as a sql user (allowed to interact with the db)

System.UnauthorizedAccessException was unhandled by user code in simple code

I got this exception in very easy code and I have running with elevated privileges around it.
It in sharepoint 2010
private void ChangeVersioningOnDocumentLibrary(SPListItem item, SPItemEventProperties properties, SPSite site)
{
string sitename = item[MeetingsCommon.Constants.FIELDS_TEXT_TITLE_NAME].ToString();
string prefix = item[MeetingsCommon.Constants.FIELDS_TEXT_TITLE_NAME].ToString().Substring(0, 2);
bool isConfirmed = item.TaxonomyFieldValueIsGivenValue(properties.AfterProperties, MeetingsCommon.Constants.FIELDS_MEETINGSTATUS_NAME, MeetingsCommon.Constants.TERMVALUE_MEETINGSTATUS_CONFIRMED, 1033);
bool isPublished = item.TaxonomyFieldValueIsGivenValue(properties.AfterProperties, MeetingsCommon.Constants.FIELDS_MEETINGSTATUS_NAME, MeetingsCommon.Constants.TERMVALUE_MEETINGSTATUS_PUBLISHED, 1033);
if (isConfirmed)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPWeb web = site.OpenWeb(prefix + "/" + sitename))
{
if (web.Exists)
{
web.AllowUnsafeUpdates = true;
SPList agendaPoints = web.GetSafeListByName(MeetingsCommon.Constants.LISTS_AGENDAPOINTS_NAME);
agendaPoints.EnableModeration = true;
agendaPoints.DraftVersionVisibility = DraftVisibilityType.Author;
agendaPoints.Update();
web.AllowUnsafeUpdates = false;
}
}
});
}
if (isPublished)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPWeb web = site.OpenWeb(prefix + "/" + sitename))
{
if (web.Exists)
{
web.AllowUnsafeUpdates = true;
SPList agendaPoints = web.GetSafeListByName(MeetingsCommon.Constants.LISTS_AGENDAPOINTS_NAME);
agendaPoints.EnableModeration = false;
agendaPoints.DraftVersionVisibility = DraftVisibilityType.Author;
agendaPoints.Update();
web.AllowUnsafeUpdates = false;
}
}
});
}
}
the problem is that it was using an spsite object coming from outside the RunWithElevatedPriviliges, the spsite object has to be created again inside in order for this to work.

Categories