I have written following code in visual stuadio 2008 to crete a new web application in sharepoint programmatically and getting following error like "Operation is not valid due to current state of the object" under invalidOperationException.
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPWebApplicationBuilder webAppBuilder = new SPWebApplicationBuilder(SPFarm.Local);
SPWebApplication newApplication;
int myPort = 20002;
webAppBuilder.Port = myPort;
webAppBuilder.RootDirectory = new System.IO.DirectoryInfo("C:\\Inetpub\\wwwroot\\wss\\VirtualDirectories\\" + myPort);
webAppBuilder.ApplicationPoolId = "AppPool1"; // application pool
webAppBuilder.ApplicationPoolUsername = "Anant_Raj";
System.Security.SecureString password = new System.Security.SecureString();
string strName = "#ana123";
char[] pass = strName.ToCharArray();
foreach (char c in pass)
password.AppendChar(c);
webAppBuilder.ApplicationPoolPassword = password;
webAppBuilder.CreateNewDatabase = true; // Create new database
webAppBuilder.DatabaseName = "wss_site2011_content"; // database name
webAppBuilder.DatabaseServer = webAppBuilder.DefaultZoneUri.Host; //Host name/computer name
webAppBuilder.UseNTLMExclusively = true; // Use NTLM authentication
webAppBuilder.AllowAnonymousAccess = true;
newApplication = webAppBuilder.Create(); // Create new web application
newApplication.Provision(); //Provision it into web farm
});
}
}
Any suggestion?
Try something like this.
protected void Page_Load(object sender, EventArgs e)
{
SPWebApplicationBuilder webAppBuilder;
SPWebApplication newApplication;
// Only the objects creation in the RunWithElevatedPrivileges block
SPSecurity.RunWithElevatedPrivileges(delegate()
{
webAppBuilder = new SPWebApplicationBuilder(SPFarm.Local);
});
// other statement outside the RunWithElevatedPrivileges block
int myPort = 20002;
webAppBuilder.Port = myPort;
webAppBuilder.RootDirectory = new System.IO.DirectoryInfo("C:\\Inetpub\\wwwroot\\wss\\VirtualDirectories\\" + myPort);
webAppBuilder.ApplicationPoolId = "AppPool1"; // application pool
webAppBuilder.ApplicationPoolUsername = "Anant_Raj";
System.Security.SecureString password = new System.Security.SecureString();
string strName = "#ana123";
char[] pass = strName.ToCharArray();
foreach (char c in pass)
password.AppendChar(c);
webAppBuilder.ApplicationPoolPassword = password;
webAppBuilder.CreateNewDatabase = true; // Create new database
webAppBuilder.DatabaseName = "wss_site2011_content"; // database name
webAppBuilder.DatabaseServer = webAppBuilder.DefaultZoneUri.Host; //Host name/computer name
webAppBuilder.UseNTLMExclusively = true; // Use NTLM authentication
webAppBuilder.AllowAnonymousAccess = true;
newApplication = webAppBuilder.Create(); // Create new web application
newApplication.Provision(); //Provision it into web farm
}
Related
How can this function be modified.
I want to use it to fill in the dataset from sqllite.
error
public void fillDATASET( DataSet ds, string tablename, string query)
{
string dbPath = Path.Combine(
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
"Department.db3");
var conn = new SQLite.SQLiteConnection(dbPath);
using (Mono.Data.Sqlite.SqliteCommand cmd = new SqliteCommand(query, conn))// error conn
{
using (var DataAdapterd = new SqliteDataAdapter(cmd))
{
ds.Clear();
DataAdapterd.Fill(ds, tablename);
}
}
}
This is because you use two different libraries.
var conn = new SQLite.SQLiteConnection(dbPath);
here you used the method in sqlite-net-pcl nuget,
Mono.Data.Sqlite.SqliteCommand cmd = new SqliteCommand(query, conn)
here you want use the method in System.Data.SQLite.Core nuget.
So you need to use a unified.
For example(use System.Data.SQLite.Core nuget):
using System.Data;
using System.Data.SQLite;
public void fillDATASET(DataSet ds, string tablename, string query)
{
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
"Department.db3");
var conn = new SQLiteConnection(dbPath);
using (SQLiteCommand cmd = new SQLiteCommand(query, conn))// error conn
{
using (var DataAdapterd = new SQLiteDataAdapter(cmd))
{
ds.Clear();
DataAdapterd.Fill(ds, tablename);
}
}
}
I am following the blog http://www.venkatbaggu.com/signalr-database-update-notifications-asp-net-mvc-usiing-sql-dependency/ to get a signalR push message out to connected clients.
My debugger never hits the onchange event.
my Global.asax.cs:
string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
protected void Application_Start()
{
// basic stuff
SqlDependency.Start(connString);
var repo = new Repositories.MarkerRepository();
repo.GetAllMarkers(); // to register the dependency
}
My MarkerRepository.cs:
readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
private MarkersHub _mh = new MarkersHub(); // my signalr hub class
public IEnumerable<House> GetAllMarkers()
{
var markers = new List<House>();
using (var connection = new SqlConnection(_connString))
{
connection.Open();
using (var command = new SqlCommand(#"SELECT * FROM [dbo].Houses", connection))
{
command.Notification = null;
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
markers.Add(item: new House {
ID = (int)reader["ID"],
Name = (string)reader["Name"],
Code = reader["Code"] != DBNull.Value ? (string)reader["Code"] : "",
Latitude = Convert.ToDouble(reader["Latitude"]),
Longitude = Convert.ToDouble(reader["Longitude"])
});
}
}
}
return markers;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
_mh.SendMarkers();
}
}
I have had a hit once but it was no change, only a notification for subscribe. I have read a lot about resubscribe, but when it hit this event the sql:
select * from sys.dm_qn_subscriptions
still returns no rows. Not on my db or master. So I think that there is an error in the blog post with the re-subscribe to the on change event? This sample https://msdn.microsoft.com/en-us/library/a52dhwx7(VS.80).aspx does unregister in the onchange event and calls the method which registers a new event. Can someone verify my assumption?
These were the values for the SqlNotificationEventArgs e in my event and told me that my query to depend on, was invalid.
SqlNotificationEventArgs.Type --> SqlNotificationType.Subscribe
SqlNotificationEventArgs.Info --> SqlNotificationInfo.Invalid
SqlNotificationEventArgs.Source --> SqlNotificationSource.Statement
The statement may not use the asterisk () or table_name. syntax to specify columns.
source https://msdn.microsoft.com/en-us/library/ms181122.aspx
I have been trying to use Postal on my MVC5 site. When I host my webpage a subsite ie, http://localhost/Subsite I am receiving the error
The virtual path '/' maps to another application, which is not allowed
I have debugged it down to when the ControllerContext is being created the HttpContext isn't getting set correctly. Since I'm running Postal from Hangfire the HttpContext.Current is always null. Postal creates the ContollerContext using the code below.
ControllerContext CreateControllerContext()
{
// A dummy HttpContextBase that is enough to allow the view to be rendered.
var httpContext = new HttpContextWrapper(
new HttpContext(
new HttpRequest("", UrlRoot(), ""),
new HttpResponse(TextWriter.Null)
)
);
var routeData = new RouteData();
routeData.Values["controller"] = EmailViewDirectoryName;
var requestContext = new RequestContext(httpContext, routeData);
var stubController = new StubController();
var controllerContext = new ControllerContext(requestContext, stubController);
stubController.ControllerContext = controllerContext;
return controllerContext;
}
string UrlRoot()
{
var httpContext = HttpContext.Current;
if (httpContext == null)
{
return "http://localhost";
}
return httpContext.Request.Url.GetLeftPart(UriPartial.Authority) +
httpContext.Request.ApplicationPath;
}
How can I specify the UrlRoot so that instead of pulling the default of localhost to pull it based on my subsite?
I followed the directions here http://docs.hangfire.io/en/latest/tutorials/send-email.html to send my email. The method in the tutorial is below
public static void NotifyNewComment(int commentId)
{
// Prepare Postal classes to work outside of ASP.NET request
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(#"~/Views/Emails"));
var engines = new ViewEngineCollection();
engines.Add(new FileSystemRazorViewEngine(viewsPath));
var emailService = new EmailService(engines);
// Get comment and send a notification.
using (var db = new MailerDbContext())
{
var comment = db.Comments.Find(commentId);
var email = new NewCommentEmail
{
To = "yourmail#example.com",
UserName = comment.UserName,
Comment = comment.Text
};
emailService.Send(email);
}
}
I found the issue was that the FileSystemRazorViewEngine was not being used bty postal. To get the this to work I had to make sure that the FileSystemRazorViewEngine was the first engine in the available. I then removed it because I did not want it to be the default engine. Below is my updated method.
public static void NotifyNewComment(int commentId)
{
// Prepare Postal classes to work outside of ASP.NET request
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(#"~/Views/Emails"));
var eng = new FileSystemRazorViewEngine(viewsPath));
ViewEngines.Engines.Insert(0, eng);
var emailService = new EmailService(engines);
// Get comment and send a notification.
using (var db = new MailerDbContext())
{
var comment = db.Comments.Find(commentId);
var email = new NewCommentEmail
{
To = "yourmail#example.com",
UserName = comment.UserName,
Comment = comment.Text
};
emailService.Send(email);
ViewEngines.Engines.RemoveAt(0)
}
}
Below is another possible solution that I think is more elegant than above. It also resolves an issue that appears when accessing the MVC application while the background process is being executed.
public static void SendTypedEmailBackground()
{
try
{
var engines = new ViewEngineCollection();
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(#"~/Views/Emails"));
var eng = new FileSystemRazorViewEngine(viewsPath);
engines.Add(eng);
var email = new WebApplication1.Controllers.EmailController.TypedEmail();
email.Date = DateTime.UtcNow.ToString();
IEmailService service = new Postal.EmailService(engines);
service.Send(email);
}
catch(Exception ex)
{
throw ex;
}
}
Can someone help me on this - in the code below the option 3 works fine for me, but that is a SYNC call, the Option 4 never returns which is true ASYNC, I need option 4 to work (the main difference is using AWAIT syntax).
// CODE from Controller within MVC APP
IRBVer01AdminSite.Data.ApiClient apic = new Data.ApiClient();
IRBVer01AdminSite.Models.Producer prd = new IRBVer01AdminSite.Models.Producer();
// opt 3 - Make a HTTP call to API DLL - BUT this one is Syncronous
source = null;
source = apic.RunAsync("http://localhost:56099/", string.Concat("api/producers/", id.ToString().Trim())).Result;
producer = null;
destination = null;
destination = Mapper.Map<IRBVer01CodeFirst.IRBVer01Domain.Producer>(source);
producer = destination;
if (producer == null)
return HttpNotFound();
//
// opt 4 - Make Http call to API DLL - Syncronous method (FAILS SO FAR)
source = null;
source = apic.GetAsyncData("http://localhost:56099/", string.Concat("api/producers/", id.ToString().Trim())).Result;
producer = null;
destination = null;
destination = Mapper.Map<IRBVer01CodeFirst.IRBVer01Domain.Producer>(source);
producer = destination;
if (producer == null)
return HttpNotFound();
//
// CODE FROM ApiClient CLASS within MVC APP
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
// called on OPT 3
public async Task<IRBVer01Api.Models.Producer> RunAsync(string urlBase, string urlPath)
{
IRBVer01Api.Models.Producer producer = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(urlBase);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetStringAsync(urlPath).Result; // No.1 - This is not SYNC, there is no AWAIT syntax used
producer = Task.Factory.StartNew(() => JsonConvert.DeserializeObject<IRBVer01Api.Models.Producer>(response)).Result;
}
return producer;
}
// called on OPT 4
public async Task<IRBVer01Api.Models.Producer> GetAsyncData(string urlBase, string urlPath)
{
IRBVer01Api.Models.Producer producer = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(urlBase);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetStringAsync(urlPath); // No.1 - This is ASYNC Version but comipler never comes back
//No.1 - for a moment forget about whats happening on the next syntax, the last line is not coming back... EVER
//producer = Task.Factory.StartNew(() => JsonConvert.DeserializeObject<IRBVer01Api.Models.Producer>(response)).Result;
}
return producer;
}
//
I have been trying to connect to Open LDAP using sample code from MSDN (Alex Tcherniakhovski)
http://blogs.msdn.com/b/alextch/archive/2012/05/07/sample-code-to-query-openldap-directory-via-net-system-directoryservices-protocols.aspx
I have tried on PORT 636 : ssl as it is in the sample code
And on PORT 389 non ssl to see if i could succeed
When trying on PORT 389 (with the same credentials I could connect to the OPEN LDAP using Softerra LDAP Browser)
I get the following error : The distinguished name contains invalid syntax.
I ran Microsoft Network Monitor and found out that some unwanted characters ââ get added to my Bind request just before my name. These characters never appear in the dotnet solution yet they are part of the request and make it fail.
Do you have an idea of how to get rid of these ?
I would have shown an image but i am not allowed.
My monitor shows BindRequest: Version:3, Name:ââcn=Manager,dc=...
in the dotnet code name is "cn=Manager,dc=.."
Using the code as is with SSL on port 636 lead to the following error : The LDAP server is unavailable.
I get the same error trying to connect with sslbind from Solution DirectoryServices.Protocol downloaded from here.
http://www.microsoft.com/en-us/download/confirmation.aspx?id=18086
Thanks for your help
using System.Collections.Generic;
using System.DirectoryServices.Protocols;
using System.Globalization;
using System.Net;
using System.Security;
namespace OpenLDAPNextUID
{
public class LDAPHelper
{
private readonly LdapConnection ldapConnection;
private readonly string searchBaseDN;
private readonly int pageSize;
public LDAPHelper(
string searchBaseDN,
string hostName,
int portNumber,
AuthType authType,
string connectionAccountName,
SecureString connectionAccountPassword,
int pageSize)
{
var ldapDirectoryIdentifier = new LdapDirectoryIdentifier(
hostName,
portNumber,
true,
false);
var networkCredential = new NetworkCredential(
connectionAccountName,
connectionAccountPassword);
ldapConnection = new LdapConnection(
ldapDirectoryIdentifier,
networkCredential)
{AuthType = authType};
ldapConnection.SessionOptions.ProtocolVersion = 3;
this.searchBaseDN = searchBaseDN;
this.pageSize = pageSize;
}
public IEnumerable<SearchResultEntryCollection> PagedSearch(
string searchFilter,
string[] attributesToLoad)
{
var pagedResults = new List<SearchResultEntryCollection>();
var searchRequest = new SearchRequest
(searchBaseDN,
searchFilter,
SearchScope.Subtree,
attributesToLoad);
var searchOptions = new SearchOptionsControl(SearchOption.DomainScope);
searchRequest.Controls.Add(searchOptions);
var pageResultRequestControl = new PageResultRequestControl(pageSize);
searchRequest.Controls.Add(pageResultRequestControl);
while (true)
{
var searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest);
var pageResponse = (PageResultResponseControl)searchResponse.Controls[0];
yield return searchResponse.Entries;
if (pageResponse.Cookie.Length == 0)
break;
pageResultRequestControl.Cookie = pageResponse.Cookie;
}
}
}
}
namespace OpenLDAP
{
class Program
{
static void Main(string[] args)
{
var password = new[]{'P','a','s','s','w','#','r','d'};
var secureString = new SecureString();
foreach (var character in password)
secureString.AppendChar(character);
var baseOfSearch = "dc=fabrikam,dc=com";
var ldapHost = "ubuntu.fabrikam.com";
var ldapPort = 636; //SSL
var ldapPort = 389; //not SSL
var connectAsDN = "cn=admin,dc=fabrikam,dc=com";
var pageSize = 1000;
var openLDAPHelper = new LDAPHelper(
baseOfSearch,
ldapHost,
ldapPort,
AuthType.Basic,
connectAsDN,
secureString,
pageSize);
var searchFilter = "nextUID=*";
var attributesToLoad = new[] {"nextUID"};
var pagedSearchResults = openLDAPHelper.PagedSearch(
searchFilter,
attributesToLoad);
foreach (var searchResultEntryCollection in pagedSearchResults)
foreach (SearchResultEntry searchResultEntry in searchResultEntryCollection)
Console.WriteLine(searchResultEntry.Attributes["nextUID"][0]);
Console.Read();
}
}
}