How do I programmatically create a FTP site in IIS7 on Windows7? - iis

I am looking to do this step: 'Creating a New FTP Site by Editing the IIS 7.0 Configuration Files' with a batch file and was wondering if anybody has done this already?
http://learn.iis.net/page.aspx/301/creating-a-new-ftp-site/

Try this. You need to reference the COM component "AppHostAdminLibrary"
using AppHostAdminLibrary;
...
public void AddFtp7Site(String siteName, String siteId, String siteRoot) {
String configPath;
String configSectionName;
var fNewSite = false;
var fNewApplication = false;
var fNewVDir = false;
//
// First setup the sites section
//
configPath = "MACHINE/WEBROOT/APPHOST";
configSectionName = "system.applicationHost/sites";
var adminManager = new AppHostAdminLibrary.AppHostWritableAdminManager();
adminManager.CommitPath = configPath;
try {
var sitesElement = adminManager.GetAdminSection(configSectionName, configPath);
IAppHostElement newSiteElement = null;
//
// check if site already exists
//
for (var i = 0; i < sitesElement.Collection.Count; i++) {
var siteElement = sitesElement.Collection[i];
if (siteElement.Properties["name"].Value.Equals(siteName) &&
siteElement.Properties["id"].Value.Equals(siteId)) {
newSiteElement = siteElement;
break;
}
}
if (newSiteElement == null) {
//
// Site doesn't exist yet. Add new site node
//
newSiteElement = sitesElement.Collection.CreateNewElement("");
newSiteElement.Properties["id"].Value = siteId;
newSiteElement.Properties["name"].Value = siteName;
fNewSite = true;
}
// setup bindings for the new site
var ftpBindingString = "*:21:";
var Bindings = newSiteElement.GetElementByName("bindings");
var BindingElement = Bindings.Collection.CreateNewElement("");
BindingElement.Properties["protocol"].Value = "ftp";
BindingElement.Properties["bindingInformation"].Value = ftpBindingString;
try {
Bindings.Collection.AddElement(BindingElement, 0);
}
catch (Exception ex) {
if (ex.Message != "") // ERROR_ALREADY_EXISTS ?
{
throw;
}
}
IAppHostElement newApplication = null;
//
// check if root application already exists
//
for (var i = 0; i < newSiteElement.Collection.Count; i++) {
var applicationElement = newSiteElement.Collection[i];
if (applicationElement.Properties["path"].Value.Equals("/")) {
newApplication = applicationElement;
break;
}
}
if (newApplication == null) {
newApplication = newSiteElement.Collection.CreateNewElement("application");
newApplication.Properties["path"].Value = "/";
fNewApplication = true;
}
IAppHostElement newVirtualDirectory = null;
//
// search for the root vdir
//
for (var i = 0; i < newApplication.Collection.Count; i++) {
var vdirElement = newApplication.Collection[i];
if (vdirElement.Properties["path"].Value.Equals("/")) {
newVirtualDirectory = vdirElement;
break;
}
}
if (newVirtualDirectory == null) {
newVirtualDirectory = newApplication.Collection.CreateNewElement("");
newVirtualDirectory.Properties["path"].Value = "/";
fNewVDir = true;
}
newVirtualDirectory.Properties["physicalPath"].Value = siteRoot;
if (fNewVDir) {
newApplication.Collection.AddElement(newVirtualDirectory, 0);
}
if (fNewApplication) {
newSiteElement.Collection.AddElement(newApplication, 0);
}
var ftpSiteSettings = newSiteElement.GetElementByName("ftpServer").GetElementByName("security").GetElementByName("authentication");
Console.WriteLine("Enable anonymous authentication");
var anonAuthSettings = ftpSiteSettings.GetElementByName("anonymousAuthentication");
anonAuthSettings.Properties["enabled"].Value = "true";
Console.WriteLine("Disable basic authentication");
var basicAuthSettings = ftpSiteSettings.GetElementByName("basicAuthentication");
basicAuthSettings.Properties["enabled"].Value = "false";
BindingElement.Properties["bindingInformation"].Value = "*:21:";
//
// Time to add new site element and commit changes
//
if (fNewSite) {
sitesElement.Collection.AddElement(newSiteElement, 0);
}
adminManager.CommitChanges();
}
catch (Exception ex) {
Console.WriteLine("Error occured in AddDefaultFtpSite: " + ex.Message);
}
//
// Add <authorization> section to allow everyone Read
//
Console.WriteLine("Enable everyone Read access");
try {
configPath = "MACHINE/WEBROOT/APPHOST/" + siteName;
configSectionName = "system.ftpServer/security/authorization";
var azSection = adminManager.GetAdminSection(configSectionName, configPath);
azSection.Collection.Clear();
var newAzElement = azSection.Collection.CreateNewElement("");
newAzElement.Properties["accessType"].Value = "Allow";
newAzElement.Properties["users"].Value = "*";
newAzElement.Properties["permissions"].Value = "Read";
azSection.Collection.AddElement(newAzElement, 0);
adminManager.CommitChanges();
}
catch (Exception ex) {
Console.WriteLine("Error occured while adding authorization section: " + ex.Message);
}
}

Does this help?:
http://blogs.iis.net/jaroslad/archive/2007/06/13/how-to-programatically-create-an-ftp7-site.aspx

Related

Xamarin.iOS Cannot display photo in Push Notification

I have a Notification Service Extension and an AppGroup. I save a photo from camera in the PCL project and copy it to the App Group Container (shared folder).
In the Notification Service Extension I try to download the photo from the App Group container and attach it to the notification but it just does not display in the notification.
I also cannot debug the Service Extension to see what is going. As far as I know that is not possible currently still in Xamarin unless someone can correct me on that please.
Here is the code:
1.in my PCL I save the photo to the AppGroup when a save button is pressed:
private void ButtonSavePhoto_Clicked(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(photoFilePath))
{
Preferences.Set(AppConstants.CUSTOM_PICTURE_FILE_PATH, photoFilePath);
Preferences.Set(AppConstants.CUSTOM_PHOTO_SET_KEY, true);
if (Device.RuntimePlatform == Device.iOS)
{
bool copiedSuccessfully = DependencyService.Get<IPhotoService>().CopiedFileToAppGroupContainer(photoFilePath);
if (copiedSuccessfully)
{
var customPhotoDestPath = DependencyService.Get<IPhotoService>().GetAppContainerCustomPhotoFilePath();
// save the path of the custom photo in the AppGroup container to pass to Notif Extension Service
DependencyService.Get<IGroupUserPrefs>().SetStringValueForKey("imageAbsoluteString", customPhotoDestPath);
// condition whether to use custom photo in push notification
DependencyService.Get<IGroupUserPrefs>().SetBoolValueForKey("isCustomPhotoSet", true);
}
}
buttonSavePhoto.IsEnabled = false;
}
}
2.in my iOS project, Dependency injection calls this method when pressing save button:
public bool CopiedFileToAppGroupContainer(string filePath)
{
bool success = false;
string suiteName = "group.com.company.appName";
var appGroupContainerUrl = NSFileManager.DefaultManager.GetContainerUrl(suiteName);
var appGroupContainerPath = appGroupContainerUrl.Path;
var directoryNameInAppGroupContainer = Path.Combine(appGroupContainerPath, "Pictures");
var filenameDestPath = Path.Combine(directoryNameInAppGroupContainer, AppConstants.CUSTOM_PHOTO_FILENAME);
try
{
Directory.CreateDirectory(directoryNameInAppGroupContainer);
if (File.Exists(filenameDestPath))
{
File.Delete(filenameDestPath);
}
File.Copy(filePath, filenameDestPath);
success = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return success;
}
Now the path for the photo in the App Group container is:
/private/var/mobile/Containers/Shared/AppGroup/12F209B9-05E9-470C-9C9F-AA959D940302/Pictures/customphoto.jpg
3.Finally in the Notification Service Extension I try to attach the photo to the push notification:
public override void DidReceiveNotificationRequest(UNNotificationRequest request, Action<UNNotificationContent> contentHandler)
{
ContentHandler = contentHandler;
BestAttemptContent = (UNMutableNotificationContent)request.Content.MutableCopy();
string imgPath;
NSUrl imgUrl;
string notificationBody = BestAttemptContent.Body;
string notifBodyInfo = "unknown";
string suiteName = "group.com.company.appname";
NSUserDefaults groupUserDefaults = new NSUserDefaults(suiteName, NSUserDefaultsType.SuiteName);
string pref1_value = groupUserDefaults.StringForKey("user_preference1");
string[] notificationBodySplitAtDelimiterArray = notificationBody.Split(',');
userPrefRegion = notificationBodySplitAtDelimiterArray[0];
bool isCustomAlertSet = groupUserDefaults.BoolForKey("isCustomAlert");
bool isCustomPhotoSet = groupUserDefaults.BoolForKey("isCustomPhotoSet");
string alarmPath = isCustomAlertSet == true ? "customalert.wav" : "default_alert.m4a";
if (isCustomPhotoSet)
{
// this is the App Group url of the custom photo saved in PCL
imgPath = groupUserDefaults.StringForKey("imageAbsoluteString");
}
else
{
imgPath = null;
}
if (imgPath != null )
{
imgUrl = NSUrl.FromString(imgPath);
}
else
{
imgUrl = null;
}
if (!string.IsNullOrEmpty(pref1_value))
{
if (BestAttemptContent.Body.Contains(pref1_value))
{
if (imgUrl != null)
{
// download the image from the AppGroup Container
var task = NSUrlSession.SharedSession.CreateDownloadTask(imgUrl, (tempFile, response, error) =>
{
if (error != null)
{
ContentHandler(BestAttemptContent);
return;
}
if (tempFile == null)
{
ContentHandler(BestAttemptContent);
return;
}
var cache = NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User, true);
var cachesFolder = cache[0];
var guid = NSProcessInfo.ProcessInfo.GloballyUniqueString;
var fileName = guid + "customphoto.jpg";
var cacheFile = cachesFolder + fileName;
var attachmentUrl = NSUrl.CreateFileUrl(cacheFile, false, null);
NSError err = null;
NSFileManager.DefaultManager.Copy(tempFile, attachmentUrl, out err);
if (err != null)
{
ContentHandler(BestAttemptContent);
return;
}
UNNotificationAttachmentOptions options = null;
var attachment = UNNotificationAttachment.FromIdentifier("image", attachmentUrl, options, out err);
if (attachment != null)
{
BestAttemptContent.Attachments = new UNNotificationAttachment[] { attachment };
}
});
task.Resume();
}
BestAttemptContent.Title = "My Custom Title";
BestAttemptContent.Subtitle = "My Custom Subtitle";
BestAttemptContent.Body = "Notification Body";
BestAttemptContent.Sound = UNNotificationSound.GetSound(alarmPath);
}
}
else
{
pref1_value = "error getting extracting user pref";
}
// finally display customized notification
ContentHandler(BestAttemptContent);
}
/private/var/mobile/Containers/Shared/AppGroup/12F209B9-05E9-470C-9C9F-AA959D940302/Pictures/customphoto.jpg
From shared code, when image getting from AppGroup .You can check the file path whether work in this project.
imgPath = groupUserDefaults.StringForKey("imageAbsoluteString");
If not getting file from this path. You can get Url from AppGroup directly.Here is a sample as follow:
var FileManager = new NSFileManager();
var appGroupContainer = FileManager.GetContainerUrl("group.com.company.appName");
NSUrl fileURL = appGroupContainer.Append("customphoto.jpg", false);
And if fileURL can not be directly used, also can convert to NSData and save to local file system. This also can be a try.
Here is a sample below that grabs from local file system:
public static void Sendlocalnotification()
{
var localURL = "...";
NSUrl url = NSUrl.FromString(localURL) ;
var attachmentID = "image";
var options = new UNNotificationAttachmentOptions();
NSError error;
var attachment = UNNotificationAttachment.FromIdentifier(attachmentID, url, options,out error);
var content = new UNMutableNotificationContent();
content.Attachments = new UNNotificationAttachment[] { attachment };
content.Title = "Good Morning ~";
content.Subtitle = "Pull this notification ";
content.Body = "reply some message-BY Ann";
content.CategoryIdentifier = "message";
var trigger1 = UNTimeIntervalNotificationTrigger.CreateTrigger(0.1, false);
var requestID = "messageRequest";
var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger1);
UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
{
if (err != null)
{
Console.Write("Notification Error");
}
});
}

Get posted file over HTTP Listener in c#

I have make a simple http server using c#. And I know how to get posted data and output them. Here is my c# code
public static void start(){
HttpListener listener = new HttpListener();
listener.Prefixes.Add(new Uri("http://localhost:8080").ToString());
istener.Start();
while(true){
HttpListenerContext con = listener.GetContext();
showPostedData(con.Request);
con.Response.StatusCode = (int)HttpStatusCode.NotFound;
string data = "Uploaded successful";
byte[] output = Encoding.ASCII.GetBytes(data);
con.Response.ContentType = "text/html";
con.Response.ContentLength64 = output.Length;
con.Response.OutputStream.Write(output , 0, output.Length );
}
}
public static void showPostedData(HttpListenerRequest request){
if (!request.HasEntityBody)
{
return;
}
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
string text;
if (request.ContentType != null)
{
text = reader.ReadToEnd();
}
Console.WriteLine( text );
}
My client html form has input box named file: <input type="file" name"file">
In the console output is like that :
file='Path of Choosed file not a file'
So How i get POSTED files and copy them to upload directory..?
Sorry for my english and thanks in advance...
public static void start(){
HttpListener listener = new HttpListener();
listener.Prefixes.Add(new Uri("http://localhost:80").ToString());
istener.Start();
while(true){
HttpListenerContext con = listener.GetContext();
var values = new HttpNameValueCollection(ref con);
try
{
Console.WriteLine(values.Files["file"].FileName);
File.WriteAllText(values.Files["file"].FileName, values.Files["file"].FileData, Encoding.Default);
}
catch (Exception tr)
{
}
}
}
class HTTPFormData
{
public class File
{
private string _fileName;
public string FileName { get { return _fileName ?? (_fileName = ""); } set { _fileName = value; } }
private string _fileData;
public string FileData { get { return _fileData ?? (_fileName = ""); } set { _fileData = value; } }
private string _contentType;
public string ContentType { get { return _contentType ?? (_contentType = ""); } set { _contentType = value; } }
}
private NameValueCollection _post;
private Dictionary<string, File> _files;
private readonly HttpListenerContext _ctx;
public NameValueCollection Post { get { return _post ?? (_post = new NameValueCollection()); } set { _post = value; } }
public NameValueCollection Get { get { return _ctx.Request.QueryString; } }
public Dictionary<string, File> Files { get { return _files ?? (_files = new Dictionary<string, File>()); } set { _files = value; } }
private void PopulatePostMultiPart(string post_string)
{
var boundary_index = _ctx.Request.ContentType.IndexOf("boundary=") + 9;
var boundary = _ctx.Request.ContentType.Substring(boundary_index, _ctx.Request.ContentType.Length - boundary_index);
var upper_bound = post_string.Length - 4;
if (post_string.Substring(2, boundary.Length) != boundary)
throw (new InvalidDataException());
var current_string = new StringBuilder();
for (var x = 4 + boundary.Length; x < upper_bound; ++x)
{
if (post_string.Substring(x, boundary.Length) == boundary)
{
x += boundary.Length + 1;
var post_variable_string = current_string.Remove(current_string.Length - 4, 4).ToString();
var end_of_header = post_variable_string.IndexOf("\r\n\r\n");
if (end_of_header == -1) throw (new InvalidDataException());
var filename_index = post_variable_string.IndexOf("filename=\"", 0, end_of_header);
var filename_starts = filename_index + 10;
var content_type_starts = post_variable_string.IndexOf("Content-Type: ", 0, end_of_header) + 14;
var name_starts = post_variable_string.IndexOf("name=\"") + 6;
var data_starts = end_of_header + 4;
if (filename_index != -1)
{
var filename = post_variable_string.Substring(filename_starts, post_variable_string.IndexOf("\"", filename_starts) - filename_starts);
var content_type = post_variable_string.Substring(content_type_starts, post_variable_string.IndexOf("\r\n", content_type_starts) - content_type_starts);
var file_data = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
Files.Add(name, new File() { FileName = filename, ContentType = content_type, FileData = file_data });
}
else
{
var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
var value = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
Post.Add(name, value);
}
current_string.Clear();
continue;
}
current_string.Append(post_string[x]);
}
}
private void PopulatePost()
{
if (_ctx.Request.HttpMethod != "POST" || _ctx.Request.ContentType == null) return;
var post_string = new StreamReader(_ctx.Request.InputStream, _ctx.Request.ContentEncoding).ReadToEnd();
if (_ctx.Request.ContentType.StartsWith("multipart/form-data"))
PopulatePostMultiPart(post_string);
}
public HTTPFormData(ref HttpListenerContext ctx)
{
_ctx = ctx;
PopulatePost();
}
}

Command Timeout, longer to get response back

I am executing large query,so my app throwing time out error. Some of the thread suggested to added command time out but after adding those lines it take longer to get response back, any idea why or what am i missing in my code?
public int CreateRecord(string theCommand, DataSet theInputData)
{
int functionReturnValue = 0;
int retVal = 0;
SqlParameter objSqlParameter = default(SqlParameter);
DataSet dsParameter = new DataSet();
int i = 0;
try
{
//Set the command text (stored procedure name or SQL statement).
mobj_SqlCommand.CommandTimeout = 120;
mobj_SqlCommand.CommandText = theCommand;
mobj_SqlCommand.CommandType = CommandType.StoredProcedure;
for (i = 0; i <= (theInputData.Tables.Count - 1); i++)
{
if (theInputData.Tables[i].Rows.Count > 0)
{
dsParameter.Tables.Add(theInputData.Tables[i].Copy());
}
}
objSqlParameter = new SqlParameter("#theXmlData", SqlDbType.Text);
objSqlParameter.Direction = ParameterDirection.Input;
objSqlParameter.Value = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + dsParameter.GetXml();
//Attach to the parameter to mobj_SqlCommand.
mobj_SqlCommand.Parameters.Add(objSqlParameter);
//Finally, execute the command.
retVal = (int)mobj_SqlCommand.ExecuteScalar();
//Detach the parameters from mobj_SqlCommand, so it can be used again.
mobj_SqlCommand.Parameters.Clear();
functionReturnValue = retVal;
}
catch (Exception ex)
{
throw new System.Exception(ex.Message);
}
finally
{
//Clean up the objects created in this object.
if (mobj_SqlConnection.State == ConnectionState.Open)
{
mobj_SqlConnection.Close();
mobj_SqlConnection.Dispose();
mobj_SqlConnection = null;
}
if ((mobj_SqlCommand != null))
{
mobj_SqlCommand.Dispose();
mobj_SqlCommand = null;
}
if ((mobj_SqlDataAdapter != null))
{
mobj_SqlDataAdapter.Dispose();
mobj_SqlDataAdapter = null;
}
if ((dsParameter != null))
{
dsParameter.Dispose();
dsParameter = null;
}
objSqlParameter = null;
}
return functionReturnValue;
}

Why is parallel.Invoke not working in this case

I have an array of files like this..
string[] unZippedFiles;
the idea is that I want to parse these files in paralle. As they are parsed a record gets placed on a concurrentbag. As record is getting placed I want to kick of the update function.
Here is what I am doing in my Main():
foreach(var file in unZippedFiles)
{ Parallel.Invoke
(
() => ImportFiles(file),
() => UpdateTest()
);
}
this is what the code of Update loooks like.
static void UpdateTest( )
{
Console.WriteLine("Updating/Inserting merchant information.");
while (!merchCollection.IsEmpty || producingRecords )
{
merchant x;
if (merchCollection.TryTake(out x))
{
UPDATE_MERCHANT(x.m_id, x.mInfo, x.month, x.year);
}
}
}
This is what the import code looks like. It's pretty much a giant string parser.
System.IO.StreamReader SR = new System.IO.StreamReader(fileName);
long COUNTER = 0;
StringBuilder contents = new StringBuilder( );
string M_ID = "";
string BOF_DELIMITER = "%%MS_SKEY_0000_000_PDF:";
string EOF_DELIMITER = "%%EOF";
try
{
record_count = 0;
producingRecords = true;
for (COUNTER = 0; COUNTER <= SR.BaseStream.Length - 1; COUNTER++)
{
if (SR.EndOfStream)
{
break;
}
contents.AppendLine(Strings.Trim(SR.ReadLine()));
contents.AppendLine(System.Environment.NewLine);
//contents += Strings.Trim(SR.ReadLine());
//contents += Strings.Chr(10);
if (contents.ToString().IndexOf((EOF_DELIMITER)) > -1)
{
if (contents.ToString().StartsWith(BOF_DELIMITER) & contents.ToString().IndexOf(EOF_DELIMITER) > -1)
{
string data = contents.ToString();
M_ID = data.Substring(data.IndexOf("_M") + 2, data.Substring(data.IndexOf("_M") + 2).IndexOf("_"));
Console.WriteLine("Merchant: " + M_ID);
merchant newmerch;
newmerch.m_id = M_ID;
newmerch.mInfo = data.Substring(0, (data.IndexOf(EOF_DELIMITER) + 5));
newmerch.month = DateTime.Now.AddMonths(-1).Month;
newmerch.year = DateTime.Now.AddMonths(-1).Year;
//Update(newmerch);
merchCollection.Add(newmerch);
}
contents.Clear();
//GC.Collect();
}
}
SR.Close();
// UpdateTest();
}
catch (Exception ex)
{
producingRecords = false;
}
finally
{
producingRecords = false;
}
}
the problem i am having is that the Update runs once and then the importfile function just takes over and does not yield to the update function. Any ideas on what am I doing wrong would be of great help.
Here's my stab at fixing your thread synchronisation. Note that I haven't changed any of the code from the functional standpoint (with the exception of taking out the catch - it's generally a bad idea; exceptions need to be propagated).
Forgive if something doesn't compile - I'm writing this based on incomplete snippets.
Main
foreach(var file in unZippedFiles)
{
using (var merchCollection = new BlockingCollection<merchant>())
{
Parallel.Invoke
(
() => ImportFiles(file, merchCollection),
() => UpdateTest(merchCollection)
);
}
}
Update
private void UpdateTest(BlockingCollection<merchant> merchCollection)
{
Console.WriteLine("Updating/Inserting merchant information.");
foreach (merchant x in merchCollection.GetConsumingEnumerable())
{
UPDATE_MERCHANT(x.m_id, x.mInfo, x.month, x.year);
}
}
Import
Don't forget to pass in merchCollection as a parameter - it should not be static.
System.IO.StreamReader SR = new System.IO.StreamReader(fileName);
long COUNTER = 0;
StringBuilder contents = new StringBuilder( );
string M_ID = "";
string BOF_DELIMITER = "%%MS_SKEY_0000_000_PDF:";
string EOF_DELIMITER = "%%EOF";
try
{
record_count = 0;
for (COUNTER = 0; COUNTER <= SR.BaseStream.Length - 1; COUNTER++)
{
if (SR.EndOfStream)
{
break;
}
contents.AppendLine(Strings.Trim(SR.ReadLine()));
contents.AppendLine(System.Environment.NewLine);
//contents += Strings.Trim(SR.ReadLine());
//contents += Strings.Chr(10);
if (contents.ToString().IndexOf((EOF_DELIMITER)) > -1)
{
if (contents.ToString().StartsWith(BOF_DELIMITER) & contents.ToString().IndexOf(EOF_DELIMITER) > -1)
{
string data = contents.ToString();
M_ID = data.Substring(data.IndexOf("_M") + 2, data.Substring(data.IndexOf("_M") + 2).IndexOf("_"));
Console.WriteLine("Merchant: " + M_ID);
merchant newmerch;
newmerch.m_id = M_ID;
newmerch.mInfo = data.Substring(0, (data.IndexOf(EOF_DELIMITER) + 5));
newmerch.month = DateTime.Now.AddMonths(-1).Month;
newmerch.year = DateTime.Now.AddMonths(-1).Year;
//Update(newmerch);
merchCollection.Add(newmerch);
}
contents.Clear();
//GC.Collect();
}
}
SR.Close();
// UpdateTest();
}
finally
{
merchCollection.CompleteAdding();
}
}

SharePoint SPWeb.GetFile method with using server url and not using it at all

I notice that when we use SPWeb.GetFile method, we can pass the whole URL or only the part of the url.
Let's say my file exists in servername/sites/SiteA/DocumentLibrary/Folder/file.txt.
(i omit http)
SiteA = servername/sites/SiteA
using (SPWeb oWebsiteFrom = new SPSite(SiteA).OpenWeb())
{
SPFile oSrcSPFile = oWebsiteFrom.GetFile(ServerURL + "/" + DocLibrary+ "/" + Folder + "/" + fileName);
}
This one is also OK to use without ServerURL in GetFile.
using (SPWeb oWebsiteFrom = new SPSite(SiteA).OpenWeb())
{
SPFile oSrcSPFile = oWebsiteFrom.GetFile(DocLibrary+ "/" + Folder + "/" + fileName);
}
What is the difference between using serverURL and not using serverURL in GetFile method?
Basically it is the same.
Lot of SharePoint methods(not all) using Url as parameter will call an internal method named "GetWebRelativeUrlFromUrl" to handle the Url
And below are the code of the methods invoked when you call SPWeb.GetFile
As you can see, the string will parse as UriScheme object and if your string is a ServerRelative uriScheme, the method will "convert" it to absolute url.
internal SPFile GetFile(string strUrl, byte iLevel)
{
string webRelativeUrlFromUrl = this.GetWebRelativeUrlFromUrl(strUrl);
if (webRelativeUrlFromUrl.Length == 0)
{
throw new ArgumentException();
}
return new SPFile(this, webRelativeUrlFromUrl, iLevel);
}
internal string GetWebRelativeUrlFromUrl(string strUrl)
{
return this.GetWebRelativeUrlFromUrl(strUrl, true, true);
}
internal string GetWebRelativeUrlFromUrl(string strUrl, bool includeQueryString, bool canonicalizeUrl)
{
string str;
char[] chrArray;
if (strUrl == null)
{
throw new ArgumentNullException();
}
if (strUrl.Length == 0)
{
return strUrl;
}
if (canonicalizeUrl || !includeQueryString)
{
strUrl = Utility.CanonicalizeFullOrRelativeUrl(strUrl, includeQueryString, out flag);
canonicalizeUrl = 0;
includeQueryString = 1;
}
UriScheme uriScheme = SPWeb.GetUriScheme(strUrl);
if (uriScheme == UriScheme.ServerRelative)
{
string serverRelativeUrl = this.ServerRelativeUrl;
if (!SPUtility.StsStartsWith(strUrl, serverRelativeUrl))
{
throw new ArgumentException();
}
str = strUrl.Substring(serverRelativeUrl.Length);
if (str.Length > 0)
{
if (str.get_Chars(0) == 47)
{
return str.Substring(1);
}
if (uriScheme == UriScheme.Http || uriScheme == UriScheme.Https)
{
if (uriScheme == UriScheme.Http && strUrl.Contains(":80/"))
{
strUrl = strUrl.Remove(strUrl.IndexOf(":80/"), ":80/".Length - 1);
}
bool flag2 = false;
if (!SPUtility.StsStartsWith(strUrl, this.Url))
{
using (SPSite sPSite = new SPSite(strUrl))
{
if (sPSite.ID != this.Site.ID)
{
throw new ArgumentException();
}
UriBuilder uriBuilder = new UriBuilder(new Uri(strUrl));
uriBuilder.Scheme = sPSite.Protocol.TrimEnd(new char[] { 58 });
uriBuilder.Host = sPSite.HostName;
uriBuilder.Port = sPSite.Port;
strUrl = uriBuilder.Uri.ToString();
}
flag2 = SPUtility.StsStartsWith(strUrl, this.Url);
}
else
{
flag2 = true;
}
if (flag2)
{
str = strUrl.Substring(this.Url.Length);
if (str.Length > 0)
{
if (str.get_Chars(0) == 47)
{
return str.Substring(1);
}
throw new ArgumentException();
if (!strUrl.StartsWith("_"))
{
bool flag3 = true;
try
{
if (false || -1 == strUrl.IndexOf(58) || null != new Uri(strUrl))
{
flag3 = false;
}
}
catch
{
}
if (!flag3)
{
throw new ArgumentException();
}
}
str = strUrl;
}
}
}
}
}
return str;
}

Resources