【发布时间】:2020-10-04 21:29:42
【问题描述】:
我有一个控制台应用程序,它根据用户输入更新数据库中名为 InstagramId 的列。我希望能够查询数据库,如果有一个为空的 instagramId,则根据他们的 instagramUsername 使用正确的 instagramID 更新它。
我不确定是否应该根据所有 null instagramId 创建一个假表,然后使用它们来更新我的列,或者是否有另一种更简洁的方法。此控制台应用程序只能使用一次,因此只需快速修复即可。
class Program
{
static async Task Main(string[] args)
{
// receive a profile name
var tasks = new List<Task<InstagramUser>>();
foreach (var arg in args)
{
if (string.IsNullOrEmpty(arg)) continue;
var profileName = arg;
var url = $"https://instagram.com/{profileName}";
tasks.Add(ScrapeInstagram(url));
}
try
{
var instagramUsers = await Task.WhenAll<InstagramUser>(tasks);
foreach (var iu in instagramUsers)
{
iu.Display();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
public static async Task<InstagramUser> ScrapeInstagram(string url)
{
using (var client = new HttpClient())
{
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
// create html document
var htmlBody = await response.Content.ReadAsStringAsync();
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(htmlBody);
// select script tags
var scripts = htmlDocument.DocumentNode.SelectNodes("/html/body/script");
// preprocess result
var uselessString = "window._sharedData = ";
var scriptInnerText = scripts[0].InnerText
.Substring(uselessString.Length)
.Replace(";", "");
// serialize objects and fetch the user data
dynamic jsonStuff = JObject.Parse(scriptInnerText);
dynamic userProfile = jsonStuff["entry_data"]["ProfilePage"][0]["graphql"]["user"];
//Update database query
string connectionString = @"Server=mockup-dev-db";
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("Update ApplicationUser Set InstagramId = '" + userProfile.id + "'" + "where Instagram = '" + userProfile.username + "'", con);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
// create an InstagramUser
var instagramUser = new InstagramUser
{
FullName = userProfile.full_name,
FollowerCount = userProfile.edge_followed_by.count,
FollowingCount = userProfile.edge_follow.count,
Id = userProfile.id,
url = url
};
return instagramUser;
}
else
{
throw new Exception($"Something wrong happened {response.StatusCode} - {response.ReasonPhrase} - {response.RequestMessage}");
}
}
}
}
}
【问题讨论】:
-
您当前的解决方案有什么问题?简短的外观表明它应该可以正常工作。
-
它目前仅在一次搜索一个时才有效。例如。我将运行调试文件并拥有用户名 (test.nora),它会更新该用户的 InstagramID。我没有查询我正在搜索数据库然后更新所有空 InstagramID 值
标签: c# sql asp.net-core console-application