I would like to write an extension to Visual Studio, which will enable me to generate a model for specified table.
I have used the following code to add MyCommand item into context menu of table in server explorer:
Commands2 commands = (Commands2)_applicationObject.Commands;
CommandBar menuBarCommandBar = ((CommandBars)_applicationObject.CommandBars)["Object Node"];
Command command = commands.AddNamedCommand2(_addInInstance, "MyCommand", "MyCommand",
"Executes the command for MyCommand", true, 59, ref contextGUIDS,
(int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled,
(int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton);
if ((command != null) && (menuBarCommandBar != null))
{
command.AddControl(menuBarCommandBar, 1);
}
To get the name of the selected Table item:
string fileName = "Dafault.cs";
var serverExplorer = _applicationObject.ToolWindows.GetToolWindow("Server Explorer") as UIHierarchy;
if (serverExplorer != null)
{
dynamic item = ((object[])serverExplorer.SelectedItems)[0];
fileName = string.Format("{0}.cs", item.Name);
}
//...
// Generate model based on table from database
//...
_applicationObject.ItemOperations.NewFile("General\\Text File", fileName, Constants.vsViewKindCode);
How can I get information about the database connection?
Brad Larson, why my question was deleted?
Found the solution.
Used this
public static IDbConnection GetConnection(DSRefNavigator navigator, out string type)
{
type = null;
try
{
if (navigator != null)
{
IVsDataConnectionsService dataConnectionsService =
(IVsDataConnectionsService) Package.GetGlobalService(typeof(IVsDataConnectionsService));
string itemName = navigator.GetConnectionName();
if (itemName != null)
{
int iConn; // = dataConnectionsService.GetConnectionIndex(itemName);
DataViewHierarchyAccessor dataViewHierarchy = null;
for(iConn = 0; iConn < dataConnectionsService.Count; iConn++)
{
DataViewHierarchyAccessor hierarchyAccessor =
new DataViewHierarchyAccessor((IVsUIHierarchy) dataConnectionsService.GetConnectionHierarchy(iConn));
try
{
if (hierarchyAccessor.Connection.DisplayConnectionString == itemName)
{
dataViewHierarchy = hierarchyAccessor;
break;
}
}
catch
{
}
}
if (dataViewHierarchy != null)
{
DataConnection connection = dataViewHierarchy.Connection;
if (connection != null && connection.ConnectionSupport.ProviderObject != null)
{
type = connection.ConnectionSupport.ProviderObject.GetType().FullName;
return (IDbConnection) connection.ConnectionSupport.ProviderObject;
}
}
}
}
}
catch
{
}
return null;
}
Related
I am using multi-thread method while saving my email data to database with dapper. There was no problem in my local tests, but it gave an error when I published it on the server.
See my method here, the class I used and the error I got.
How can I solve it? (project is ASP.NET Core 3.1 MVC)
private MailBoxResultDto SaveMails(MailBoxResultDto modelResult)
{
var savedMails = new List<IncomingMailDto>();
var processCount = 0;
int threadCount = 0, maxThreadCount = 50;
foreach (var mail in modelResult.MailList)
{
while (threadCount >= maxThreadCount)
{
Thread.Sleep(100);
}
threadCount++;
var thread = new Thread(() =>
{
// Mail daha önce alınmışsa kaydetme, atla
//var isExistMail = _incomingMailRepository.GetAll()
// .Any(a => a.Date == mail.Date && a.Subject == mail.Subject && a.From == JsonConvert.SerializeObject(mail.MailFrom));
var orm = new DapperOrm(new SqlConnection());
var getMail = orm.QuerySingleOrDefault<IncomingMail>(SqlQueryString.IncomingMailIsExistQueryString(mail.Date, mail.Subject, mail.MailFrom.SerializeObject()));
if (getMail == null)
{
// save mail
var willBeInsertMail = mail.SelectEmailToEntity(attch => attch.SelectAttachmentToEntity(), false);
willBeInsertMail.TenantId = AbpSession.TenantId.Value;
willBeInsertMail.UserId = AbpSession.UserId.Value;
long savedMailID = 0;
//try { savedMailID = _incomingMailRepository.InsertAndGetId(willBeInsertMail); }
orm = new DapperOrm(new SqlConnection());
try { savedMailID = orm.InsertReturnId(willBeInsertMail); }
catch (Exception ex) { threadCount--; processCount++; return; }
// save mail attachments
foreach (var attachment in willBeInsertMail.Attachments)
{
// isim, boyut, değiştirme tarihi, contentType
//var isExistMailAttach = _incomingMailAttachmentRepository.GetAll()
// .Any(a => a.Name == attachment.Name && a.Size == attachment.Size && a.LastModifiedTime == attachment.LastModifiedTime && a.ContentType == attachment.ContentType);
orm = new DapperOrm(new SqlConnection());
var getMailAttachment = orm.QuerySingleOrDefault<IncomingMailAttachment>(SqlQueryString.IncomingMailAttachmentIsExistQueryString(attachment.Name, attachment.Size, attachment.LastModifiedTime, attachment.ContentType));
if (getMailAttachment == null)
{
attachment.MailId = savedMailID;
attachment.TenantId = AbpSession.TenantId.Value;
attachment.Id = 0;
//try { _incomingMailAttachmentRepository.Insert(attachment); }
orm = new DapperOrm(new SqlConnection());
try { orm.Insert(attachment); }
catch (Exception ex) { threadCount--; processCount++; return; }
}
}
var incomingMailDto = willBeInsertMail.SelectEmailToDTO(attach => attach.SelectEmailAttachmentToDTO(), false);
savedMails.Add(incomingMailDto);
}
threadCount--;
processCount++;
});
thread.SetApartmentState(ApartmentState.MTA); // <-- at the this point
thread.Priority = ThreadPriority.Highest;
thread.Start();
}
while (processCount < modelResult.MailList.Count)
{
Thread.Sleep(500);
}
if (savedMails.Count > 1)
return MailBoxResult.Success("Kaydedilen Mail Listesi Getirildi", savedMails);
else
return MailBoxResult.Warning($"Mailler Kaydedilemedi{(string.IsNullOrEmpty(modelResult.ErrorMessage) ? "" : $" : {modelResult.ErrorMessage}")}", null);
}
My Dapper Orm Class
public class DapperOrm
{
public SqlConnection SqlConnection { get; }
public string ConnectionString { get; } = "...sqlconnectionString...";
public DapperOrm(SqlConnection sqlConnection)
{
SqlConnection = sqlConnection;
SqlConnection.ConnectionString = ConnectionString;
}
public DapperOrm(SqlConnection sqlConnection, string connectionString)
{
SqlConnection = sqlConnection;
SqlConnection.ConnectionString = connectionString;
}
public IEnumerable<T> GetQuery<T>(string sqlQuery)
{
IEnumerable<T> result = null;
using (SqlConnection)
{
if (SqlConnection.State != System.Data.ConnectionState.Open)
{
SqlConnection.Close();
SqlConnection.Open();
}
result = SqlConnection.Query<T>(sqlQuery);
SqlConnection.Close();
}
return result;
}
public T QuerySingleOrDefault<T>(string sqlQuery)
{
T result;
using (SqlConnection)
{
if (SqlConnection.State != System.Data.ConnectionState.Open)
{
SqlConnection.Close();
SqlConnection.Open();
}
result = SqlConnection.QuerySingleOrDefault<T>(sqlQuery);
SqlConnection.Close();
}
return result;
}
public bool Insert<T>(T model) where T : IMustHaveTenant
{
bool result = false;
using (SqlConnection)
{
if (SqlConnection.State != System.Data.ConnectionState.Open)
{
SqlConnection.Close();
SqlConnection.Open();
}
var fieldModellessAndListLess = model.GetType().GetProperties()
.Where(s => (
s.PropertyType.BaseType.Name == "ValueType" ||
s.PropertyType.BaseType.Name == "Array" ||
s.PropertyType.Name == "String"
) && s.Name != "Id")
.ToList(); // model ve liste olan propertyler hariç
var tableFields = fieldModellessAndListLess.Select(s => s.Name).ToList();
var fieldNames = $"[{tableFields.Aggregate((a, b) => $"{a}], [{b}")}]";
var valueNames = $"#{tableFields.Aggregate((a, b) => $"{a}, #{b}")}";
result = SqlConnection.Execute($"INSERT INTO {SqlQueryString.GetTableName(model)} ({fieldNames}) VALUES({valueNames})", model) > 0;
SqlConnection.Close();
}
return result;
}
public long InsertReturnId<T>(T model) where T : IMustHaveTenant
{
long result = 0;
using (SqlConnection)
{
if (SqlConnection.State != System.Data.ConnectionState.Open)
{
SqlConnection.Close();
SqlConnection.Open();
}
var fieldModellessAndListLess = model.GetType().GetProperties()
.Where(s => (
s.PropertyType.BaseType.Name == "ValueType" ||
s.PropertyType.BaseType.Name == "Array" ||
s.PropertyType.Name == "String"
) && s.Name != "Id")
.ToList(); // model ve liste olan propertyler hariç
var tableFields = fieldModellessAndListLess.Select(s => s.Name).ToList();
var fieldNames = $"[{tableFields.Aggregate((a, b) => $"{a}], [{b}")}]";
var valueNames = $"#{tableFields.Aggregate((a, b) => $"{a}, #{b}")}";
result = SqlConnection.ExecuteScalar<long>($"INSERT INTO {SqlQueryString.GetTableName(model)} ({fieldNames}) OUTPUT Inserted.ID VALUES({valueNames})", model);
SqlConnection.Close();
}
return result;
}
}
public class SqlQueryString
{
public static string GetTableName<T>(T entity)
{
return $"{entity.GetType().Name}s";
}
public static string IncomingMailIsExistQueryString(DateTime mailDate, string subject, string mailFrom)
{
return $"SELECT TOP 1 Id FROM IncomingMails WHERE [Date] = '{mailDate:yyyy-MM-dd HH:mm:ss}' AND [Subject] = '{subject.Replace("'", "''")}' AND [From] = '{mailFrom.Replace("'", "''")}'";
}
public static string IncomingMailAttachmentIsExistQueryString(string name, int size, DateTime modifiedTime, string contentType)
{
return $"SELECT TOP 1 Id FROM IncomingMailAttachments WHERE [Name] = '{name}' AND [Size] = {size} AND [LastModifiedTime] = '{modifiedTime:yyyy-MM-dd HH:mm:ss}' AND [ContentType] = '{contentType.Replace("'", "''")}'";
}
}
Exception
System.PlatformNotSupportedException: COM Interop is not supported on this platform.
at CFCRM.Mails.Mailbox.MailBoxAppService.SaveMails(MailBoxResultDto modelResult) in /opt/crm/src/CFCRM.Application/Mails/Mailbox/MailBoxAppService.cs:line 343
at CFCRM.Mails.Mailbox.MailBoxAppService.SyncInboxMail() in /opt/crm/src/CFCRM.Application/Mails/Mailbox/MailBoxAppService.cs:line 151
at lambda_method(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
[1
Yes, we found the problem; Our project was running on linux server and I didn't know about it. EWS (Exchange Web Service) also gave an error because there is no linux server support.
Thanks for the comments guys.
Error:
Store update, insert, or delete statement affected an unexpected
number of rows (0). Entities may have been modified or deleted since
entities were loaded.
I am trying to upload a file into my database with few changes in it but each time it keeps giving me this error and won't update the values...
if (!addRecord) {
if (currentShiipingAddress != null) {
var shippingAddress = existingAccount.AccountAddresses.FirstOrDefault(m => m.Name == currentShiipingAddress.Name && m.AddressLine1 == currentShiipingAddress.AddressLine1 && m.AddTypeShipping == true);
if (shippingAddress == null) {
existingAccount.AccountAddresses.Add(currentShiipingAddress);
}
else {
shippingAddress.PostCode = currentShiipingAddress.PostCode;
shippingAddress.AddressLine1 = currentShiipingAddress.AddressLine1;
shippingAddress.AddressLine2 = currentShiipingAddress.AddressLine2;
shippingAddress.AddressLine3 = currentShiipingAddress.AddressLine3;
shippingAddress.DateUpdated = DateTime.UtcNow;
shippingAddress.AddTypeShipping = true;
context.Entry(shippingAddress).State = EntityState.Modified;
}
}
if (currentBillingAddress != null) {
var billingAddress = existingAccount.AccountAddresses.FirstOrDefault(m => m.Name == currentBillingAddress.Name && m.AddressLine1 == currentBillingAddress.AddressLine1 && m.AddTypeBilling == true);
if (billingAddress == null) {
existingAccount.AccountAddresses.Add(currentBillingAddress);
}
else {
billingAddress.PostCode = currentBillingAddress.PostCode;
billingAddress.AddressLine1 = currentBillingAddress.AddressLine1;
billingAddress.AddressLine2 = currentBillingAddress.AddressLine2;
billingAddress.AddressLine3 = currentBillingAddress.AddressLine3;
billingAddress.DateUpdated = DateTime.UtcNow;
billingAddress.AddTypeBilling = true;
context.Entry(billingAddress).State = EntityState.Modified;
}
}
if (invoiceCurrentContact != null) {
var existingContact = existingAccount.AccountContacts.FirstOrDefault(m => m.ContactEmail == invoiceEmail);
if (existingContact == null) {
existingAccount.AccountContacts.Add(invoiceCurrentContact);
}
else {
existingContact.ContactEmail = invoiceCurrentContact.ContactEmail;
existingContact.ContactName = invoiceCurrentContact.ContactName;
existingContact.TenantContactPhone = invoiceCurrentContact.TenantContactPhone;
existingContact.DateUpdated = DateTime.UtcNow;
context.Entry(existingContact).State = EntityState.Modified;
}
}
if (purchaseCurrentContact != null) {
var existingContact = existingAccount.AccountContacts.FirstOrDefault(m => m.ContactEmail == purchaseEmail);
if (existingContact == null) {
existingAccount.AccountContacts.Add(purchaseCurrentContact);
}
else {
existingContact.ContactEmail = purchaseCurrentContact.ContactEmail;
existingContact.ContactName = purchaseCurrentContact.ContactName;
existingContact.TenantContactPhone = purchaseCurrentContact.TenantContactPhone;
existingContact.DateUpdated = DateTime.UtcNow;
context.Entry(existingContact).State = EntityState.Modified;
}
}
}
else {
if (invoiceCurrentContact != null) {
existingAccount.AccountContacts.Add(invoiceCurrentContact);
}
if (purchaseCurrentContact != null) {
existingAccount.AccountContacts.Add(purchaseCurrentContact);
}
if (currentShiipingAddress != null) {
existingAccount.AccountAddresses.Add(currentShiipingAddress);
}
if (currentBillingAddress != null) {
existingAccount.AccountAddresses.Add(currentBillingAddress);
}
}
if (addRecord) {
context.Account.Add(existingAccount);
}
else {
context.Entry(existingAccount).State = EntityState.Modified;
}
This is where I am committing the changes to be saved but it turns out to give me the above-mentioned error
}
context.SaveChanges();
}
}
}
catch (Exception ex)
{
return "Import Failed : " + ex.Message + " " + counter.ToString();
}
return $"Supplier Account details imported successfully. Added { addedSuppliers }, Updated = { updatedSuppliers }";
}
I have a problem. I created a SwitchButton and want to store the state in a database table. So I created this code to debug:
SettingSwitch.CheckedChange += (s, b) =>
{
SettingDb testsetting = new SettingDb
{
Name = mItems[position].Name,
};
SettingDb test = MainActivity.db.SelectRowFromTableSettings(testsetting);
if (test != null)
{
bool SwitchValueBool = Convert.ToBoolean(test.Value);
}
bool isChecked = ValueDictionary[position];
if(isChecked == true)
{
isChecked = false;
}
else if(isChecked == false)
{
isChecked = true;
}
SettingDb setting = new SettingDb()
{
Name = SettingName.Text,
Type = "Switch",
Value = isChecked.ToString()
};
MainActivity.db.UpdateTableSettings(setting);
ValueDictionary[position] = isChecked;
SettingDb test2 = MainActivity.db.SelectRowFromTableSettings(testsetting);
if (test2 != null)
{
bool SwitchValueBool = Convert.ToBoolean(test2.Value);
}
};
The expected outcome should be:
test.Value = False
test2.Value = Opposite of test.Value, so True
But now the value I get from the table is always False. Here is the update function:
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
public bool UpdateTableSettings(SettingDb setting)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
{
connection.BeginTransaction();
connection.Query<SettingDb>("UPDATE SettingDb SET Value=? WHERE Name=?", setting.Value, setting.Name);
//connection.Update(setting);
connection.Commit();
return true;
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public SettingDb SelectRowFromTableSettings(SettingDb setting)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
{
return connection.Query<SettingDb>("SELECT * FROM SettingDb WHERE Name=?", setting.Name).FirstOrDefault();
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return null;
}
}
The table value doesn't get updated!!!
Can someone tell me what I am doing wrong?
Please let me know!
According to your description, you want to update sqlite database table, please take a look the following code and modify the update function.
static void UpdateDatabase(int primaryKey, string newText, int newValue)
{
string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "mydatabase.db");
var db = new SQLiteConnection(path, false);
string sql = "UPDATE MyTable SET MyTextColumn = ?, MyValueColumn = ? WHERE MyPrimaryKey= ?";
string[] parms = new String[] { newText, newValue.ToString(), primaryKey.ToString() };
var cmd = db.CreateCommand(sql, parms);
cmd.ExecuteNonQuery();
}
I've found APIs to regenerate keys for queues and topics, like:
TopicDescription topicDescription = namespaceManager.GetTopic(topicName);
SharedAccessAuthorizationRule rule;
bool topicSuccess = topicDescription.Authorization.TryGetSharedAccessAuthorizationRule("RootManageSharedAccessKey", out rule);
if (topicSuccess)
{
string newkey = SharedAccessAuthorizationRule.GenerateRandomKey();
rule.PrimaryKey = newkey;
namespaceManager.UpdateTopic(topicDescription);
}
The docs online claim that "you can configure the SharedAccessAuthorizationRule rule on the Service Bus namespaces, queues, or topics", however I can only find the C# API for queues and topics. I found a REST API for the namespace level, but nothing else.
Is there a supported way to regenerate the namespace-level keys?
You can regenerate the namespace key using Microsoft.Azure.Management.ServiceBus.Fluent library.
There is a method RegenerateKeysAsync available in this library to regenerate the access keys of the namespace.
All the namespace level operations can be done using this library.
You can follow this code repo for examples
Azure SDK for .NET
below code you would be interested in
public async Task<AzureOperationResponse<AccessKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (authorizationRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationRuleName");
}
if (authorizationRuleName != null)
{
if (authorizationRuleName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "authorizationRuleName", 50);
}
if (authorizationRuleName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "authorizationRuleName", 1);
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("authorizationRuleName", authorizationRuleName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "RegenerateKeys", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/regenerateKeys").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{authorizationRuleName}", System.Uri.EscapeDataString(authorizationRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<AccessKeys>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AccessKeys>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
Hope it helps.
MV
I create a project that check the sub domain and redirect to the exist subdomain ( username ) but I can't find out why when the username is in database it can't show it .
on local system it works finely .. but when I upload it on server it not works .. of course I change the commented place to uncomment for test .. but it's not working ..
it shows this error :
Object reference not set to an instance of an object.
My code is this in page load :
//Uri MyUrl = new Uri(Request.Url.ToString());
//string Url = MyUrl.Host.ToString();
Uri MyUrl = new Uri("http://Subdomain.Mydomain.com/");
string Url = MyUrl.Host.ToString();
string St1 = Url.Split('.')[0];
if ((St1.ToLower() == "Mydomain") || (St1.ToLower() == "Mydomain"))
{
Response.Redirect("Intro.aspx");
}
else if (St1.ToLower() == "www")
{
string St2 = Url.Split('.')[1];
if ((St2.ToLower() == "Mydomain") || (St2.ToLower() == "Mydomain"))
{
Response.Redirect("Intro.aspx");
}
else
{
object Blogger = ClsPublic.GetBlogger(St2);
if (Blogger != null)
{
lblBloger.Text = Blogger.ToString();
if (Request.QueryString["id"] != null)
{
GvImage.DataSourceID = "SqlDataSourceImageId";
GvComments.DataSourceID = "SqlDataSourceCommentsId";
this.BindItemsList();
GetSubComments();
}
else
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT TOP (1) fId FROM tblImages WHERE (fxAccepted = 1) AND (fBloging = 1) AND (fxSender = #fxSender) ORDER BY fId DESC", scn);
scm.Parameters.AddWithValue("#fxSender", lblBloger.Text);
scn.Open();
lblLastNo.Text = scm.ExecuteScalar().ToString();
scn.Close();
GvImage.DataSourceID = "SqlDataSourceLastImage";
GvComments.DataSourceID = "SqlDataSourceCommentsWId";
this.BindItemsList();
GetSubComments();
}
if (Session["User"] != null)
{
MultiViewCommenting.ActiveViewIndex = 0;
}
else
{
MultiViewCommenting.ActiveViewIndex = 1;
}
}
else
{
Response.Redirect("Intro.aspx");
}
}
}
else
{
object Blogger = ClsPublic.GetBlogger(St1);
if (Blogger != null)
{
lblBloger.Text = Blogger.ToString();
if (Request.QueryString["id"] != null)
{
GvImage.DataSourceID = "SqlDataSourceImageId";
GvComments.DataSourceID = "SqlDataSourceCommentsId";
this.BindItemsList();
GetSubComments();
}
else
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT TOP (1) fId FROM tblImages WHERE (fxAccepted = 1) AND (fBloging = 1) AND (fxSender = #fxSender) ORDER BY fId DESC", scn);
scm.Parameters.AddWithValue("#fxSender", lblBloger.Text);
scn.Open();
lblLastNo.Text = scm.ExecuteScalar().ToString();
scn.Close();
GvImage.DataSourceID = "SqlDataSourceLastImage";
GvComments.DataSourceID = "SqlDataSourceCommentsWId";
this.BindItemsList();
GetSubComments();
}
if (Session["User"] != null)
{
MultiViewCommenting.ActiveViewIndex = 0;
}
else
{
MultiViewCommenting.ActiveViewIndex = 1;
}
}
else
{
Response.Redirect("Intro.aspx");
}
}
and my class :
public static object GetBlogger(string User)
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT fUsername FROM tblMembers WHERE fUsername = #fUsername", scn);
scm.Parameters.AddWithValue("#fUsername", User);
scn.Open();
object Blogger = scm.ExecuteScalar();
if (Blogger != null)
{
SqlCommand sccm = new SqlCommand("SELECT COUNT(fId) AS Exp1 FROM tblImages WHERE (fxSender = #fxSender) AND (fxAccepted = 1)", scn);
sccm.Parameters.AddWithValue("fxSender", Blogger);
object HasQuty = sccm.ExecuteScalar();
scn.Close();
if (HasQuty != null)
{
int Count = Int32.Parse(HasQuty.ToString());
if (Count < 10)
{
Blogger = null;
}
}
}
return Blogger;
}
Which place if my code has problem ?
If it works fine locally, I guess the URL in the server has something to do with it.
Were you able to pinpoint exactly where you get the "Object reference not set to an instance of an object." exception? It would help to find the problem.
Anyway check this SO question where its mentioned that Request.Url.ToString() might behave differently in certain situations (Check the accepted answer) →
Request.Url.ToString() returns the machine name nested of the domain