I have a piece of code to migrate data from an old app to a new app. The data represents the user's websites.
In the old app the user only had one section for websites, on which you could add any website, even social links.
In the new app, the user can add personal websites, social links (only Facebook, Twitter and LinkedIn are considered social links) and what we call custom social networks (eg. Reddit, Meetup, Tumblr, etc)
This is the code:
public async Task ImportWebsites(int userId)
{
string[] socialNetworksStr =
{
"linkedin.",
"twitter.",
"facebook.",
};
string[] customSocialNetworksStr =
{ "deviantart.",
"viadeo.",
"reddit.",
"xing.",
"pinterest.",
"tumblr.",
};
List<UserLinkDTO> personalWebsites = new List<UserLinkDTO>();
List<UserSocialNetworkDTO> socialNetworks = new List<UserSocialNetworkDTO>();
List<UserLinkDTO> customSocialNetworks = new List<UserLinkDTO>();
List<UserLinkDTO> personalWebsitesRemoved = new List<UserLinkDTO>();
using (OldContext ctx = new OldContext())
{
if (await (ctx.UserSettings.AnyAsync(u => u.UserId == userId)) == false)
throw new RelatedEntityNotFoundException($"{userId} not be found!");
personalWebsites = await ctx.PersonalWebsite.AsNoTracking()
.Where(w => w.UserId == userId)
.Select(w => new UserLinkDTO
{
UserId = w.UserId,
Description = w.PersonalWebsiteDescription,
Url = w.PersonalWebsiteURL,
Name = w.PersonalWebsiteName
}).ToListAsync().ConfigureAwait(false);
}
for (int i = 0; i < personalWebsites.Count; i++)
{
string url = personalWebsites[i].Url;
if (!url.StartsWith("http://"))
{
personalWebsites[i].Url = "http://" + url;
}
}
if (personalWebsites.Any())
{
foreach (var personalWebsite in personalWebsites)
{
foreach (var socialNetwork in socialNetworksStr)
{
if (personalWebsite.Url.Contains(socialNetwork))
{
socialNetworks.Add(new UserSocialNetworkDTO() {
SocialNetworkId = (short)(Array.IndexOf(socialNetworksStr, socialNetwork) + 1),
Account = personalWebsite.Url
});
personalWebsitesRemoved.Add(personalWebsite);
}
}
foreach (var customSocialNetwork in customSocialNetworksStr)
{
if (personalWebsite.Url.Contains(customSocialNetwork))
{
customSocialNetworks.Add(personalWebsite);
personalWebsitesRemoved.Add(personalWebsite);
}
}
}
personalWebsites = personalWebsites.Except(personalWebsitesRemoved).ToList();
var personalInfo = await PersonalInfoService.GetPersonalInfo(userId);
personalInfo.Result.PersonalWebsites = personalWebsites;
if(socialNetworks.Any()) personalInfo.Result.SocialNetworks = socialNetworks;
if(customSocialNetworks.Any()) personalInfo.Result.CustomSocialNetworks = customSocialNetworks;
var response = await PersonalInfoService.SavePersonalInfo(personalInfo.Result);
}
}
var response = await PersonalInfoService.SavePersonalInfo(personalInfo.Result);
}
My code does its job, but it takes some time, on those foreaches, and I think it's a little bit redundant, and I think it may be optimzed. How would you improve this?
PS I think I included all the necessary info, sorry If I forgot something.