DataSync In Mvc4 for Two Different User - sql

I am trying to sync two database of a sql in mvc4 website?
i have this code to sync it is showing no error but it is not getting executing
using Microsoft.Synchronization;
using Microsoft.Synchronization.Data;
using Microsoft.Synchronization.Data.SqlServer;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Planetskool.Controllers
{
public class DataSyncViewController : Controller
{
//
// GET: /DataSyncView/
public ActionResult Index()
{
string sqlazureConnectionString = "Server=(LocalDb)\v11.0;Initial Catalog=aspnet-Planetskool-20130901224447;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-20130901224447.mdf";
string sqllocalConnectionString = "Server=(LocalDb)\v11.0;Initial Catalog=aspnet-Planetskool-20130901224446;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-20130901224446.mdf";
using (SqlConnection serverCon = new SqlConnection(sqlazureConnectionString))
using (SqlConnection clientCon = new SqlConnection(sqllocalConnectionString))
{
var provider1 = new SqlSyncProvider("scope1", serverCon);
var provider2 = new SqlSyncProvider("scope1", clientCon);
prepareServer(provider1);
prepareClinet(provider2, serverCon);
SyncOrchestrator sync = new SyncOrchestrator();
sync.LocalProvider = provider1;
sync.RemoteProvider = provider2;
sync.Synchronize();
return View();
}}
private static void prepareServer(SqlSyncProvider provider)
{
SqlConnection connection = (SqlConnection)provider.Connection;
SqlSyncScopeProvisioning config = new SqlSyncScopeProvisioning(connection);
if (!config.ScopeExists(provider.ScopeName))
{
DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(provider.ScopeName);
scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Author_Master", connection));
config.PopulateFromScopeDescription(scopeDesc);
config.SetCreateTableDefault(DbSyncCreationOption.CreateOrUseExisting);
config.Apply();
}
}
private static void prepareClinet(SqlSyncProvider provider, SqlConnection sourceConnection)
{
SqlConnection connection = (SqlConnection)provider.Connection;
SqlSyncScopeProvisioning config = new SqlSyncScopeProvisioning(connection);
if (!config.ScopeExists(provider.ScopeName))
{
DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(provider.ScopeName);
scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Author_Master", sourceConnection));
config.PopulateFromScopeDescription(scopeDesc);
config.Apply();
}
}
}
}

You can enable sync framework tracing in verbose mode to trace the synchronization. Likewise, did you forget to set the sync direction?

Related

"Validation failed for one or more entities. ERROR

I am creating web API to save the uploaded file in my local storage. When I testing my code it gives an error as ExceptionMessage": "Validation failed for one or more entities. See EntityValidationErrors' property for more details."
Can anyone help to fix this issue. Thanks in advance.
Controller(FileUploadController)
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using System.Collections.Generic;
using System.Web.Http;
using VantageCore.BL;
namespace VantageCoreApi.Controllers.Api
{
public class FileUploadController : ApiController
{
[HttpPost]
[Route("api/FileUpload")]
public async Task<IHttpActionResult> UploadFile(string FileName, int Id)
{
try
{
List<string> ids = new List<string>();
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var referenceId = FileName.Split('_')[0];
foreach (var file in provider.Contents)
{
Guid guid;
ids.Add(Guid.TryParse(await new FileUploadMgt().ReceiveFile(file, FileName, Id), out guid) ? FileName : "Error");
}
return Ok(ids);
}
catch (Exception e)
{
return InternalServerError(e);
}
}
public string SaveFile(byte[] File, string path)
{
string Result = "";
try
{
//LOCAL SERVER PATH
var fs = new BinaryWriter(new FileStream(#"F:\Testfolder" + path, FileMode.Append, FileAccess.Write));
fs.Write(File);
fs.Close();
Result = path;
}
catch (Exception ee)
{
Result = ee.ToString();
}
return Result;
}
}
}
BL (FileUplodMgt.cs)
using System;
using System.Threading.Tasks;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Net.Http;
using VantageCore.Entity.Model;
using File = VantageCore.Entity.Model.File;
namespace VantageCore.BL
{
public class FileUploadMgt
{
public async Task<string> ReceiveFile(HttpContent receivedFile, string receivedFileName, int Id)
{
if (receivedFile != null)
{
var fileId = Guid.NewGuid();
using (var c = new DBEntities())
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
string folder = appSettings["TestPath"];
var fileName = fileId.ToString() + Path.GetExtension(receivedFileName).ToLower();
var file = Path.Combine(folder, fileName);
bool exists = Directory.Exists(folder);
if (!exists) Directory.CreateDirectory(folder);
using (var fs = new BinaryWriter(new FileStream(file, FileMode.Create, FileAccess.Write)))
{
fs.Write(await receivedFile.ReadAsByteArrayAsync());
}
string extention = Path.GetExtension(file);
receivedFileName = Path.GetFileNameWithoutExtension(receivedFileName).Length <= 32
? Path.GetFileNameWithoutExtension(receivedFileName)
: Path.GetFileNameWithoutExtension(receivedFileName).Substring(0, 31) + "~";
var newFile = new File
{
Uid = fileId,
FileExtention = extention,
FileName = receivedFileName,
FileSize = (int)(receivedFile.Headers.ContentLength / 1024),
CreatedDate = DateTime.UtcNow
};
c.Files.Add(newFile);
c.SaveChanges();
}
return fileId.ToString();
}
else
{
return "Error,Invalid file Or file size exceeded";
}
}
}
}
You could try as below to observe the error message when you debug and share it;
try
{
c.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
}
}

Azure Key Vault Operation get is not allowed on a disabled secret

We have implemented Azure key vault in the .NET core application. Everything is working fine until we disabled the secret from the list - After my application tries to fetch the list again it started giving me the exception
Unhandled exception. Microsoft.Azure.KeyVault.Models.KeyVaultErrorException: Operation get is not allowed on a disabled secret.
at Microsoft.Azure.KeyVault.KeyVaultClient.GetSecretWithHttpMessagesAsync(String vaultBaseUrl, String secretName, String secretVersion, Dictionary`2 customHeaders, CancellationToken cancellationToken)
at Microsoft.Azure.KeyVault.KeyVaultClientExtensions.GetSecretAsync(IKeyVaultClient operations, String secretIdentifier, CancellationToken cancellationToken)
at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.LoadAsync()
at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.Load()
at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
at Microsoft.Extensions.Hosting.HostBuilder.BuildAppConfiguration()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at Vodafone.LandingPage.Program.Main(String[] args) in D:\a\1\s\src\LandingPage\Program.cs:line 30
Code I use to connect with Key Vault in program.cs file.
if (ctx.HostingEnvironment.IsProduction())
{
var builtConfig = builder.Build();
var keyVaultEndpoint = $"https://{builtConfig["AppSettings:KeyVaultName"]}.vault.azure.net/";
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));
builder.AddAzureKeyVault(keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
}
How we can restrict the list so that it will not take the disabled secrets together.
I am using "Get" and "List" permission.
After a research I found below solution.
You can use it like this
Problem : Code which read all secret
builder.AddAzureKeyVault(keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
Solution : Code Which read only enabled secrets
builder.AddAzureKeyVault(keyVaultEndpoint,keyVaultClient,new PrefixKeyVaultSecretManager(keyVaultEndpoint));
Implementation of IKeyVaultSecretManager
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.KeyVault.Models;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureKeyVault;
namespace KeyVaultPOC
{
public class PrefixKeyVaultSecretManager : IKeyVaultSecretManager
{
private readonly IList<string> _overrides = new List<string>();
public PrefixKeyVaultSecretManager(string vaultUrl)
{
Task.Run(() => LoadListOfOverrides(vaultUrl)).Wait();
}
private async Task LoadListOfOverrides(string vaultUrl)
{
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)
);
var secrets = await keyVaultClient.GetSecretsAsync(vaultUrl);
bool moreSecrets;
do
{
foreach (var secret in secrets)
{
if ((bool)secret.Attributes.Enabled)
{
_overrides.Add(secret.Identifier.Name);
}
}
moreSecrets = !string.IsNullOrEmpty(secrets.NextPageLink);
if (moreSecrets)
{
secrets = await keyVaultClient.GetSecretsNextAsync(secrets.NextPageLink);
}
} while (moreSecrets);
}
public bool Load(SecretItem secret)
{
return true;
}
public string GetKey(SecretBundle secret)
{
var key = secret.SecretIdentifier.Name;
return key;
}
}
}
Ref : https://gist.github.com/davidxcheng/0576659d2c876d299619d979767dcdd6

transfer local database (SQILLIT) on the Web(internet) in xamarin cod C# for Android

I want to transfer my local database on the Web, Please help me.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.IO;
using Mono.Data.Sqlite;
using Java.IO;
namespace Forooshgah
{
class cls_Connection
{
private static string DatabaseName = "DB_Forooshgah.db3";
private static string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
private static string DatabaseNameEndofYear;
private static Java.IO.File _dirBackup = new Java.IO.File(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "Do2ta/backup");
public static string getConnectionString()
{
string db = Path.Combine (path, DatabaseName);
return db;
}
public static SqliteConnection setConnection()
{
var databasePath = Path.Combine(path, DatabaseName);
//return new SqliteConnection(String.Format("Data Source={0};Password={1}", databasePath, "test"));
return new SqliteConnection(String.Format("Data Source={0};", databasePath));
}
This code is "Upload File using FTP"
protected void Upload(string dbpath)
{
try
{
// Get the object used to communicate with the server.
string url = "ftp://xxx.xxx.xxx.xxx/xxx/xxx";
FtpWebRequest request =(FtpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","someone#somesite.com");
FileStream file = File.OpenRead(dbpath);
byte[] buffer = new byte[file.Length];
file.Read (buffer, 0, (int)file.Length);
file.Close ();
Stream ftpStream = request.GetRequestStream ();
ftpStream.Write (buffer, 0, buffer.Length);
ftpStream.Close ();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
catch(Exception exc)
{
}
}

Is it possible to query public Big Query Data Sets using scripts without registering for billing

Is it possible to query public Big Query Data Sets such as https://www.githubarchive.org/ using C#/python scripts without registering for billing on Google Big Query. I have used the C# code attached but it gives me Insufficient Permission [403] error
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using Google.Apis.Util;
namespace BQTry
{
public class BigQueryConsole
{
static string query = "SELECT count(*) FROM [githubarchive:year.2014]";
static string projectId = "some project id";
public static void Main(string[] args)
{
Console.WriteLine("BigQueryAPI STARTINg");
Console.WriteLine("==========================");
String serviceAccountEmail = "someaccount#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"G:\CW and Research\TERM 2\SM\PROJECT\Code\BQTry\key\somekye.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { BigqueryService.Scope.DevstorageReadOnly }
}.FromCertificate(certificate));
// Create the service.
var service = new BigqueryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "BigQuery API Sample",
});
//Note: all your requests will run against Service.
JobsResource j = service.Jobs;
QueryRequest qr = new QueryRequest();
qr.Query = query;
QueryResponse response = j.Query(qr, projectId).Execute();
}
}
}
No matter what you do, you will need to enable billing, or send the credentials from a project that did.
So quick answer to your question : no. You will need to enable billing. Doesn't mean that, if all you do is query the public datasets, you'll pay.
As indicated here and in the linked docs on this page, the first TB of processed data each month is free.

Object reference not set to an instance of an object when using SPGridViewPager

It's my first sharepoint project and eveything looks very confusing.
I need to have a SPGridView with paging.
Here is an entire code of mx webpart:
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace FirstSPGridView.VisualWebPart1
{
[ToolboxItemAttribute(false)]
public class VisualWebPart1 : WebPart
{
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = #"~/_CONTROLTEMPLATES/FirstSPGridView/SPGridViewWebPartTest/VisualWebPart1UserControl.ascx";
SPGridView _grid;
protected override void CreateChildControls()
{
base.CreateChildControls();
try
{
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();
//Using RunWithElevatedPrivileges
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteCollection = new SPSite(mySite.ID))
{
using (SPWeb web = siteCollection.OpenWeb(myWeb.ID))
{
_grid = new SPGridView();
_grid.AutoGenerateColumns = false;
_grid.PageSize = 3;
_grid.AllowPaging = true;
_grid.DataSource = SelectData();
Controls.Add(_grid);
SPGridViewPager pager = new SPGridViewPager();
pager.GridViewId = _grid.ID;
this.Controls.Add(pager);
}
}
});
}
catch (Exception ex)
{ }
}
protected sealed override void Render(HtmlTextWriter writer)
{
try
{
GenerateColumns();
_grid.DataBind();
base.Render(writer);
}
catch (Exception e)
{
throw new NotImplementedException();
}
}
private void GenerateColumns()
{
BoundField clientNameColumn = new BoundField();
clientNameColumn.HeaderText = "Client";
clientNameColumn.DataField = "LastName";
_grid.Columns.Add(clientNameColumn);
BoundField birthDayColumn = new BoundField();
birthDayColumn.HeaderText = "BirthDate";
birthDayColumn.DataField = "BirthDate";
_grid.Columns.Add(birthDayColumn);
}
public DataTable SelectData()
{
var dataGet = new DataTable();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (
var conn =
new SqlConnection(
"Data Source=localhost;Initial Catalog=AdventureWorksDW2008R2;Integrated Security=True")
)
{
var adapter = new SqlDataAdapter();
adapter.SelectCommand =
new SqlCommand("Select TOP 100 LastName,Birthdate FROM DimCustomer");
adapter.SelectCommand.Connection = conn;
conn.Open();
adapter.Fill(dataGet);
}
});
return dataGet;
}
}
}
Everything was working (except paging until I added this code:
SPGridViewPager pager = new SPGridViewPager();
pager.GridViewId = _grid.ID;
this.Controls.Add(pager);
After that I get an exception on the Render method here:
base.Render(writer);
StackTrace is:
at System.Web.UI.Control.FindControl(String id, Int32 pathOffset)\r\n at Microsoft.SharePoint.WebControls.Menu.FindControlByWalking(Control namingContainer, String id)\r\n at Microsoft.SharePoint.WebControls.SPGridViewPager.get_GridViewControl()\r\n at Microsoft.SharePoint.WebControls.SPGridViewPager.Render(HtmlTextWriter output)\r\n at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)\r\n at System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer)\r\n at System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer)\r\n at FirstSPGridView.VisualWebPart1.VisualWebPart1.Render(HtmlTextWriter writer)
How can I fix that error?
You must just set ID for _grid.
For example, _grid.ID = "_gridView";